diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 435ccb1..040fc5d 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,6 +4,7 @@ services: variables: GITLAB_SHARED_DIND_DIR: /builds/$CI_PROJECT_PATH/shared + GIT_SUBMODULE_STRATEGY: normal GIT_FETCH_EXTRA_FLAGS: --tags stages: diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e43a13a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "kasmweb"] + path = kasmweb + url = https://github.com/kasmtech/noVNC.git + branch = master diff --git a/builder/build_www.sh b/builder/build_www.sh index a0cd8a1..af5e321 100755 --- a/builder/build_www.sh +++ b/builder/build_www.sh @@ -14,6 +14,5 @@ cp -R ./* /build/ cd /build rm *.md rm AUTHORS -rm *.yml rm vnc.html rm vnc_lite.html diff --git a/common/network/Socket.cxx b/common/network/Socket.cxx index 9dd8bfe..78484f5 100644 --- a/common/network/Socket.cxx +++ b/common/network/Socket.cxx @@ -25,6 +25,9 @@ #include #include #define errorNumber WSAGetLastError() +#define SHUT_RD SD_RECEIVE +#define SHUT_WR SD_SEND +#define SHUT_RDWR SD_BOTH #else #define errorNumber errno #define closesocket close @@ -94,7 +97,7 @@ Socket::~Socket() void Socket::shutdown() { isShutdown_ = true; - ::shutdown(getFd(), 2); + ::shutdown(getFd(), SHUT_RDWR); } bool Socket::isShutdown() const @@ -149,7 +152,7 @@ void SocketListener::shutdown() closesocket(fd); fd = -1; #else - ::shutdown(fd, 2); + ::shutdown(fd, SHUT_RDWR); #endif } diff --git a/common/rdr/BufferedInStream.cxx b/common/rdr/BufferedInStream.cxx new file mode 100644 index 0000000..967e5a5 --- /dev/null +++ b/common/rdr/BufferedInStream.cxx @@ -0,0 +1,69 @@ +/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2020 Pierre Ossman for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +using namespace rdr; + +static const size_t DEFAULT_BUF_SIZE = 8192; + +BufferedInStream::BufferedInStream() + : bufSize(DEFAULT_BUF_SIZE), offset(0) +{ + ptr = end = start = new U8[bufSize]; +} + +BufferedInStream::~BufferedInStream() +{ + delete [] start; +} + +size_t BufferedInStream::pos() +{ + return offset + ptr - start; +} + +bool BufferedInStream::overrun(size_t needed, bool wait) +{ + if (needed > bufSize) + throw Exception("BufferedInStream overrun: " + "requested size of %lu bytes exceeds maximum of %lu bytes", + (long unsigned)needed, (long unsigned)bufSize); + + // Do we need to shuffle things around? + if ((bufSize - (ptr - start)) < needed) { + memmove(start, ptr, end - ptr); + + offset += ptr - start; + end -= ptr - start; + ptr = start; + } + + while (avail() < needed) { + if (!fillBuffer(start + bufSize - end, wait)) + return false; + } + + return true; +} diff --git a/common/rdr/BufferedInStream.h b/common/rdr/BufferedInStream.h new file mode 100644 index 0000000..acf2b92 --- /dev/null +++ b/common/rdr/BufferedInStream.h @@ -0,0 +1,54 @@ +/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2020 Pierre Ossman for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +// +// Base class for input streams with a buffer +// + +#ifndef __RDR_BUFFEREDINSTREAM_H__ +#define __RDR_BUFFEREDINSTREAM_H__ + +#include + +namespace rdr { + + class BufferedInStream : public InStream { + + public: + virtual ~BufferedInStream(); + + virtual size_t pos(); + + private: + virtual bool fillBuffer(size_t maxSize, bool wait) = 0; + + virtual bool overrun(size_t needed, bool wait); + + private: + size_t bufSize; + size_t offset; + U8* start; + + protected: + BufferedInStream(); + }; + +} // end of namespace rdr + +#endif diff --git a/common/rdr/BufferedOutStream.cxx b/common/rdr/BufferedOutStream.cxx new file mode 100644 index 0000000..ac76f6a --- /dev/null +++ b/common/rdr/BufferedOutStream.cxx @@ -0,0 +1,108 @@ +/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2011-2020 Pierre Ossman for Cendio AB + * Copyright 2017 Peter Astrand for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + + +using namespace rdr; + +static const size_t DEFAULT_BUF_SIZE = 16384; + +BufferedOutStream::BufferedOutStream() + : bufSize(DEFAULT_BUF_SIZE), offset(0) +{ + ptr = start = sentUpTo = new U8[bufSize]; + end = start + bufSize; +} + +BufferedOutStream::~BufferedOutStream() +{ + // FIXME: Complain about non-flushed buffer? + delete [] start; +} + +size_t BufferedOutStream::length() +{ + return offset + ptr - sentUpTo; +} + +size_t BufferedOutStream::bufferUsage() +{ + return ptr - sentUpTo; +} + +void BufferedOutStream::flush() +{ + while (sentUpTo < ptr) { + size_t len; + + len = bufferUsage(); + + if (!flushBuffer(false)) + break; + + offset += len - bufferUsage(); + } + + // Managed to flush everything? + if (sentUpTo == ptr) + ptr = sentUpTo = start; +} + +void BufferedOutStream::overrun(size_t needed) +{ + if (needed > bufSize) + throw Exception("BufferedOutStream overrun: " + "requested size of %lu bytes exceeds maximum of %lu bytes", + (long unsigned)needed, (long unsigned)bufSize); + + // First try to get rid of the data we have + flush(); + + // Still not enough space? + while (needed > avail()) { + // Can we shuffle things around? + // (don't do this if it gains us less than 25%) + if (((size_t)(sentUpTo - start) > bufSize / 4) && + (needed < bufSize - (ptr - sentUpTo))) { + memmove(start, sentUpTo, ptr - sentUpTo); + ptr = start + (ptr - sentUpTo); + sentUpTo = start; + } else { + size_t len; + + len = bufferUsage(); + + // Have to get rid of more data, so allow the flush to wait... + flushBuffer(true); + + offset += len - bufferUsage(); + + // Managed to flush everything? + if (sentUpTo == ptr) + ptr = sentUpTo = start; + } + } +} diff --git a/common/rdr/BufferedOutStream.h b/common/rdr/BufferedOutStream.h new file mode 100644 index 0000000..8e3229d --- /dev/null +++ b/common/rdr/BufferedOutStream.h @@ -0,0 +1,65 @@ +/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2011-2020 Pierre Ossman for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +// +// Base class for output streams with a buffer +// + +#ifndef __RDR_BUFFEREDOUTSTREAM_H__ +#define __RDR_BUFFEREDOUTSTREAM_H__ + +#include + +namespace rdr { + + class BufferedOutStream : public OutStream { + + public: + virtual ~BufferedOutStream(); + + virtual size_t length(); + virtual void flush(); + + size_t bufferUsage(); + + private: + // flushBuffer() requests that the stream be flushed. Returns true if it is + // able to progress the output (which might still not mean any bytes + // actually moved) and can be called again. If wait is true then it will + // block until all data has been written. + + virtual bool flushBuffer(bool wait) = 0; + + virtual void overrun(size_t needed); + + private: + size_t bufSize; + size_t offset; + U8* start; + + protected: + U8* sentUpTo; + + protected: + BufferedOutStream(); + }; + +} + +#endif diff --git a/common/rdr/CMakeLists.txt b/common/rdr/CMakeLists.txt index 989ba2f..78778dd 100644 --- a/common/rdr/CMakeLists.txt +++ b/common/rdr/CMakeLists.txt @@ -1,6 +1,8 @@ include_directories(${CMAKE_SOURCE_DIR}/common ${ZLIB_INCLUDE_DIRS}) add_library(rdr STATIC + BufferedInStream.cxx + BufferedOutStream.cxx Exception.cxx FdInStream.cxx FdOutStream.cxx diff --git a/common/rdr/FdInStream.cxx b/common/rdr/FdInStream.cxx index 1730d6d..27de92b 100644 --- a/common/rdr/FdInStream.cxx +++ b/common/rdr/FdInStream.cxx @@ -36,13 +36,6 @@ #include #endif -#ifndef vncmin -#define vncmin(a,b) (((a) < (b)) ? (a) : (b)) -#endif -#ifndef vncmax -#define vncmax(a,b) (((a) > (b)) ? (a) : (b)) -#endif - /* Old systems have select() in sys/time.h */ #ifdef HAVE_SYS_SELECT_H #include @@ -53,31 +46,22 @@ using namespace rdr; -enum { DEFAULT_BUF_SIZE = 8192, - MIN_BULK_SIZE = 1024 }; +enum { DEFAULT_BUF_SIZE = 8192 }; -FdInStream::FdInStream(int fd_, int timeoutms_, size_t bufSize_, +FdInStream::FdInStream(int fd_, int timeoutms_, bool closeWhenDone_) : fd(fd_), closeWhenDone(closeWhenDone_), - timeoutms(timeoutms_), blockCallback(0), - timing(false), timeWaitedIn100us(5), timedKbits(0), - bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0) + timeoutms(timeoutms_), blockCallback(0) { - ptr = end = start = new U8[bufSize]; } -FdInStream::FdInStream(int fd_, FdInStreamBlockCallback* blockCallback_, - size_t bufSize_) - : fd(fd_), timeoutms(0), blockCallback(blockCallback_), - timing(false), timeWaitedIn100us(5), timedKbits(0), - bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0) +FdInStream::FdInStream(int fd_, FdInStreamBlockCallback* blockCallback_) + : fd(fd_), timeoutms(0), blockCallback(blockCallback_) { - ptr = end = start = new U8[bufSize]; } FdInStream::~FdInStream() { - delete [] start; if (closeWhenDone) close(fd); } @@ -92,72 +76,15 @@ void FdInStream::setBlockCallback(FdInStreamBlockCallback* blockCallback_) timeoutms = 0; } -size_t FdInStream::pos() -{ - return offset + ptr - start; -} - -void FdInStream::readBytes(void* data, size_t length) -{ - if (length < MIN_BULK_SIZE) { - InStream::readBytes(data, length); - return; - } - - U8* dataPtr = (U8*)data; - - size_t n = end - ptr; - if (n > length) n = length; - - memcpy(dataPtr, ptr, n); - dataPtr += n; - length -= n; - ptr += n; - - while (length > 0) { - n = readWithTimeoutOrCallback(dataPtr, length); - dataPtr += n; - length -= n; - offset += n; - } -} - -size_t FdInStream::overrun(size_t itemSize, size_t nItems, bool wait) +bool FdInStream::fillBuffer(size_t maxSize, bool wait) { - if (itemSize > bufSize) - throw Exception("FdInStream overrun: max itemSize exceeded"); - - if (end - ptr != 0) - memmove(start, ptr, end - ptr); - - offset += ptr - start; - end -= ptr - start; - ptr = start; - - size_t bytes_to_read; - while ((size_t)(end - start) < itemSize) { - bytes_to_read = start + bufSize - end; - if (!timing) { - // When not timing, we must be careful not to read too much - // extra data into the buffer. Otherwise, the line speed - // estimation might stay at zero for a long time: All reads - // during timing=1 can be satisfied without calling - // readWithTimeoutOrCallback. However, reading only 1 or 2 bytes - // bytes is ineffecient. - bytes_to_read = vncmin(bytes_to_read, vncmax(itemSize*nItems, 8)); - } - size_t n = readWithTimeoutOrCallback((U8*)end, bytes_to_read, wait); - if (n == 0) return 0; - end += n; - } - - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; + size_t n = readWithTimeoutOrCallback((U8*)end, maxSize, wait); + if (n == 0) + return false; + end += n; - return nItems; + return true; } // @@ -175,10 +102,6 @@ size_t FdInStream::overrun(size_t itemSize, size_t nItems, bool wait) size_t FdInStream::readWithTimeoutOrCallback(void* buf, size_t len, bool wait) { - struct timeval before, after; - if (timing) - gettimeofday(&before, 0); - int n; while (true) { do { @@ -215,48 +138,5 @@ size_t FdInStream::readWithTimeoutOrCallback(void* buf, size_t len, bool wait) if (n < 0) throw SystemException("read",errno); if (n == 0) throw EndOfStream(); - if (timing) { - gettimeofday(&after, 0); - int newTimeWaited = ((after.tv_sec - before.tv_sec) * 10000 + - (after.tv_usec - before.tv_usec) / 100); - int newKbits = n * 8 / 1000; - - // limit rate to between 10kbit/s and 40Mbit/s - - if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000; - if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4; - - timeWaitedIn100us += newTimeWaited; - timedKbits += newKbits; - } - return n; } - -void FdInStream::startTiming() -{ - timing = true; - - // Carry over up to 1s worth of previous rate for smoothing. - - if (timeWaitedIn100us > 10000) { - timedKbits = timedKbits * 10000 / timeWaitedIn100us; - timeWaitedIn100us = 10000; - } -} - -void FdInStream::stopTiming() -{ - timing = false; - if (timeWaitedIn100us < timedKbits/2) - timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s -} - -unsigned int FdInStream::kbitsPerSecond() -{ - // The following calculation will overflow 32-bit arithmetic if we have - // received more than about 50Mbytes (400Mbits) since we started timing, so - // it should be OK for a single RFB update. - - return timedKbits * 10000 / timeWaitedIn100us; -} diff --git a/common/rdr/FdInStream.h b/common/rdr/FdInStream.h index d99ad3c..0203389 100644 --- a/common/rdr/FdInStream.h +++ b/common/rdr/FdInStream.h @@ -23,7 +23,7 @@ #ifndef __RDR_FDINSTREAM_H__ #define __RDR_FDINSTREAM_H__ -#include +#include namespace rdr { @@ -33,31 +33,21 @@ namespace rdr { virtual ~FdInStreamBlockCallback() {} }; - class FdInStream : public InStream { + class FdInStream : public BufferedInStream { public: - FdInStream(int fd, int timeoutms=-1, size_t bufSize=0, - bool closeWhenDone_=false); - FdInStream(int fd, FdInStreamBlockCallback* blockCallback, - size_t bufSize=0); + FdInStream(int fd, int timeoutms=-1, bool closeWhenDone_=false); + FdInStream(int fd, FdInStreamBlockCallback* blockCallback); virtual ~FdInStream(); void setTimeout(int timeoutms); void setBlockCallback(FdInStreamBlockCallback* blockCallback); int getFd() { return fd; } - size_t pos(); - void readBytes(void* data, size_t length); - - void startTiming(); - void stopTiming(); - unsigned int kbitsPerSecond(); - unsigned int timeWaited() { return timeWaitedIn100us; } - - protected: - size_t overrun(size_t itemSize, size_t nItems, bool wait); private: + virtual bool fillBuffer(size_t maxSize, bool wait); + size_t readWithTimeoutOrCallback(void* buf, size_t len, bool wait=true); int fd; @@ -65,11 +55,6 @@ namespace rdr { int timeoutms; FdInStreamBlockCallback* blockCallback; - bool timing; - unsigned int timeWaitedIn100us; - unsigned int timedKbits; - - size_t bufSize; size_t offset; U8* start; }; diff --git a/common/rdr/FdOutStream.cxx b/common/rdr/FdOutStream.cxx index f5d07e4..c4ca03f 100644 --- a/common/rdr/FdOutStream.cxx +++ b/common/rdr/FdOutStream.cxx @@ -35,6 +35,8 @@ #include #include #include +#include +#include #endif /* Old systems have select() in sys/time.h */ @@ -49,26 +51,19 @@ using namespace rdr; -enum { DEFAULT_BUF_SIZE = 16384 }; - -FdOutStream::FdOutStream(int fd_, bool blocking_, int timeoutms_, size_t bufSize_) - : fd(fd_), blocking(blocking_), timeoutms(timeoutms_), - bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0) +FdOutStream::FdOutStream(int fd_, bool blocking_, int timeoutms_) + : fd(fd_), blocking(blocking_), timeoutms(timeoutms_) { - ptr = start = sentUpTo = new U8[bufSize]; - end = start + bufSize; - gettimeofday(&lastWrite, NULL); } FdOutStream::~FdOutStream() { try { - blocking = true; - flush(); + while (sentUpTo != ptr) + flushBuffer(true); } catch (Exception&) { } - delete [] start; } void FdOutStream::setTimeout(int timeoutms_) { @@ -79,82 +74,29 @@ void FdOutStream::setBlocking(bool blocking_) { blocking = blocking_; } -size_t FdOutStream::length() -{ - return offset + ptr - sentUpTo; -} - -int FdOutStream::bufferUsage() -{ - return ptr - sentUpTo; -} - unsigned FdOutStream::getIdleTime() { return rfb::msSince(&lastWrite); } -void FdOutStream::flush() +bool FdOutStream::flushBuffer(bool wait) { - while (sentUpTo < ptr) { - size_t n = writeWithTimeout((const void*) sentUpTo, - ptr - sentUpTo, - blocking? timeoutms : 0); - - // Timeout? - if (n == 0) { - // If non-blocking then we're done here - if (!blocking) - break; - - throw TimedOut(); - } - - sentUpTo += n; - offset += n; - } - - // Managed to flush everything? - if (sentUpTo == ptr) - ptr = sentUpTo = start; -} + size_t n = writeWithTimeout((const void*) sentUpTo, + ptr - sentUpTo, + (blocking || wait)? timeoutms : 0); + // Timeout? + if (n == 0) { + // If non-blocking then we're done here + if (!blocking && !wait) + return false; -size_t FdOutStream::overrun(size_t itemSize, size_t nItems) -{ - if (itemSize > bufSize) - throw Exception("FdOutStream overrun: max itemSize exceeded"); - - // First try to get rid of the data we have - flush(); - - // Still not enough space? - if (itemSize > (size_t)(end - ptr)) { - // Can we shuffle things around? - // (don't do this if it gains us less than 25%) - if (((size_t)(sentUpTo - start) > bufSize / 4) && - (itemSize < bufSize - (ptr - sentUpTo))) { - memmove(start, sentUpTo, ptr - sentUpTo); - ptr = start + (ptr - sentUpTo); - sentUpTo = start; - } else { - // Have to get rid of more data, so turn off non-blocking - // for a bit... - bool realBlocking; - - realBlocking = blocking; - blocking = true; - flush(); - blocking = realBlocking; - } + throw TimedOut(); } - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; + sentUpTo += n; - return nItems; + return true; } // diff --git a/common/rdr/FdOutStream.h b/common/rdr/FdOutStream.h index ed84fdb..2432797 100644 --- a/common/rdr/FdOutStream.h +++ b/common/rdr/FdOutStream.h @@ -26,38 +26,29 @@ #include -#include +#include namespace rdr { - class FdOutStream : public OutStream { + class FdOutStream : public BufferedOutStream { public: - FdOutStream(int fd, bool blocking=true, int timeoutms=-1, size_t bufSize=0); + FdOutStream(int fd, bool blocking=true, int timeoutms=-1); virtual ~FdOutStream(); void setTimeout(int timeoutms); void setBlocking(bool blocking); int getFd() { return fd; } - void flush(); - size_t length(); - - int bufferUsage(); - unsigned getIdleTime(); private: - size_t overrun(size_t itemSize, size_t nItems); + virtual bool flushBuffer(bool wait); size_t writeWithTimeout(const void* data, size_t length, int timeoutms); int fd; bool blocking; int timeoutms; - size_t bufSize; - size_t offset; - U8* start; - U8* sentUpTo; struct timeval lastWrite; }; diff --git a/common/rdr/FileInStream.cxx b/common/rdr/FileInStream.cxx index bdb05a3..66dfe76 100644 --- a/common/rdr/FileInStream.cxx +++ b/common/rdr/FileInStream.cxx @@ -30,7 +30,6 @@ FileInStream::FileInStream(const char *fileName) file = fopen(fileName, "rb"); if (!file) throw SystemException("fopen", errno); - ptr = end = b; } FileInStream::~FileInStream(void) { @@ -40,50 +39,17 @@ FileInStream::~FileInStream(void) { } } -void FileInStream::reset(void) { - if (!file) - throw Exception("File is not open"); - if (fseek(file, 0, SEEK_SET) != 0) - throw SystemException("fseek", errno); - ptr = end = b; -} - -size_t FileInStream::pos() +bool FileInStream::fillBuffer(size_t maxSize, bool wait) { - if (!file) - throw Exception("File is not open"); - - return ftell(file) + ptr - b; -} - -size_t FileInStream::overrun(size_t itemSize, size_t nItems, bool wait) -{ - if (itemSize > sizeof(b)) - throw Exception("FileInStream overrun: max itemSize exceeded"); - - if (end - ptr != 0) - memmove(b, ptr, end - ptr); - - end -= ptr - b; - ptr = b; - - - while ((size_t)(end - b) < itemSize) { - size_t n = fread((U8 *)end, b + sizeof(b) - end, 1, file); - if (n == 0) { - if (ferror(file)) - throw SystemException("fread", errno); - if (feof(file)) - throw EndOfStream(); - return 0; - } - end += b + sizeof(b) - end; + size_t n = fread((U8 *)end, 1, maxSize, file); + if (n == 0) { + if (ferror(file)) + throw SystemException("fread", errno); + if (feof(file)) + throw EndOfStream(); + return false; } + end += n; - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; - - return nItems; + return true; } diff --git a/common/rdr/FileInStream.h b/common/rdr/FileInStream.h index a33c765..268f537 100644 --- a/common/rdr/FileInStream.h +++ b/common/rdr/FileInStream.h @@ -22,26 +22,21 @@ #include -#include +#include namespace rdr { - class FileInStream : public InStream { + class FileInStream : public BufferedInStream { public: FileInStream(const char *fileName); ~FileInStream(void); - void reset(void); - - size_t pos(); - - protected: - size_t overrun(size_t itemSize, size_t nItems, bool wait = true); + private: + virtual bool fillBuffer(size_t maxSize, bool wait); private: - U8 b[131072]; FILE *file; }; diff --git a/common/rdr/HexInStream.cxx b/common/rdr/HexInStream.cxx index a6bc92c..3800961 100644 --- a/common/rdr/HexInStream.cxx +++ b/common/rdr/HexInStream.cxx @@ -24,18 +24,14 @@ using namespace rdr; -const int DEFAULT_BUF_LEN = 16384; - static inline int min(int a, int b) {return a bufSize) - throw Exception("HexInStream overrun: max itemSize exceeded"); - - if (end - ptr != 0) - memmove(start, ptr, end - ptr); - - end -= ptr - start; - offset += ptr - start; - ptr = start; - - while ((size_t)(end - ptr) < itemSize) { - size_t n = in_stream.check(2, 1, wait); - if (n == 0) return 0; - const U8* iptr = in_stream.getptr(); - const U8* eptr = in_stream.getend(); - size_t length = min((eptr - iptr)/2, start + bufSize - end); +bool HexInStream::fillBuffer(size_t maxSize, bool wait) { + if (!in_stream.check(2, wait)) + return false; - U8* optr = (U8*) end; - for (size_t i=0; i +#include namespace rdr { - class HexInStream : public InStream { + class HexInStream : public BufferedInStream { public: - HexInStream(InStream& is, size_t bufSize=0); + HexInStream(InStream& is); virtual ~HexInStream(); - size_t pos(); - static bool readHexAndShift(char c, int* v); static bool hexStrToBin(const char* s, char** data, size_t* length); - protected: - size_t overrun(size_t itemSize, size_t nItems, bool wait); - private: - size_t bufSize; - U8* start; - size_t offset; + virtual bool fillBuffer(size_t maxSize, bool wait); + private: InStream& in_stream; }; diff --git a/common/rdr/HexOutStream.cxx b/common/rdr/HexOutStream.cxx index eac2eff..19c6685 100644 --- a/common/rdr/HexOutStream.cxx +++ b/common/rdr/HexOutStream.cxx @@ -25,8 +25,8 @@ const int DEFAULT_BUF_LEN = 16384; static inline size_t min(size_t a, size_t b) {return a bufSize) - throw Exception("HexOutStream overrun: max itemSize exceeded"); +void HexOutStream::overrun(size_t needed) { + if (needed > bufSize) + throw Exception("HexOutStream overrun: buffer size exceeded"); writeBuffer(); - - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; - - return nItems; } diff --git a/common/rdr/HexOutStream.h b/common/rdr/HexOutStream.h index 92442a7..0236647 100644 --- a/common/rdr/HexOutStream.h +++ b/common/rdr/HexOutStream.h @@ -26,7 +26,7 @@ namespace rdr { class HexOutStream : public OutStream { public: - HexOutStream(OutStream& os, size_t buflen=0); + HexOutStream(OutStream& os); virtual ~HexOutStream(); void flush(); @@ -37,7 +37,7 @@ namespace rdr { private: void writeBuffer(); - size_t overrun(size_t itemSize, size_t nItems); + virtual void overrun(size_t needed); OutStream& out_stream; diff --git a/common/rdr/InStream.h b/common/rdr/InStream.h index a8e515d..fc99321 100644 --- a/common/rdr/InStream.h +++ b/common/rdr/InStream.h @@ -35,28 +35,25 @@ namespace rdr { virtual ~InStream() {} - // check() ensures there is buffer data for at least one item of size - // itemSize bytes. Returns the number of items in the buffer (up to a - // maximum of nItems). If wait is false, then instead of blocking to wait - // for the bytes, zero is returned if the bytes are not immediately - // available. If itemSize or nItems is zero, check() will return zero. + // avail() returns the number of bytes that are currenctly directly + // available from the stream. - inline size_t check(size_t itemSize, size_t nItems=1, bool wait=true) + inline size_t avail() { - size_t nAvail; - - if (itemSize == 0 || nItems == 0) - return 0; + return end - ptr; + } - if (itemSize > (size_t)(end - ptr)) - return overrun(itemSize, nItems, wait); + // check() ensures there is buffer data for at least needed bytes. Returns + // true once the data is available. If wait is false, then instead of + // blocking to wait for the bytes, false is returned if the bytes are not + // immediately available. - // itemSize cannot be zero at this point - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; + inline size_t check(size_t needed, bool wait=true) + { + if (needed > avail()) + return overrun(needed, wait); - return nItems; + return true; } // checkNoWait() tries to make sure that the given number of bytes can @@ -64,10 +61,7 @@ namespace rdr { // otherwise. The length must be "small" (less than the buffer size). // If length is zero, checkNoWait() will return true. - inline bool checkNoWait(size_t length) - { - return length == 0 || check(length, 1, false) > 0; - } + inline bool checkNoWait(size_t length) { return check(length, false); } // readU/SN() methods read unsigned and signed N-bit integers. @@ -138,13 +132,12 @@ namespace rdr { private: // overrun() is implemented by a derived class to cope with buffer overrun. - // It ensures there are at least itemSize bytes of buffer data. Returns - // the number of items in the buffer (up to a maximum of nItems). itemSize - // is supposed to be "small" (a few bytes). If wait is false, then - // instead of blocking to wait for the bytes, zero is returned if the bytes - // are not immediately available. + // It ensures there are at least needed bytes of buffer data. Returns true + // once the data is available. If wait is false, then instead of blocking + // to wait for the bytes, false is returned if the bytes are not + // immediately available. - virtual size_t overrun(size_t itemSize, size_t nItems, bool wait=true) = 0; + virtual bool overrun(size_t needed, bool wait=true) = 0; protected: diff --git a/common/rdr/MemInStream.h b/common/rdr/MemInStream.h index 3e9e77b..83740dd 100644 --- a/common/rdr/MemInStream.h +++ b/common/rdr/MemInStream.h @@ -53,7 +53,7 @@ namespace rdr { private: - size_t overrun(size_t itemSize, size_t nItems, bool wait) { throw EndOfStream(); } + bool overrun(size_t needed, bool wait) { throw EndOfStream(); } const U8* start; bool deleteWhenDone; }; diff --git a/common/rdr/MemOutStream.h b/common/rdr/MemOutStream.h index b56bac3..f8b4d93 100644 --- a/common/rdr/MemOutStream.h +++ b/common/rdr/MemOutStream.h @@ -41,12 +41,6 @@ namespace rdr { delete [] start; } - void writeBytes(const void* data, size_t length) { - check(length); - memcpy(ptr, data, length); - ptr += length; - } - size_t length() { return ptr - start; } void clear() { ptr = start; }; void clearAndZero() { memset(start, 0, ptr-start); clear(); } @@ -58,11 +52,11 @@ namespace rdr { protected: - // overrun() either doubles the buffer or adds enough space for nItems of - // size itemSize bytes. + // overrun() either doubles the buffer or adds enough space for + // needed bytes. - size_t overrun(size_t itemSize, size_t nItems) { - size_t len = ptr - start + itemSize * nItems; + virtual void overrun(size_t needed) { + size_t len = ptr - start + needed; if (len < (size_t)(end - start) * 2) len = (end - start) * 2; @@ -75,8 +69,6 @@ namespace rdr { delete [] start; start = newStart; end = newStart + len; - - return nItems; } U8* start; diff --git a/common/rdr/OutStream.h b/common/rdr/OutStream.h index 0f60ccc..bb88f32 100644 --- a/common/rdr/OutStream.h +++ b/common/rdr/OutStream.h @@ -40,22 +40,20 @@ namespace rdr { virtual ~OutStream() {} - // check() ensures there is buffer space for at least one item of size - // itemSize bytes. Returns the number of items which fit (up to a maximum - // of nItems). + // avail() returns the number of bytes that currently be written to the + // stream without any risk of blocking. - inline size_t check(size_t itemSize, size_t nItems=1) + inline size_t avail() { - size_t nAvail; - - if (itemSize > (size_t)(end - ptr)) - return overrun(itemSize, nItems); + return end - ptr; + } - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; + // check() ensures there is buffer space for at least needed bytes. - return nItems; + inline void check(size_t needed) + { + if (needed > avail()) + overrun(needed); } // writeU/SN() methods write unsigned and signed N-bit integers. @@ -83,19 +81,14 @@ namespace rdr { while (bytes-- > 0) writeU8(0); } - inline void skip(size_t bytes) { - while (bytes > 0) { - size_t n = check(1, bytes); - ptr += n; - bytes -= n; - } - } - // writeBytes() writes an exact number of bytes. void writeBytes(const void* data, size_t length) { while (length > 0) { - size_t n = check(1, length); + check(1); + size_t n = length; + if (length > avail()) + n = avail(); memcpy(ptr, data, n); ptr += n; data = (U8*)data + n; @@ -107,7 +100,10 @@ namespace rdr { void copyBytes(InStream* is, size_t length) { while (length > 0) { - size_t n = check(1, length); + check(1); + size_t n = length; + if (length > avail()) + n = avail(); is->readBytes(ptr, n); ptr += n; length -= n; @@ -143,11 +139,9 @@ namespace rdr { private: // overrun() is implemented by a derived class to cope with buffer overrun. - // It ensures there are at least itemSize bytes of buffer space. Returns - // the number of items which fit (up to a maximum of nItems). itemSize is - // supposed to be "small" (a few bytes). + // It ensures there are at least needed bytes of buffer space. - virtual size_t overrun(size_t itemSize, size_t nItems) = 0; + virtual void overrun(size_t needed) = 0; protected: diff --git a/common/rdr/RandomStream.cxx b/common/rdr/RandomStream.cxx index 6c64ac5..27b33ad 100644 --- a/common/rdr/RandomStream.cxx +++ b/common/rdr/RandomStream.cxx @@ -32,15 +32,10 @@ using namespace rdr; -const size_t DEFAULT_BUF_LEN = 256; - unsigned int RandomStream::seed; RandomStream::RandomStream() - : offset(0) { - ptr = end = start = new U8[DEFAULT_BUF_LEN]; - #ifdef RFB_HAVE_WINCRYPT provider = 0; if (!CryptAcquireContext(&provider, 0, 0, PROV_RSA_FULL, 0)) { @@ -72,8 +67,6 @@ RandomStream::RandomStream() } RandomStream::~RandomStream() { - delete [] start; - #ifdef RFB_HAVE_WINCRYPT if (provider) CryptReleaseContext(provider, 0); @@ -83,50 +76,29 @@ RandomStream::~RandomStream() { #endif } -size_t RandomStream::pos() { - return offset + ptr - start; -} - -size_t RandomStream::overrun(size_t itemSize, size_t nItems, bool wait) { - if (itemSize > DEFAULT_BUF_LEN) - throw Exception("RandomStream overrun: max itemSize exceeded"); - - if (end - ptr != 0) - memmove(start, ptr, end - ptr); - - end -= ptr - start; - offset += ptr - start; - ptr = start; - - size_t length = start + DEFAULT_BUF_LEN - end; - +bool RandomStream::fillBuffer(size_t maxSize, bool wait) { #ifdef RFB_HAVE_WINCRYPT if (provider) { - if (!CryptGenRandom(provider, length, (U8*)end)) + if (!CryptGenRandom(provider, maxSize, (U8*)end)) throw rdr::SystemException("unable to CryptGenRandom", GetLastError()); - end += length; + end += maxSize; } else { #else #ifndef WIN32 if (fp) { - size_t n = fread((U8*)end, length, 1, fp); - if (n != 1) + size_t n = fread((U8*)end, 1, maxSize, fp); + if (n <= 0) throw rdr::SystemException("reading /dev/urandom or /dev/random failed", errno); - end += length; + end += n; } else { #else { #endif #endif - for (size_t i=0; i -#include +#include #ifdef WIN32 #include @@ -32,22 +32,17 @@ namespace rdr { - class RandomStream : public InStream { + class RandomStream : public BufferedInStream { public: RandomStream(); virtual ~RandomStream(); - size_t pos(); - - protected: - size_t overrun(size_t itemSize, size_t nItems, bool wait); - private: - U8* start; - size_t offset; + virtual bool fillBuffer(size_t maxSize, bool wait); + private: static unsigned int seed; #ifdef RFB_HAVE_WINCRYPT HCRYPTPROV provider; diff --git a/common/rdr/TLSInStream.cxx b/common/rdr/TLSInStream.cxx index cd81f22..70303db 100644 --- a/common/rdr/TLSInStream.cxx +++ b/common/rdr/TLSInStream.cxx @@ -30,21 +30,19 @@ #ifdef HAVE_GNUTLS using namespace rdr; -enum { DEFAULT_BUF_SIZE = 16384 }; - ssize_t TLSInStream::pull(gnutls_transport_ptr_t str, void* data, size_t size) { TLSInStream* self= (TLSInStream*) str; InStream *in = self->in; try { - if (!in->check(1, 1, false)) { + if (!in->check(1, false)) { gnutls_transport_set_errno(self->session, EAGAIN); return -1; } - if ((size_t)(in->getend() - in->getptr()) < size) - size = in->getend() - in->getptr(); + if (in->avail() < size) + size = in->avail(); in->readBytes(data, size); @@ -57,12 +55,10 @@ ssize_t TLSInStream::pull(gnutls_transport_ptr_t str, void* data, size_t size) } TLSInStream::TLSInStream(InStream* _in, gnutls_session_t _session) - : session(_session), in(_in), bufSize(DEFAULT_BUF_SIZE), offset(0) + : session(_session), in(_in) { gnutls_transport_ptr_t recv, send; - ptr = end = start = new U8[bufSize]; - gnutls_transport_set_pull_function(session, pull); gnutls_transport_get_ptr2(session, &recv, &send); gnutls_transport_set_ptr2(session, this, send); @@ -71,40 +67,16 @@ TLSInStream::TLSInStream(InStream* _in, gnutls_session_t _session) TLSInStream::~TLSInStream() { gnutls_transport_set_pull_function(session, NULL); - - delete[] start; -} - -size_t TLSInStream::pos() -{ - return offset + ptr - start; } -size_t TLSInStream::overrun(size_t itemSize, size_t nItems, bool wait) +bool TLSInStream::fillBuffer(size_t maxSize, bool wait) { - if (itemSize > bufSize) - throw Exception("TLSInStream overrun: max itemSize exceeded"); - - if (end - ptr != 0) - memmove(start, ptr, end - ptr); - - offset += ptr - start; - end -= ptr - start; - ptr = start; - - while ((size_t)(end - start) < itemSize) { - size_t n = readTLS((U8*) end, start + bufSize - end, wait); - if (!wait && n == 0) - return 0; - end += n; - } - - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; + size_t n = readTLS((U8*) end, maxSize, wait); + if (!wait && n == 0) + return false; + end += n; - return nItems; + return true; } size_t TLSInStream::readTLS(U8* buf, size_t len, bool wait) @@ -112,7 +84,7 @@ size_t TLSInStream::readTLS(U8* buf, size_t len, bool wait) int n; if (gnutls_record_check_pending(session) == 0) { - n = in->check(1, 1, wait); + n = in->check(1, wait); if (n == 0) return 0; } diff --git a/common/rdr/TLSInStream.h b/common/rdr/TLSInStream.h index 5f9dee7..9779c68 100644 --- a/common/rdr/TLSInStream.h +++ b/common/rdr/TLSInStream.h @@ -27,27 +27,22 @@ #ifdef HAVE_GNUTLS #include -#include +#include namespace rdr { - class TLSInStream : public InStream { + class TLSInStream : public BufferedInStream { public: TLSInStream(InStream* in, gnutls_session_t session); virtual ~TLSInStream(); - size_t pos(); - private: - size_t overrun(size_t itemSize, size_t nItems, bool wait); + virtual bool fillBuffer(size_t maxSize, bool wait); size_t readTLS(U8* buf, size_t len, bool wait); static ssize_t pull(gnutls_transport_ptr_t str, void* data, size_t size); gnutls_session_t session; InStream* in; - size_t bufSize; - size_t offset; - U8* start; }; }; diff --git a/common/rdr/TLSOutStream.cxx b/common/rdr/TLSOutStream.cxx index 7d7c3b5..76f5dff 100644 --- a/common/rdr/TLSOutStream.cxx +++ b/common/rdr/TLSOutStream.cxx @@ -93,19 +93,12 @@ void TLSOutStream::flush() out->flush(); } -size_t TLSOutStream::overrun(size_t itemSize, size_t nItems) +void TLSOutStream::overrun(size_t needed) { - if (itemSize > bufSize) - throw Exception("TLSOutStream overrun: max itemSize exceeded"); + if (needed > bufSize) + throw Exception("TLSOutStream overrun: buffer size exceeded"); flush(); - - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; - - return nItems; } size_t TLSOutStream::writeTLS(const U8* data, size_t length) diff --git a/common/rdr/TLSOutStream.h b/common/rdr/TLSOutStream.h index 71a7f3b..9ce6eb6 100644 --- a/common/rdr/TLSOutStream.h +++ b/common/rdr/TLSOutStream.h @@ -39,7 +39,7 @@ namespace rdr { size_t length(); protected: - size_t overrun(size_t itemSize, size_t nItems); + virtual void overrun(size_t needed); private: size_t writeTLS(const U8* data, size_t length); diff --git a/common/rdr/ZlibInStream.cxx b/common/rdr/ZlibInStream.cxx index 0fb3ad1..b9e772d 100644 --- a/common/rdr/ZlibInStream.cxx +++ b/common/rdr/ZlibInStream.cxx @@ -24,41 +24,30 @@ using namespace rdr; -enum { DEFAULT_BUF_SIZE = 16384 }; - -ZlibInStream::ZlibInStream(size_t bufSize_) - : underlying(0), bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0), - zs(NULL), bytesIn(0) +ZlibInStream::ZlibInStream() + : underlying(0), zs(NULL), bytesIn(0) { - ptr = end = start = new U8[bufSize]; init(); } ZlibInStream::~ZlibInStream() { deinit(); - delete [] start; } void ZlibInStream::setUnderlying(InStream* is, size_t bytesIn_) { underlying = is; bytesIn = bytesIn_; - ptr = end = start; -} - -size_t ZlibInStream::pos() -{ - return offset + ptr - start; + skip(avail()); } void ZlibInStream::flushUnderlying() { - ptr = end = start; - while (bytesIn > 0) { - decompress(true); - end = start; // throw away any data + if (!check(1)) + throw Exception("ZlibInStream: failed to flush remaining stream data"); + skip(avail()); } setUnderlying(NULL, 0); @@ -96,47 +85,18 @@ void ZlibInStream::deinit() zs = NULL; } -size_t ZlibInStream::overrun(size_t itemSize, size_t nItems, bool wait) -{ - if (itemSize > bufSize) - throw Exception("ZlibInStream overrun: max itemSize exceeded"); - - if (end - ptr != 0) - memmove(start, ptr, end - ptr); - - offset += ptr - start; - end -= ptr - start; - ptr = start; - - while ((size_t)(end - ptr) < itemSize) { - if (!decompress(wait)) - return 0; - } - - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; - - return nItems; -} - -// decompress() calls the decompressor once. Note that this won't necessarily -// generate any output data - it may just consume some input data. Returns -// false if wait is false and we would block on the underlying stream. - -bool ZlibInStream::decompress(bool wait) +bool ZlibInStream::fillBuffer(size_t maxSize, bool wait) { if (!underlying) throw Exception("ZlibInStream overrun: no underlying stream"); zs->next_out = (U8*)end; - zs->avail_out = start + bufSize - end; + zs->avail_out = maxSize; - size_t n = underlying->check(1, 1, wait); + size_t n = underlying->check(1, wait); if (n == 0) return false; zs->next_in = (U8*)underlying->getptr(); - zs->avail_in = underlying->getend() - underlying->getptr(); + zs->avail_in = underlying->avail(); if (zs->avail_in > bytesIn) zs->avail_in = bytesIn; diff --git a/common/rdr/ZlibInStream.h b/common/rdr/ZlibInStream.h index 08784b0..1597b54 100644 --- a/common/rdr/ZlibInStream.h +++ b/common/rdr/ZlibInStream.h @@ -24,38 +24,32 @@ #ifndef __RDR_ZLIBINSTREAM_H__ #define __RDR_ZLIBINSTREAM_H__ -#include +#include struct z_stream_s; namespace rdr { - class ZlibInStream : public InStream { + class ZlibInStream : public BufferedInStream { public: - - ZlibInStream(size_t bufSize=0); + ZlibInStream(); virtual ~ZlibInStream(); void setUnderlying(InStream* is, size_t bytesIn); void flushUnderlying(); - size_t pos(); void reset(); private: - void init(); void deinit(); - size_t overrun(size_t itemSize, size_t nItems, bool wait); - bool decompress(bool wait); + virtual bool fillBuffer(size_t maxSize, bool wait); + private: InStream* underlying; - size_t bufSize; - size_t offset; z_stream_s* zs; size_t bytesIn; - U8* start; }; } // end of namespace rdr diff --git a/common/rdr/ZlibOutStream.cxx b/common/rdr/ZlibOutStream.cxx index 1cccb2b..d58e43e 100644 --- a/common/rdr/ZlibOutStream.cxx +++ b/common/rdr/ZlibOutStream.cxx @@ -30,9 +30,9 @@ using namespace rdr; enum { DEFAULT_BUF_SIZE = 16384 }; -ZlibOutStream::ZlibOutStream(OutStream* os, size_t bufSize_, int compressLevel) +ZlibOutStream::ZlibOutStream(OutStream* os, int compressLevel) : underlying(os), compressionLevel(compressLevel), newLevel(compressLevel), - bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0) + bufSize(DEFAULT_BUF_SIZE), offset(0) { zs = new z_stream; zs->zalloc = Z_NULL; @@ -95,18 +95,18 @@ void ZlibOutStream::flush() ptr = start; } -size_t ZlibOutStream::overrun(size_t itemSize, size_t nItems) +void ZlibOutStream::overrun(size_t needed) { #ifdef ZLIBOUT_DEBUG fprintf(stderr,"zos overrun\n"); #endif - if (itemSize > bufSize) - throw Exception("ZlibOutStream overrun: max itemSize exceeded"); + if (needed > bufSize) + throw Exception("ZlibOutStream overrun: buffer size exceeded"); checkCompressionLevel(); - while ((size_t)(end - ptr) < itemSize) { + while (avail() < needed) { zs->next_in = start; zs->avail_in = ptr - start; @@ -126,13 +126,6 @@ size_t ZlibOutStream::overrun(size_t itemSize, size_t nItems) ptr -= zs->next_in - start; } } - - size_t nAvail; - nAvail = (end - ptr) / itemSize; - if (nAvail < nItems) - return nAvail; - - return nItems; } void ZlibOutStream::deflate(int flush) @@ -148,7 +141,7 @@ void ZlibOutStream::deflate(int flush) do { underlying->check(1); zs->next_out = underlying->getptr(); - zs->avail_out = underlying->getend() - underlying->getptr(); + zs->avail_out = underlying->avail(); #ifdef ZLIBOUT_DEBUG fprintf(stderr,"zos: calling deflate, avail_in %d, avail_out %d\n", diff --git a/common/rdr/ZlibOutStream.h b/common/rdr/ZlibOutStream.h index 11bb046..2b08f8d 100644 --- a/common/rdr/ZlibOutStream.h +++ b/common/rdr/ZlibOutStream.h @@ -35,7 +35,7 @@ namespace rdr { public: - ZlibOutStream(OutStream* os=0, size_t bufSize=0, int compressionLevel=-1); + ZlibOutStream(OutStream* os=0, int compressionLevel=-1); virtual ~ZlibOutStream(); void setUnderlying(OutStream* os); @@ -45,7 +45,7 @@ namespace rdr { private: - size_t overrun(size_t itemSize, size_t nItems); + virtual void overrun(size_t needed); void deflate(int flush); void checkCompressionLevel(); diff --git a/common/rfb/CConnection.cxx b/common/rfb/CConnection.cxx index ce489b1..ffb05c1 100644 --- a/common/rfb/CConnection.cxx +++ b/common/rfb/CConnection.cxx @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -42,7 +43,8 @@ CConnection::CConnection() : csecurity(0), is(0), os(0), reader_(0), writer_(0), shared(false), state_(RFBSTATE_UNINITIALISED), useProtocol3_3(false), - framebuffer(NULL), decoder(this) + framebuffer(NULL), decoder(this), + serverClipboard(NULL), hasLocalClipboard(false) { } @@ -54,6 +56,7 @@ CConnection::~CConnection() reader_ = 0; delete writer_; writer_ = 0; + strFree(serverClipboard); } void CConnection::setStreams(rdr::InStream* is_, rdr::OutStream* os_) @@ -342,6 +345,79 @@ void CConnection::dataRect(const Rect& r, int encoding) decoder.decodeRect(r, encoding, framebuffer); } +void CConnection::serverCutText(const char* str) +{ + hasLocalClipboard = false; + + strFree(serverClipboard); + serverClipboard = NULL; + + serverClipboard = latin1ToUTF8(str); + + handleClipboardAnnounce(true); +} + +void CConnection::handleClipboardCaps(rdr::U32 flags, + const rdr::U32* lengths) +{ + rdr::U32 sizes[] = { 0 }; + + CMsgHandler::handleClipboardCaps(flags, lengths); + + writer()->writeClipboardCaps(rfb::clipboardUTF8 | + rfb::clipboardRequest | + rfb::clipboardPeek | + rfb::clipboardNotify | + rfb::clipboardProvide, + sizes); +} + +void CConnection::handleClipboardRequest(rdr::U32 flags) +{ + if (!(flags & rfb::clipboardUTF8)) + return; + if (!hasLocalClipboard) + return; + handleClipboardRequest(); +} + +void CConnection::handleClipboardPeek(rdr::U32 flags) +{ + if (!hasLocalClipboard) + return; + if (cp.clipboardFlags() & rfb::clipboardNotify) + writer()->writeClipboardNotify(rfb::clipboardUTF8); +} + +void CConnection::handleClipboardNotify(rdr::U32 flags) +{ + strFree(serverClipboard); + serverClipboard = NULL; + + if (flags & rfb::clipboardUTF8) { + hasLocalClipboard = false; + handleClipboardAnnounce(true); + } else { + handleClipboardAnnounce(false); + } +} + +void CConnection::handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data) +{ + if (!(flags & rfb::clipboardUTF8)) + return; + + strFree(serverClipboard); + serverClipboard = NULL; + + serverClipboard = convertLF((const char*)data[0], lengths[0]); + + // FIXME: Should probably verify that this data was actually requested + handleClipboardData(serverClipboard); +} + void CConnection::authSuccess() { } @@ -364,3 +440,53 @@ void CConnection::fence(rdr::U32 flags, unsigned len, const char data[]) writer()->writeFence(flags, len, data); } + +void CConnection::handleClipboardRequest() +{ +} + +void CConnection::handleClipboardAnnounce(bool available) +{ +} + +void CConnection::handleClipboardData(const char* data) +{ +} + +void CConnection::requestClipboard() +{ + if (serverClipboard != NULL) { + handleClipboardData(serverClipboard); + return; + } + + if (cp.clipboardFlags() & rfb::clipboardRequest) + writer()->writeClipboardRequest(rfb::clipboardUTF8); +} + +void CConnection::announceClipboard(bool available) +{ + hasLocalClipboard = available; + + if (cp.clipboardFlags() & rfb::clipboardNotify) + writer()->writeClipboardNotify(available ? rfb::clipboardUTF8 : 0); + else { + if (available) + handleClipboardRequest(); + } +} + +void CConnection::sendClipboardData(const char* data) +{ + if (cp.clipboardFlags() & rfb::clipboardProvide) { + CharArray filtered(convertCRLF(data)); + size_t sizes[1] = { strlen(filtered.buf) + 1 }; + const rdr::U8* data[1] = { (const rdr::U8*)filtered.buf }; + writer()->writeClipboardProvide(rfb::clipboardUTF8, sizes, data); + } else { + CharArray latin1(utf8ToLatin1(data)); + + writer()->writeClientCutText(latin1.buf, strlen(latin1.buf)); + } +} + diff --git a/common/rfb/CConnection.h b/common/rfb/CConnection.h index e29c033..742c50a 100644 --- a/common/rfb/CConnection.h +++ b/common/rfb/CConnection.h @@ -107,6 +107,17 @@ namespace rfb { virtual void framebufferUpdateEnd(); virtual void dataRect(const Rect& r, int encoding); + virtual void serverCutText(const char* str); + + virtual void handleClipboardCaps(rdr::U32 flags, + const rdr::U32* lengths); + virtual void handleClipboardRequest(rdr::U32 flags); + virtual void handleClipboardPeek(rdr::U32 flags); + virtual void handleClipboardNotify(rdr::U32 flags); + virtual void handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data); + // Methods to be overridden in a derived class @@ -121,9 +132,43 @@ namespace rfb { // derived class must call on to CConnection::serverInit(). virtual void serverInit(); + // handleClipboardRequest() is called whenever the server requests + // the client to send over its clipboard data. It will only be + // called after the client has first announced a clipboard change + // via announceClipboard(). + virtual void handleClipboardRequest(); + + // handleClipboardAnnounce() is called to indicate a change in the + // clipboard on the server. Call requestClipboard() to access the + // actual data. + virtual void handleClipboardAnnounce(bool available); + + // handleClipboardData() is called when the server has sent over + // the clipboard data as a result of a previous call to + // requestClipboard(). Note that this function might never be + // called if the clipboard data was no longer available when the + // server received the request. + virtual void handleClipboardData(const char* data); + // Other methods + // requestClipboard() will result in a request to the server to + // transfer its clipboard data. A call to handleClipboardData() + // will be made once the data is available. + virtual void requestClipboard(); + + // announceClipboard() informs the server of changes to the + // clipboard on the client. The server may later request the + // clipboard data via handleClipboardRequest(). + virtual void announceClipboard(bool available); + + // sendClipboardData() transfers the clipboard data to the server + // and should be called whenever the server has requested the + // clipboard via handleClipboardRequest(). + virtual void sendClipboardData(const char* data); + + CMsgReader* reader() { return reader_; } CMsgWriter* writer() { return writer_; } @@ -190,6 +235,9 @@ namespace rfb { ModifiablePixelBuffer* framebuffer; DecodeManager decoder; + + char* serverClipboard; + bool hasLocalClipboard; }; } #endif diff --git a/common/rfb/CMsgHandler.cxx b/common/rfb/CMsgHandler.cxx index b89bc18..b831e24 100644 --- a/common/rfb/CMsgHandler.cxx +++ b/common/rfb/CMsgHandler.cxx @@ -92,3 +92,26 @@ void CMsgHandler::setLEDState(unsigned int state) { cp.setLEDState(state); } + +void CMsgHandler::handleClipboardCaps(rdr::U32 flags, const rdr::U32* lengths) +{ + cp.setClipboardCaps(flags, lengths); +} + +void CMsgHandler::handleClipboardRequest(rdr::U32 flags) +{ +} + +void CMsgHandler::handleClipboardPeek(rdr::U32 flags) +{ +} + +void CMsgHandler::handleClipboardNotify(rdr::U32 flags) +{ +} + +void CMsgHandler::handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data) +{ +} diff --git a/common/rfb/CMsgHandler.h b/common/rfb/CMsgHandler.h index 903ee15..8e640f4 100644 --- a/common/rfb/CMsgHandler.h +++ b/common/rfb/CMsgHandler.h @@ -72,6 +72,15 @@ namespace rfb { virtual void setLEDState(unsigned int state); + virtual void handleClipboardCaps(rdr::U32 flags, + const rdr::U32* lengths); + virtual void handleClipboardRequest(rdr::U32 flags); + virtual void handleClipboardPeek(rdr::U32 flags); + virtual void handleClipboardNotify(rdr::U32 flags); + virtual void handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data); + ConnParams cp; }; } diff --git a/common/rfb/CMsgWriter.cxx b/common/rfb/CMsgWriter.cxx index 44b73da..60174ea 100644 --- a/common/rfb/CMsgWriter.cxx +++ b/common/rfb/CMsgWriter.cxx @@ -18,10 +18,14 @@ */ #include #include +#include +#include + #include #include #include #include +#include #include #include #include @@ -57,7 +61,7 @@ void CMsgWriter::writeSetPixelFormat(const PixelFormat& pf) void CMsgWriter::writeSetEncodings(int nEncodings, rdr::U32* encodings) { startMsg(msgTypeSetEncodings); - os->skip(1); + os->pad(1); os->writeU16(nEncodings); for (int i = 0; i < nEncodings; i++) os->writeU32(encodings[i]); @@ -265,6 +269,104 @@ void CMsgWriter::writeClientCutText(const char* str, rdr::U32 len) endMsg(); } +void CMsgWriter::writeClipboardCaps(rdr::U32 caps, + const rdr::U32* lengths) +{ + size_t i, count; + + if (!(cp->clipboardFlags() & clipboardCaps)) + throw Exception("Server does not support clipboard \"caps\" action"); + + count = 0; + for (i = 0;i < 16;i++) { + if (caps & (1 << i)) + count++; + } + + startMsg(msgTypeClientCutText); + os->pad(3); + os->writeS32(-(4 + 4 * count)); + + os->writeU32(caps | clipboardCaps); + + count = 0; + for (i = 0;i < 16;i++) { + if (caps & (1 << i)) + os->writeU32(lengths[count++]); + } + + endMsg(); +} + +void CMsgWriter::writeClipboardRequest(rdr::U32 flags) +{ + if (!(cp->clipboardFlags() & clipboardRequest)) + throw Exception("Server does not support clipboard \"request\" action"); + + startMsg(msgTypeClientCutText); + os->pad(3); + os->writeS32(-4); + os->writeU32(flags | clipboardRequest); + endMsg(); +} + +void CMsgWriter::writeClipboardPeek(rdr::U32 flags) +{ + if (!(cp->clipboardFlags() & clipboardPeek)) + throw Exception("Server does not support clipboard \"peek\" action"); + + startMsg(msgTypeClientCutText); + os->pad(3); + os->writeS32(-4); + os->writeU32(flags | clipboardPeek); + endMsg(); +} + +void CMsgWriter::writeClipboardNotify(rdr::U32 flags) +{ + if (!(cp->clipboardFlags() & clipboardNotify)) + throw Exception("Server does not support clipboard \"notify\" action"); + + startMsg(msgTypeClientCutText); + os->pad(3); + os->writeS32(-4); + os->writeU32(flags | clipboardNotify); + endMsg(); +} + +void CMsgWriter::writeClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data) +{ + rdr::MemOutStream mos; + rdr::ZlibOutStream zos; + + int i, count; + + if (!(cp->clipboardFlags() & clipboardProvide)) + throw Exception("Server does not support clipboard \"provide\" action"); + + zos.setUnderlying(&mos); + + count = 0; + for (i = 0;i < 16;i++) { + if (!(flags & (1 << i))) + continue; + zos.writeU32(lengths[count]); + zos.writeBytes(data[count], lengths[count]); + count++; + } + + zos.flush(); + + startMsg(msgTypeClientCutText); + os->pad(3); + os->writeS32(-(4 + mos.length())); + os->writeU32(flags | clipboardProvide); + os->writeBytes(mos.data(), mos.length()); + endMsg(); +} + void CMsgWriter::startMsg(int type) { os->writeU8(type); diff --git a/common/rfb/CMsgWriter.h b/common/rfb/CMsgWriter.h index 1322186..bd999c2 100644 --- a/common/rfb/CMsgWriter.h +++ b/common/rfb/CMsgWriter.h @@ -56,6 +56,13 @@ namespace rfb { void writePointerEvent(const Point& pos, int buttonMask); void writeClientCutText(const char* str, rdr::U32 len); + void writeClipboardCaps(rdr::U32 caps, const rdr::U32* lengths); + void writeClipboardRequest(rdr::U32 flags); + void writeClipboardPeek(rdr::U32 flags); + void writeClipboardNotify(rdr::U32 flags); + void writeClipboardProvide(rdr::U32 flags, const size_t* lengths, + const rdr::U8* const* data); + protected: void startMsg(int type); void endMsg(); diff --git a/common/rfb/ConnParams.cxx b/common/rfb/ConnParams.cxx index 7942779..848712f 100644 --- a/common/rfb/ConnParams.cxx +++ b/common/rfb/ConnParams.cxx @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -36,19 +37,25 @@ ConnParams::ConnParams() width(0), height(0), useCopyRect(false), supportsLocalCursor(false), supportsLocalXCursor(false), supportsLocalCursorWithAlpha(false), + supportsCursorPosition(false), supportsDesktopResize(false), supportsExtendedDesktopSize(false), supportsDesktopRename(false), supportsLastRect(false), supportsLEDState(false), supportsQEMUKeyEvent(false), supportsWEBP(false), supportsSetDesktopSize(false), supportsFence(false), - supportsContinuousUpdates(false), + supportsContinuousUpdates(false), supportsExtendedClipboard(false), compressLevel(2), qualityLevel(-1), fineQualityLevel(-1), - subsampling(subsampleUndefined), name_(0), verStrPos(0), + subsampling(subsampleUndefined), name_(0), cursorPos_(0, 0), verStrPos(0), ledState_(ledUnknown), shandler(NULL) { memset(kasmPassed, 0, KASM_NUM_SETTINGS); setName(""); cursor_ = new Cursor(0, 0, Point(), NULL); + + clipFlags = clipboardUTF8 | clipboardRTF | clipboardHTML | + clipboardRequest | clipboardNotify | clipboardProvide; + memset(clipSizes, 0, sizeof(clipSizes)); + clipSizes[0] = 20 * 1024 * 1024; } ConnParams::~ConnParams() @@ -101,6 +108,11 @@ void ConnParams::setCursor(const Cursor& other) cursor_ = new Cursor(other); } +void ConnParams::setCursorPos(const Point& pos) +{ + cursorPos_ = pos; +} + bool ConnParams::supportsEncoding(rdr::S32 encoding) const { return encodings_.count(encoding) != 0; @@ -147,6 +159,9 @@ void ConnParams::setEncodings(int nEncodings, const rdr::S32* encodings) case pseudoEncodingExtendedDesktopSize: supportsExtendedDesktopSize = true; break; + case pseudoEncodingVMwareCursorPosition: + supportsCursorPosition = true; + break; case pseudoEncodingDesktopName: supportsDesktopRename = true; break; @@ -168,6 +183,9 @@ void ConnParams::setEncodings(int nEncodings, const rdr::S32* encodings) case pseudoEncodingContinuousUpdates: supportsContinuousUpdates = true; break; + case pseudoEncodingExtendedClipboard: + supportsExtendedClipboard = true; + break; case pseudoEncodingSubsamp1X: subsampling = subsampleNone; break; @@ -259,3 +277,17 @@ void ConnParams::setLEDState(unsigned int state) { ledState_ = state; } + +void ConnParams::setClipboardCaps(rdr::U32 flags, const rdr::U32* lengths) +{ + int i, num; + + clipFlags = flags; + + num = 0; + for (i = 0;i < 16;i++) { + if (!(flags & (1 << i))) + continue; + clipSizes[i] = lengths[num++]; + } +} diff --git a/common/rfb/ConnParams.h b/common/rfb/ConnParams.h index 7439943..39a0de0 100644 --- a/common/rfb/ConnParams.h +++ b/common/rfb/ConnParams.h @@ -84,6 +84,9 @@ namespace rfb { const Cursor& cursor() const { return *cursor_; } void setCursor(const Cursor& cursor); + const Point& cursorPos() const { return cursorPos_; } + void setCursorPos(const Point& pos); + bool supportsEncoding(rdr::S32 encoding) const; void setEncodings(int nEncodings, const rdr::S32* encodings); @@ -91,11 +94,15 @@ namespace rfb { unsigned int ledState() { return ledState_; } void setLEDState(unsigned int state); + rdr::U32 clipboardFlags() const { return clipFlags; } + void setClipboardCaps(rdr::U32 flags, const rdr::U32* lengths); + bool useCopyRect; bool supportsLocalCursor; bool supportsLocalXCursor; bool supportsLocalCursorWithAlpha; + bool supportsCursorPosition; bool supportsDesktopResize; bool supportsExtendedDesktopSize; bool supportsDesktopRename; @@ -107,6 +114,7 @@ namespace rfb { bool supportsSetDesktopSize; bool supportsFence; bool supportsContinuousUpdates; + bool supportsExtendedClipboard; int compressLevel; int qualityLevel; @@ -136,11 +144,14 @@ namespace rfb { PixelFormat pf_; char* name_; Cursor* cursor_; + Point cursorPos_; std::set encodings_; char verStr[13]; int verStrPos; unsigned int ledState_; SMsgHandler *shandler; + rdr::U32 clipFlags; + rdr::U32 clipSizes[16]; }; } #endif diff --git a/common/rfb/JpegCompressor.cxx b/common/rfb/JpegCompressor.cxx index 27cb9de..73fb078 100644 --- a/common/rfb/JpegCompressor.cxx +++ b/common/rfb/JpegCompressor.cxx @@ -85,7 +85,7 @@ JpegInitDestination(j_compress_ptr cinfo) jc->clear(); dest->pub.next_output_byte = jc->getptr(); - dest->pub.free_in_buffer = jc->getend() - jc->getptr(); + dest->pub.free_in_buffer = jc->avail(); } static boolean @@ -95,9 +95,9 @@ JpegEmptyOutputBuffer(j_compress_ptr cinfo) JpegCompressor *jc = dest->instance; jc->setptr(jc->getend()); - jc->overrun(jc->getend() - jc->getstart(), 1); + jc->check(jc->length()); dest->pub.next_output_byte = jc->getptr(); - dest->pub.free_in_buffer = jc->getend() - jc->getptr(); + dest->pub.free_in_buffer = jc->avail(); return TRUE; } diff --git a/common/rfb/JpegCompressor.h b/common/rfb/JpegCompressor.h index 9c6332b..de20173 100644 --- a/common/rfb/JpegCompressor.h +++ b/common/rfb/JpegCompressor.h @@ -47,12 +47,6 @@ namespace rfb { void writeBytes(const void*, int); - inline rdr::U8* getstart() { return start; } - - virtual inline size_t overrun(size_t itemSize, size_t nItems) { - return MemOutStream::overrun(itemSize, nItems); - } - private: struct jpeg_compress_struct *cinfo; diff --git a/common/rfb/SConnection.cxx b/common/rfb/SConnection.cxx index 6b81055..bd1ea45 100644 --- a/common/rfb/SConnection.cxx +++ b/common/rfb/SConnection.cxx @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -52,7 +53,8 @@ SConnection::SConnection() : readyForSetColourMapEntries(false), is(0), os(0), reader_(0), writer_(0), ssecurity(0), state_(RFBSTATE_UNINITIALISED), - preferredEncoding(encodingRaw) + preferredEncoding(encodingRaw), + clientClipboard(NULL), hasLocalClipboard(false) { defaultMajorVersion = 3; defaultMinorVersion = 8; @@ -69,6 +71,7 @@ SConnection::~SConnection() reader_ = 0; delete writer_; writer_ = 0; + strFree(clientClipboard); } void SConnection::setStreams(rdr::InStream* is_, rdr::OutStream* os_) @@ -281,6 +284,73 @@ void SConnection::setEncodings(int nEncodings, const rdr::S32* encodings) } SMsgHandler::setEncodings(nEncodings, encodings); + + if (cp.supportsExtendedClipboard) { + rdr::U32 sizes[] = { 0 }; + writer()->writeClipboardCaps(rfb::clipboardUTF8 | + rfb::clipboardRequest | + rfb::clipboardPeek | + rfb::clipboardNotify | + rfb::clipboardProvide, + sizes); + } +} + +void SConnection::clientCutText(const char* str, int len) +{ + hasLocalClipboard = false; + + strFree(clientClipboard); + clientClipboard = NULL; + + clientClipboard = latin1ToUTF8(str); + + handleClipboardAnnounce(true); +} + +void SConnection::handleClipboardRequest(rdr::U32 flags) +{ + if (!(flags & rfb::clipboardUTF8)) + return; + if (!hasLocalClipboard) + return; + handleClipboardRequest(); +} + +void SConnection::handleClipboardPeek(rdr::U32 flags) +{ + if (!hasLocalClipboard) + return; + if (cp.clipboardFlags() & rfb::clipboardNotify) + writer()->writeClipboardNotify(rfb::clipboardUTF8); +} + +void SConnection::handleClipboardNotify(rdr::U32 flags) +{ + strFree(clientClipboard); + clientClipboard = NULL; + + if (flags & rfb::clipboardUTF8) { + handleClipboardAnnounce(true); + hasLocalClipboard = false; + } else { + handleClipboardAnnounce(false); + } +} + +void SConnection::handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data) +{ + if (!(flags & rfb::clipboardUTF8)) + return; + + strFree(clientClipboard); + clientClipboard = NULL; + + clientClipboard = convertLF((const char*)data[0], lengths[0]); + + handleClipboardData(clientClipboard, strlen(clientClipboard)); } void SConnection::supportsQEMUKeyEvent() @@ -375,6 +445,58 @@ void SConnection::enableContinuousUpdates(bool enable, { } +void SConnection::handleClipboardRequest() +{ +} + +void SConnection::handleClipboardAnnounce(bool available) +{ +} + +void SConnection::handleClipboardData(const char* data, int len) +{ +} + +void SConnection::requestClipboard() +{ + if (clientClipboard != NULL) { + handleClipboardData(clientClipboard, strlen(clientClipboard)); + return; + } + + if (cp.supportsExtendedClipboard && + (cp.clipboardFlags() & rfb::clipboardRequest)) + writer()->writeClipboardRequest(rfb::clipboardUTF8); +} + +void SConnection::announceClipboard(bool available) +{ + hasLocalClipboard = available; + + if (cp.supportsExtendedClipboard && + (cp.clipboardFlags() & rfb::clipboardNotify)) + writer()->writeClipboardNotify(available ? rfb::clipboardUTF8 : 0); + else { + if (available) + handleClipboardRequest(); + } +} + +void SConnection::sendClipboardData(const char* data, int len) +{ + if (cp.supportsExtendedClipboard && + (cp.clipboardFlags() & rfb::clipboardProvide)) { + CharArray filtered(convertCRLF(data)); + size_t sizes[1] = { strlen(filtered.buf) + 1 }; + const rdr::U8* data[1] = { (const rdr::U8*)filtered.buf }; + writer()->writeClipboardProvide(rfb::clipboardUTF8, sizes, data); + } else { + CharArray latin1(utf8ToLatin1(data)); + + writer()->writeServerCutText(latin1.buf, strlen(latin1.buf)); + } +} + void SConnection::writeFakeColourMap(void) { int i; diff --git a/common/rfb/SConnection.h b/common/rfb/SConnection.h index 392182e..4f8e4c7 100644 --- a/common/rfb/SConnection.h +++ b/common/rfb/SConnection.h @@ -73,6 +73,15 @@ namespace rfb { virtual void setEncodings(int nEncodings, const rdr::S32* encodings); + virtual void clientCutText(const char* str, int len); + + virtual void handleClipboardRequest(rdr::U32 flags); + virtual void handleClipboardPeek(rdr::U32 flags); + virtual void handleClipboardNotify(rdr::U32 flags); + virtual void handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data); + virtual void supportsQEMUKeyEvent(); // Methods to be overridden in a derived class @@ -118,6 +127,25 @@ namespace rfb { virtual void enableContinuousUpdates(bool enable, int x, int y, int w, int h); + // handleClipboardRequest() is called whenever the client requests + // the server to send over its clipboard data. It will only be + // called after the server has first announced a clipboard change + // via announceClipboard(). + virtual void handleClipboardRequest(); + + // handleClipboardAnnounce() is called to indicate a change in the + // clipboard on the client. Call requestClipboard() to access the + // actual data. + virtual void handleClipboardAnnounce(bool available); + + // handleClipboardData() is called when the client has sent over + // the clipboard data as a result of a previous call to + // requestClipboard(). Note that this function might never be + // called if the clipboard data was no longer available when the + // client received the request. + virtual void handleClipboardData(const char* data, int len); + + virtual void add_changed_all() {} // setAccessRights() allows a security package to limit the access rights @@ -138,6 +166,22 @@ namespace rfb { // Other methods + // requestClipboard() will result in a request to the client to + // transfer its clipboard data. A call to handleClipboardData() + // will be made once the data is available. + virtual void requestClipboard(); + + // announceClipboard() informs the client of changes to the + // clipboard on the server. The client may later request the + // clipboard data via handleClipboardRequest(). + virtual void announceClipboard(bool available); + + // sendClipboardData() transfers the clipboard data to the client + // and should be called whenever the client has requested the + // clipboard via handleClipboardRequest(). + virtual void sendClipboardData(const char* data, int len); + + // authenticated() returns true if the client has authenticated // successfully. bool authenticated() { return (state_ == RFBSTATE_INITIALISATION || @@ -203,6 +247,9 @@ namespace rfb { SSecurity* ssecurity; stateEnum state_; rdr::S32 preferredEncoding; + + char* clientClipboard; + bool hasLocalClipboard; }; } #endif diff --git a/common/rfb/SDesktop.h b/common/rfb/SDesktop.h index 717ddbc..ec833c3 100644 --- a/common/rfb/SDesktop.h +++ b/common/rfb/SDesktop.h @@ -77,6 +77,25 @@ namespace rfb { // pointerEvent(), keyEvent() and clientCutText() are called in response to // the relevant RFB protocol messages from clients. // See InputHandler for method signatures. + + // handleClipboardRequest() is called whenever a client requests + // the server to send over its clipboard data. It will only be + // called after the server has first announced a clipboard change + // via VNCServer::announceClipboard(). + virtual void handleClipboardRequest() {} + + // handleClipboardAnnounce() is called to indicate a change in the + // clipboard on a client. Call VNCServer::requestClipboard() to + // access the actual data. + virtual void handleClipboardAnnounce(bool __unused_attr available) {} + + // handleClipboardData() is called when a client has sent over + // the clipboard data as a result of a previous call to + // VNCServer::requestClipboard(). Note that this function might + // never be called if the clipboard data was no longer available + // when the client received the request. + virtual void handleClipboardData(const char* __unused_attr data, int len __unused_attr) {} + protected: virtual ~SDesktop() {} }; diff --git a/common/rfb/SMsgHandler.cxx b/common/rfb/SMsgHandler.cxx index 78ece78..29c33ea 100644 --- a/common/rfb/SMsgHandler.cxx +++ b/common/rfb/SMsgHandler.cxx @@ -64,6 +64,29 @@ void SMsgHandler::setEncodings(int nEncodings, const rdr::S32* encodings) supportsQEMUKeyEvent(); } +void SMsgHandler::handleClipboardCaps(rdr::U32 flags, const rdr::U32* lengths) +{ + cp.setClipboardCaps(flags, lengths); +} + +void SMsgHandler::handleClipboardRequest(rdr::U32 flags) +{ +} + +void SMsgHandler::handleClipboardPeek(rdr::U32 flags) +{ +} + +void SMsgHandler::handleClipboardNotify(rdr::U32 flags) +{ +} + +void SMsgHandler::handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data) +{ +} + void SMsgHandler::supportsLocalCursor() { } diff --git a/common/rfb/SMsgHandler.h b/common/rfb/SMsgHandler.h index a169621..8b7a9ad 100644 --- a/common/rfb/SMsgHandler.h +++ b/common/rfb/SMsgHandler.h @@ -54,6 +54,15 @@ namespace rfb { virtual void enableContinuousUpdates(bool enable, int x, int y, int w, int h) = 0; + virtual void handleClipboardCaps(rdr::U32 flags, + const rdr::U32* lengths); + virtual void handleClipboardRequest(rdr::U32 flags); + virtual void handleClipboardPeek(rdr::U32 flags); + virtual void handleClipboardNotify(rdr::U32 flags); + virtual void handleClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data); + virtual void sendStats() = 0; virtual bool canChangeKasmSettings() const = 0; diff --git a/common/rfb/SMsgReader.cxx b/common/rfb/SMsgReader.cxx index a71272a..11655b6 100644 --- a/common/rfb/SMsgReader.cxx +++ b/common/rfb/SMsgReader.cxx @@ -18,8 +18,11 @@ */ #include #include +#include + #include #include +#include #include #include #include @@ -224,11 +227,15 @@ void SMsgReader::readPointerEvent() void SMsgReader::readClientCutText() { is->skip(3); - int len = is->readU32(); - if (len < 0) { - throw Exception("Cut text too long."); + rdr::U32 len = is->readU32(); + + if (len & 0x80000000) { + rdr::S32 slen = len; + slen = -slen; + readExtendedClipboard(slen); + return; } - if (len > maxCutText) { + if (len > (size_t)maxCutText) { is->skip(len); vlog.error("Cut text too long (%d bytes) - ignoring", len); return; @@ -239,6 +246,100 @@ void SMsgReader::readClientCutText() handler->clientCutText(ca.buf, len); } +void SMsgReader::readExtendedClipboard(rdr::S32 len) +{ + rdr::U32 flags; + rdr::U32 action; + + if (len < 4) + throw Exception("Invalid extended clipboard message"); + if (len > maxCutText) { + vlog.error("Extended clipboard message too long (%d bytes) - ignoring", len); + is->skip(len); + return; + } + + flags = is->readU32(); + action = flags & clipboardActionMask; + + if (action & clipboardCaps) { + int i; + size_t num; + rdr::U32 lengths[16]; + + num = 0; + for (i = 0;i < 16;i++) { + if (flags & (1 << i)) + num++; + } + + if (len < (rdr::S32)(4 + 4*num)) + throw Exception("Invalid extended clipboard message"); + + num = 0; + for (i = 0;i < 16;i++) { + if (flags & (1 << i)) + lengths[num++] = is->readU32(); + } + + handler->handleClipboardCaps(flags, lengths); + } else if (action == clipboardProvide) { + rdr::ZlibInStream zis; + + int i; + size_t num; + size_t lengths[16]; + rdr::U8* buffers[16]; + + zis.setUnderlying(is, len - 4); + + num = 0; + for (i = 0;i < 16;i++) { + if (!(flags & 1 << i)) + continue; + + lengths[num] = zis.readU32(); + if (lengths[num] > (size_t)maxCutText) { + vlog.error("Extended clipboard data too long (%d bytes) - ignoring", + (unsigned)lengths[num]); + zis.skip(lengths[num]); + flags &= ~(1 << i); + continue; + } + + buffers[num] = new rdr::U8[lengths[num]]; + zis.readBytes(buffers[num], lengths[num]); + num++; + } + + zis.flushUnderlying(); + zis.setUnderlying(NULL, 0); + + handler->handleClipboardProvide(flags, lengths, buffers); + + num = 0; + for (i = 0;i < 16;i++) { + if (!(flags & 1 << i)) + continue; + delete [] buffers[num++]; + } + } else { + switch (action) { + case clipboardRequest: + handler->handleClipboardRequest(flags); + break; + case clipboardPeek: + handler->handleClipboardPeek(flags); + break; + case clipboardNotify: + handler->handleClipboardNotify(flags); + break; + default: + throw Exception("Invalid extended clipboard action"); + } + } +} + void SMsgReader::readRequestStats() { is->skip(3); diff --git a/common/rfb/SMsgReader.h b/common/rfb/SMsgReader.h index ebeee84..ec0035b 100644 --- a/common/rfb/SMsgReader.h +++ b/common/rfb/SMsgReader.h @@ -55,6 +55,7 @@ namespace rfb { void readKeyEvent(); void readPointerEvent(); void readClientCutText(); + void readExtendedClipboard(rdr::S32 len); void readRequestStats(); void readQEMUMessage(); diff --git a/common/rfb/SMsgWriter.cxx b/common/rfb/SMsgWriter.cxx index 07622fd..3d46e2d 100644 --- a/common/rfb/SMsgWriter.cxx +++ b/common/rfb/SMsgWriter.cxx @@ -19,8 +19,12 @@ */ #include #include +#include +#include + #include #include +#include #include #include #include @@ -39,6 +43,7 @@ SMsgWriter::SMsgWriter(ConnParams* cp_, rdr::OutStream* os_) needSetDesktopSize(false), needExtendedDesktopSize(false), needSetDesktopName(false), needSetCursor(false), needSetXCursor(false), needSetCursorWithAlpha(false), + needCursorPos(false), needLEDState(false), needQEMUKeyEvent(false) { } @@ -88,6 +93,112 @@ void SMsgWriter::writeServerCutText(const char* str, int len) endMsg(); } +void SMsgWriter::writeClipboardCaps(rdr::U32 caps, + const rdr::U32* lengths) +{ + size_t i, count; + + if (!cp->supportsExtendedClipboard) + throw Exception("Client does not support extended clipboard"); + + count = 0; + for (i = 0;i < 16;i++) { + if (caps & (1 << i)) + count++; + } + + startMsg(msgTypeServerCutText); + os->pad(3); + os->writeS32(-(4 + 4 * count)); + + os->writeU32(caps | clipboardCaps); + + count = 0; + for (i = 0;i < 16;i++) { + if (caps & (1 << i)) + os->writeU32(lengths[count++]); + } + + endMsg(); +} + +void SMsgWriter::writeClipboardRequest(rdr::U32 flags) +{ + if (!cp->supportsExtendedClipboard) + throw Exception("Client does not support extended clipboard"); + if (!(cp->clipboardFlags() & clipboardRequest)) + throw Exception("Client does not support clipboard \"request\" action"); + + startMsg(msgTypeServerCutText); + os->pad(3); + os->writeS32(-4); + os->writeU32(flags | clipboardRequest); + endMsg(); +} + +void SMsgWriter::writeClipboardPeek(rdr::U32 flags) +{ + if (!cp->supportsExtendedClipboard) + throw Exception("Client does not support extended clipboard"); + if (!(cp->clipboardFlags() & clipboardPeek)) + throw Exception("Client does not support clipboard \"peek\" action"); + + startMsg(msgTypeServerCutText); + os->pad(3); + os->writeS32(-4); + os->writeU32(flags | clipboardPeek); + endMsg(); +} + +void SMsgWriter::writeClipboardNotify(rdr::U32 flags) +{ + if (!cp->supportsExtendedClipboard) + throw Exception("Client does not support extended clipboard"); + if (!(cp->clipboardFlags() & clipboardNotify)) + throw Exception("Client does not support clipboard \"notify\" action"); + + startMsg(msgTypeServerCutText); + os->pad(3); + os->writeS32(-4); + os->writeU32(flags | clipboardNotify); + endMsg(); +} + +void SMsgWriter::writeClipboardProvide(rdr::U32 flags, + const size_t* lengths, + const rdr::U8* const* data) +{ + rdr::MemOutStream mos; + rdr::ZlibOutStream zos; + + int i, count; + + if (!cp->supportsExtendedClipboard) + throw Exception("Client does not support extended clipboard"); + if (!(cp->clipboardFlags() & clipboardProvide)) + throw Exception("Client does not support clipboard \"provide\" action"); + + zos.setUnderlying(&mos); + + count = 0; + for (i = 0;i < 16;i++) { + if (!(flags & (1 << i))) + continue; + zos.writeU32(lengths[count]); + zos.writeBytes(data[count], lengths[count]); + count++; + } + + zos.flush(); + + startMsg(msgTypeServerCutText); + os->pad(3); + os->writeS32(-(4 + mos.length())); + os->writeU32(flags | clipboardProvide); + os->writeBytes(mos.data(), mos.length()); + endMsg(); +} + void SMsgWriter::writeStats(const char* str, int len) { startMsg(msgTypeStats); @@ -204,6 +315,14 @@ bool SMsgWriter::writeSetCursorWithAlpha() return true; } +void SMsgWriter::writeCursorPos() +{ + if (!cp->supportsEncoding(pseudoEncodingVMwareCursorPosition)) + throw Exception("Client does not support cursor position"); + + needCursorPos = true; +} + bool SMsgWriter::writeLEDState() { if (!cp->supportsLEDState) @@ -232,6 +351,8 @@ bool SMsgWriter::needFakeUpdate() return true; if (needSetCursor || needSetXCursor || needSetCursorWithAlpha) return true; + if (needCursorPos) + return true; if (needLEDState) return true; if (needQEMUKeyEvent) @@ -284,6 +405,8 @@ void SMsgWriter::writeFramebufferUpdateStart(int nRects) nRects++; if (needSetCursorWithAlpha) nRects++; + if (needCursorPos) + nRects++; if (needLEDState) nRects++; if (needQEMUKeyEvent) @@ -399,6 +522,18 @@ void SMsgWriter::writePseudoRects() needSetCursorWithAlpha = false; } + if (needCursorPos) { + const Point& cursorPos = cp->cursorPos(); + + if (cp->supportsEncoding(pseudoEncodingVMwareCursorPosition)) { + writeSetVMwareCursorPositionRect(cursorPos.x, cursorPos.y); + } else { + throw Exception("Client does not support cursor position"); + } + + needCursorPos = false; + } + if (needSetDesktopName) { writeSetDesktopNameRect(cp->name()); needSetDesktopName = false; @@ -577,6 +712,20 @@ void SMsgWriter::writeSetCursorWithAlphaRect(int width, int height, } } +void SMsgWriter::writeSetVMwareCursorPositionRect(int hotspotX, int hotspotY) +{ + if (!cp->supportsEncoding(pseudoEncodingVMwareCursorPosition)) + throw Exception("Client does not support cursor position"); + if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) + throw Exception("SMsgWriter::writeSetVMwareCursorRect: nRects out of sync"); + + os->writeS16(hotspotX); + os->writeS16(hotspotY); + os->writeU16(0); + os->writeU16(0); + os->writeU32(pseudoEncodingVMwareCursorPosition); +} + void SMsgWriter::writeLEDStateRect(rdr::U8 state) { if (!cp->supportsLEDState) diff --git a/common/rfb/SMsgWriter.h b/common/rfb/SMsgWriter.h index 6945ba4..f561136 100644 --- a/common/rfb/SMsgWriter.h +++ b/common/rfb/SMsgWriter.h @@ -55,6 +55,14 @@ namespace rfb { // writeBell() and writeServerCutText() do the obvious thing. void writeBell(); void writeServerCutText(const char* str, int len); + + void writeClipboardCaps(rdr::U32 caps, const rdr::U32* lengths); + void writeClipboardRequest(rdr::U32 flags); + void writeClipboardPeek(rdr::U32 flags); + void writeClipboardNotify(rdr::U32 flags); + void writeClipboardProvide(rdr::U32 flags, const size_t* lengths, + const rdr::U8* const* data); + void writeStats(const char* str, int len); // writeFence() sends a new fence request or response to the client. @@ -83,6 +91,9 @@ namespace rfb { bool writeSetXCursor(); bool writeSetCursorWithAlpha(); + // Notifies the client that the cursor pointer was moved by the server. + void writeCursorPos(); + // Same for LED state message bool writeLEDState(); @@ -138,6 +149,7 @@ namespace rfb { void writeSetCursorWithAlphaRect(int width, int height, int hotspotX, int hotspotY, const rdr::U8* data); + void writeSetVMwareCursorPositionRect(int hotspotX, int hotspotY); void writeLEDStateRect(rdr::U8 state); void writeQEMUKeyEventRect(); @@ -153,6 +165,7 @@ namespace rfb { bool needSetCursor; bool needSetXCursor; bool needSetCursorWithAlpha; + bool needCursorPos; bool needLEDState; bool needQEMUKeyEvent; diff --git a/common/rfb/Timer.h b/common/rfb/Timer.h index ef50972..ddfce1b 100644 --- a/common/rfb/Timer.h +++ b/common/rfb/Timer.h @@ -35,6 +35,8 @@ namespace rfb { dispatch elapsed Timer callbacks and to determine how long to wait in select() for the next timeout to occur. + For classes that can be derived it's best to use MethodTimer which can call a specific + method on the class, thus avoiding conflicts when subclassing. */ struct Timer { @@ -101,6 +103,19 @@ namespace rfb { static std::list pending; }; + template class MethodTimer + : public Timer, public Timer::Callback { + public: + MethodTimer(T* obj_, bool (T::*cb_)(Timer*)) + : Timer(this), obj(obj_), cb(cb_) {} + + virtual bool handleTimeout(Timer* t) { return (obj->*cb)(t); } + + private: + T* obj; + bool (T::*cb)(Timer*); + }; + }; #endif diff --git a/common/rfb/VNCSConnectionST.cxx b/common/rfb/VNCSConnectionST.cxx index 31bd16e..0ad5d49 100644 --- a/common/rfb/VNCSConnectionST.cxx +++ b/common/rfb/VNCSConnectionST.cxx @@ -155,6 +155,17 @@ void VNCSConnectionST::close(const char* reason) server->lastDisconnectTime = time(0); } + try { + if (sock->outStream().bufferUsage() > 0) { + sock->cork(false); + sock->outStream().flush(); + if (sock->outStream().bufferUsage() > 0) + vlog.error("Failed to flush remaining socket data on close"); + } + } catch (rdr::Exception& e) { + vlog.error("Failed to flush remaining socket data on close: %s", e.str()); + } + // Just shutdown the socket and mark our state as closing. Eventually the // calling code will call VNCServerST's removeSocket() method causing us to // be deleted. @@ -392,7 +403,31 @@ static void keylog(unsigned keysym, const char *client) { flushKeylog(client); } -void VNCSConnectionST::serverCutTextOrClose(const char *str, int len) +void VNCSConnectionST::requestClipboardOrClose() +{ + try { + if (!(accessRights & AccessCutText)) return; + if (!rfb::Server::acceptCutText) return; + if (state() != RFBSTATE_NORMAL) return; + requestClipboard(); + } catch(rdr::Exception& e) { + close(e.str()); + } +} + +void VNCSConnectionST::announceClipboardOrClose(bool available) +{ + try { + if (!(accessRights & AccessCutText)) return; + if (!rfb::Server::sendCutText) return; + if (state() != RFBSTATE_NORMAL) return; + announceClipboard(available); + } catch(rdr::Exception& e) { + close(e.str()); + } +} + +void VNCSConnectionST::sendClipboardDataOrClose(const char* data) { try { if (!(accessRights & AccessCutText)) return; @@ -402,19 +437,19 @@ void VNCSConnectionST::serverCutTextOrClose(const char *str, int len) sock->getPeerAddress()); return; } + int len = strlen(data); const int origlen = len; if (rfb::Server::DLP_ClipSendMax && len > rfb::Server::DLP_ClipSendMax) len = rfb::Server::DLP_ClipSendMax; - cliplog(str, len, origlen, "sent", sock->getPeerAddress()); - if (state() == RFBSTATE_NORMAL) - writer()->writeServerCutText(str, len); + cliplog(data, len, origlen, "sent", sock->getPeerAddress()); + if (state() != RFBSTATE_NORMAL) return; + sendClipboardData(data, len); gettimeofday(&lastClipboardOp, NULL); } catch(rdr::Exception& e) { close(e.str()); } } - void VNCSConnectionST::setDesktopNameOrClose(const char *name) { try { @@ -506,6 +541,15 @@ void VNCSConnectionST::renderedCursorChange() } } +// cursorPositionChange() is called whenever the cursor has changed position by +// the server. If the client supports being informed about these changes then +// it will arrange for the new cursor position to be sent to the client. + +void VNCSConnectionST::cursorPositionChange() +{ + setCursorPos(); +} + // needRenderedCursor() returns true if this client needs the server-side // rendered cursor. This may be because it does not support local cursor or // because the current cursor position has not been set by this client. @@ -826,24 +870,6 @@ void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) { server->desktop->keyEvent(keysym, keycode, down); } -void VNCSConnectionST::clientCutText(const char* str, int len) -{ - if (!(accessRights & AccessCutText)) return; - if (!rfb::Server::acceptCutText) return; - if (msSince(&lastClipboardOp) < (unsigned) rfb::Server::DLP_ClipDelay) { - vlog.info("DLP: client %s: refused to receive clipboard, too soon", - sock->getPeerAddress()); - return; - } - const int origlen = len; - if (rfb::Server::DLP_ClipAcceptMax && len > rfb::Server::DLP_ClipAcceptMax) - len = rfb::Server::DLP_ClipAcceptMax; - cliplog(str, len, origlen, "received", sock->getPeerAddress()); - - gettimeofday(&lastClipboardOp, NULL); - server->desktop->clientCutText(str, len); -} - void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental) { Rect safeRect; @@ -863,7 +889,7 @@ void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental) // Just update the requested region. // Framebuffer update will be sent a bit later, see processMessages(). - Region reqRgn(r); + Region reqRgn(safeRect); if (!incremental || !continuousUpdates) requested.assign_union(reqRgn); @@ -977,6 +1003,38 @@ void VNCSConnectionST::enableContinuousUpdates(bool enable, } } +void VNCSConnectionST::handleClipboardRequest() +{ + if (!(accessRights & AccessCutText)) return; + server->handleClipboardRequest(this); +} + +void VNCSConnectionST::handleClipboardAnnounce(bool available) +{ + if (!(accessRights & AccessCutText)) return; + if (!rfb::Server::acceptCutText) return; + server->handleClipboardAnnounce(this, available); +} + +void VNCSConnectionST::handleClipboardData(const char* data, int len) +{ + if (!(accessRights & AccessCutText)) return; + if (!rfb::Server::acceptCutText) return; + if (msSince(&lastClipboardOp) < (unsigned) rfb::Server::DLP_ClipDelay) { + vlog.info("DLP: client %s: refused to receive clipboard, too soon", + sock->getPeerAddress()); + return; + } + const int origlen = len; + if (rfb::Server::DLP_ClipAcceptMax && len > rfb::Server::DLP_ClipAcceptMax) + len = rfb::Server::DLP_ClipAcceptMax; + cliplog(data, len, origlen, "received", sock->getPeerAddress()); + + gettimeofday(&lastClipboardOp, NULL); + server->handleClipboardData(this, data, len); +} + + // supportsLocalCursor() is called whenever the status of // cp.supportsLocalCursor has changed. If the client does now support local // cursor, we make sure that the old server-side rendered cursor is cleaned up @@ -1471,6 +1529,21 @@ void VNCSConnectionST::setCursor() } } +// setCursorPos() is called whenever the cursor has changed position by the +// server. If the client supports being informed about these changes then it +// will arrange for the new cursor position to be sent to the client. + +void VNCSConnectionST::setCursorPos() +{ + if (state() != RFBSTATE_NORMAL) + return; + + if (cp.supportsCursorPosition) { + cp.setCursorPos(server->cursorPos); + writer()->writeCursorPos(); + } +} + void VNCSConnectionST::setDesktopName(const char *name) { cp.setName(name); diff --git a/common/rfb/VNCSConnectionST.h b/common/rfb/VNCSConnectionST.h index d1e1267..1bc6ba5 100644 --- a/common/rfb/VNCSConnectionST.h +++ b/common/rfb/VNCSConnectionST.h @@ -75,9 +75,11 @@ namespace rfb { void screenLayoutChangeOrClose(rdr::U16 reason); void setCursorOrClose(); void bellOrClose(); - void serverCutTextOrClose(const char *str, int len); void setDesktopNameOrClose(const char *name); void setLEDStateOrClose(unsigned int state); + void requestClipboardOrClose(); + void announceClipboardOrClose(bool available); + void sendClipboardDataOrClose(const char* data); // checkIdleTimeout() returns the number of milliseconds left until the // idle timeout expires. If it has expired, the connection is closed and @@ -97,6 +99,11 @@ namespace rfb { // cursor. void renderedCursorChange(); + // cursorPositionChange() is called whenever the cursor has changed position by + // the server. If the client supports being informed about these changes then + // it will arrange for the new cursor position to be sent to the client. + void cursorPositionChange(); + // needRenderedCursor() returns true if this client needs the server-side // rendered cursor. This may be because it does not support local cursor // or because the current cursor position has not been set by this client. @@ -170,13 +177,15 @@ namespace rfb { virtual void setPixelFormat(const PixelFormat& pf); virtual void pointerEvent(const Point& pos, int buttonMask, const bool skipClick, const bool skipRelease); virtual void keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down); - virtual void clientCutText(const char* str, int len); virtual void framebufferUpdateRequest(const Rect& r, bool incremental); virtual void setDesktopSize(int fb_width, int fb_height, const ScreenSet& layout); virtual void fence(rdr::U32 flags, unsigned len, const char data[]); virtual void enableContinuousUpdates(bool enable, int x, int y, int w, int h); + virtual void handleClipboardRequest(); + virtual void handleClipboardAnnounce(bool available); + virtual void handleClipboardData(const char* data, int len); virtual void supportsLocalCursor(); virtual void supportsFence(); virtual void supportsContinuousUpdates(); @@ -223,6 +232,7 @@ namespace rfb { void screenLayoutChange(rdr::U16 reason); void setCursor(); + void setCursorPos(); void setDesktopName(const char *name); void setLEDState(unsigned int state); void setSocketTimeouts(); diff --git a/common/rfb/VNCServer.h b/common/rfb/VNCServer.h index c5335ad..d2e0fa2 100644 --- a/common/rfb/VNCServer.h +++ b/common/rfb/VNCServer.h @@ -52,9 +52,21 @@ namespace rfb { // getPixelBuffer() returns a pointer to the PixelBuffer object. virtual PixelBuffer* getPixelBuffer() const = 0; - // serverCutText() tells the server that the cut text has changed. This - // will normally be sent to all clients. - virtual void serverCutText(const char* str, int len) = 0; + // requestClipboard() will result in a request to a client to + // transfer its clipboard data. A call to + // SDesktop::handleClipboardData() will be made once the data is + // available. + virtual void requestClipboard() = 0; + + // announceClipboard() informs all clients of changes to the + // clipboard on the server. A client may later request the + // clipboard data via SDesktop::handleClipboardRequest(). + virtual void announceClipboard(bool available) = 0; + + // sendClipboardData() transfers the clipboard data to a client + // and should be called whenever a client has requested the + // clipboard via SDesktop::handleClipboardRequest(). + virtual void sendClipboardData(const char* data) = 0; // bell() tells the server that it should make all clients make a bell sound. virtual void bell() = 0; @@ -69,8 +81,10 @@ namespace rfb { virtual void setCursor(int width, int height, const Point& hotspot, const rdr::U8* cursorData) = 0; - // setCursorPos() tells the server the current position of the cursor. - virtual void setCursorPos(const Point& p) = 0; + // setCursorPos() tells the server the current position of the cursor, and + // whether the server initiated that change (e.g. through another X11 + // client calling XWarpPointer()). + virtual void setCursorPos(const Point& p, bool warped) = 0; // setName() tells the server what desktop title to supply to clients virtual void setName(const char* name) = 0; diff --git a/common/rfb/VNCServerST.cxx b/common/rfb/VNCServerST.cxx index 7bec158..96f970d 100644 --- a/common/rfb/VNCServerST.cxx +++ b/common/rfb/VNCServerST.cxx @@ -123,8 +123,8 @@ static void parseRegionPart(const bool percents, rdr::U16 &pcdest, int &dest, VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_) : blHosts(&blacklist), desktop(desktop_), desktopStarted(false), blockCounter(0), pb(0), blackedpb(0), ledState(ledUnknown), - name(strDup(name_)), pointerClient(0), comparer(0), - cursor(new Cursor(0, 0, Point(), NULL)), + name(strDup(name_)), pointerClient(0), clipboardClient(0), + comparer(0), cursor(new Cursor(0, 0, Point(), NULL)), renderedCursorInvalid(false), queryConnectionHandler(0), keyRemapper(&KeyRemapper::defInstance), lastConnectionTime(0), disableclients(false), @@ -502,21 +502,51 @@ void VNCServerST::setScreenLayout(const ScreenSet& layout) } } -void VNCServerST::bell() +void VNCServerST::requestClipboard() +{ + if (clipboardClient == NULL) + return; + + clipboardClient->requestClipboard(); +} + +void VNCServerST::announceClipboard(bool available) { std::list::iterator ci, ci_next; + + if (available) + clipboardClient = NULL; + + clipboardRequestors.clear(); + for (ci = clients.begin(); ci != clients.end(); ci = ci_next) { ci_next = ci; ci_next++; - (*ci)->bellOrClose(); + (*ci)->announceClipboard(available); } } -void VNCServerST::serverCutText(const char* str, int len) +void VNCServerST::sendClipboardData(const char* data) +{ + std::list::iterator ci, ci_next; + + if (strchr(data, '\r') != NULL) + throw Exception("Invalid carriage return in clipboard data"); + + for (ci = clipboardRequestors.begin(); + ci != clipboardRequestors.end(); ci = ci_next) { + ci_next = ci; ci_next++; + (*ci)->sendClipboardDataOrClose(data); + } + + clipboardRequestors.clear(); +} + +void VNCServerST::bell() { std::list::iterator ci, ci_next; for (ci = clients.begin(); ci != clients.end(); ci = ci_next) { ci_next = ci; ci_next++; - (*ci)->serverCutTextOrClose(str, len); + (*ci)->bellOrClose(); } } @@ -565,14 +595,17 @@ void VNCServerST::setCursor(int width, int height, const Point& newHotspot, } } -void VNCServerST::setCursorPos(const Point& pos) +void VNCServerST::setCursorPos(const Point& pos, bool warped) { if (!cursorPos.equals(pos)) { cursorPos = pos; renderedCursorInvalid = true; std::list::iterator ci; - for (ci = clients.begin(); ci != clients.end(); ci++) + for (ci = clients.begin(); ci != clients.end(); ci++) { (*ci)->renderedCursorChange(); + if (warped) + (*ci)->cursorPositionChange(); + } } } @@ -1049,3 +1082,32 @@ bool VNCServerST::getComparerState() } return false; } + +void VNCServerST::handleClipboardRequest(VNCSConnectionST* client) +{ + clipboardRequestors.push_back(client); + if (clipboardRequestors.size() == 1) + desktop->handleClipboardRequest(); +} + +void VNCServerST::handleClipboardAnnounce(VNCSConnectionST* client, + bool available) +{ + if (available) + clipboardClient = client; + else { + if (client != clipboardClient) + return; + clipboardClient = NULL; + } + desktop->handleClipboardAnnounce(available); +} + +void VNCServerST::handleClipboardData(VNCSConnectionST* client, + const char* data, int len) +{ + if (client != clipboardClient) + return; + desktop->handleClipboardData(data, len); +} + diff --git a/common/rfb/VNCServerST.h b/common/rfb/VNCServerST.h index 7872141..285c4fd 100644 --- a/common/rfb/VNCServerST.h +++ b/common/rfb/VNCServerST.h @@ -96,12 +96,14 @@ namespace rfb { virtual void setPixelBuffer(PixelBuffer* pb); virtual void setScreenLayout(const ScreenSet& layout); virtual PixelBuffer* getPixelBuffer() const { if (DLPRegion.enabled && blackedpb) return blackedpb; else return pb; } - virtual void serverCutText(const char* str, int len); + virtual void requestClipboard(); + virtual void announceClipboard(bool available); + virtual void sendClipboardData(const char* data); virtual void add_changed(const Region ®ion); virtual void add_copied(const Region &dest, const Point &delta); virtual void setCursor(int width, int height, const Point& hotspot, const rdr::U8* data); - virtual void setCursorPos(const Point& p); + virtual void setCursorPos(const Point& p, bool warped); virtual void setLEDState(unsigned state); virtual void bell(); @@ -189,6 +191,10 @@ namespace rfb { void setAPIMessager(network::GetAPIMessager *msgr) { apimessager = msgr; } + void handleClipboardRequest(VNCSConnectionST* client); + void handleClipboardAnnounce(VNCSConnectionST* client, bool available); + void handleClipboardData(VNCSConnectionST* client, const char* data, int len); + protected: friend class VNCSConnectionST; @@ -217,6 +223,8 @@ namespace rfb { std::list clients; VNCSConnectionST* pointerClient; + VNCSConnectionST* clipboardClient; + std::list clipboardRequestors; std::list closingSockets; static EncCache encCache; diff --git a/common/rfb/ZRLEEncoder.cxx b/common/rfb/ZRLEEncoder.cxx index 8917d8f..f1a3262 100644 --- a/common/rfb/ZRLEEncoder.cxx +++ b/common/rfb/ZRLEEncoder.cxx @@ -31,7 +31,7 @@ IntParameter zlibLevel("ZlibLevel","Zlib compression level",-1); ZRLEEncoder::ZRLEEncoder(SConnection* conn) : Encoder(conn, encodingZRLE, EncoderPlain, 127), - zos(0,0,zlibLevel), mos(129*1024) + zos(0,zlibLevel), mos(129*1024) { zos.setUnderlying(&mos); } diff --git a/common/rfb/clipboardTypes.h b/common/rfb/clipboardTypes.h new file mode 100644 index 0000000..bd3fa03 --- /dev/null +++ b/common/rfb/clipboardTypes.h @@ -0,0 +1,41 @@ +/* Copyright 2019 Pierre Ossman for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ +#ifndef __RFB_CLIPBOARDTYPES_H__ +#define __RFB_CLIPBOARDTYPES_H__ + +namespace rfb { + + // Formats + const unsigned int clipboardUTF8 = 1 << 0; + const unsigned int clipboardRTF = 1 << 1; + const unsigned int clipboardHTML = 1 << 2; + const unsigned int clipboardDIB = 1 << 3; + const unsigned int clipboardFiles = 1 << 4; + + const unsigned int clipboardFormatMask = 0x0000ffff; + + // Actions + const unsigned int clipboardCaps = 1 << 24; + const unsigned int clipboardRequest = 1 << 25; + const unsigned int clipboardPeek = 1 << 26; + const unsigned int clipboardNotify = 1 << 27; + const unsigned int clipboardProvide = 1 << 28; + + const unsigned int clipboardActionMask = 0xff000000; +} +#endif diff --git a/common/rfb/encodings.h b/common/rfb/encodings.h index 96d82f4..fda4582 100644 --- a/common/rfb/encodings.h +++ b/common/rfb/encodings.h @@ -85,6 +85,12 @@ namespace rfb { const int pseudoEncodingVideoOutTimeLevel1 = -1986; const int pseudoEncodingVideoOutTimeLevel100 = -1887; + // VMware-specific + const int pseudoEncodingVMwareCursorPosition = 0x574d5666; + + // UltraVNC-specific + const int pseudoEncodingExtendedClipboard = 0xC0A1E5CE; + int encodingNum(const char* name); const char* encodingName(int num); } diff --git a/common/rfb/util.cxx b/common/rfb/util.cxx index f52213b..649eb0b 100644 --- a/common/rfb/util.cxx +++ b/common/rfb/util.cxx @@ -1,4 +1,5 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2011-2019 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,6 +64,10 @@ namespace rfb { delete [] s; } + void strFree(wchar_t* s) { + delete [] s; + } + bool strSplit(const char* src, const char limiter, char** out1, char** out2, bool fromEnd) { CharArray out1old, out2old; @@ -107,6 +112,444 @@ namespace rfb { dest[src ? destlen-1 : 0] = 0; } + char* convertLF(const char* src, size_t bytes) + { + char* buffer; + size_t sz; + + char* out; + const char* in; + size_t in_len; + + // Always include space for a NULL + sz = 1; + + // Compute output size + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + if (*in != '\r') { + sz++; + in++; + in_len--; + continue; + } + + if ((in_len < 2) || (*(in+1) != '\n')) + sz++; + + in++; + in_len--; + } + + // Alloc + buffer = new char[sz]; + memset(buffer, 0, sz); + + // And convert + out = buffer; + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + if (*in != '\r') { + *out++ = *in++; + in_len--; + continue; + } + + if ((in_len < 2) || (*(in+1) != '\n')) + *out++ = '\n'; + + in++; + in_len--; + } + + return buffer; + } + + char* convertCRLF(const char* src, size_t bytes) + { + char* buffer; + size_t sz; + + char* out; + const char* in; + size_t in_len; + + // Always include space for a NULL + sz = 1; + + // Compute output size + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + sz++; + + if (*in == '\r') { + if ((in_len < 2) || (*(in+1) != '\n')) + sz++; + } else if (*in == '\n') { + if ((in == src) || (*(in-1) != '\r')) + sz++; + } + + in++; + in_len--; + } + + // Alloc + buffer = new char[sz]; + memset(buffer, 0, sz); + + // And convert + out = buffer; + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + if (*in == '\n') { + if ((in == src) || (*(in-1) != '\r')) + *out++ = '\r'; + } + + *out = *in; + + if (*in == '\r') { + if ((in_len < 2) || (*(in+1) != '\n')) { + out++; + *out = '\n'; + } + } + + out++; + in++; + in_len--; + } + + return buffer; + } + + size_t ucs4ToUTF8(unsigned src, char* dst) { + if (src < 0x80) { + *dst++ = src; + *dst++ = '\0'; + return 1; + } else if (src < 0x800) { + *dst++ = 0xc0 | (src >> 6); + *dst++ = 0x80 | (src & 0x3f); + *dst++ = '\0'; + return 2; + } else if (src < 0x10000) { + *dst++ = 0xe0 | (src >> 12); + *dst++ = 0x80 | ((src >> 6) & 0x3f); + *dst++ = 0x80 | (src & 0x3f); + *dst++ = '\0'; + return 3; + } else if (src < 0x110000) { + *dst++ = 0xf0 | (src >> 18); + *dst++ = 0x80 | ((src >> 12) & 0x3f); + *dst++ = 0x80 | ((src >> 6) & 0x3f); + *dst++ = 0x80 | (src & 0x3f); + *dst++ = '\0'; + return 4; + } else { + return ucs4ToUTF8(0xfffd, dst); + } + } + + size_t utf8ToUCS4(const char* src, size_t max, unsigned* dst) { + size_t count, consumed; + + *dst = 0xfffd; + + if (max == 0) + return 0; + + consumed = 1; + + if ((*src & 0x80) == 0) { + *dst = *src; + count = 0; + } else if ((*src & 0xe0) == 0xc0) { + *dst = *src & 0x1f; + count = 1; + } else if ((*src & 0xf0) == 0xe0) { + *dst = *src & 0x0f; + count = 2; + } else if ((*src & 0xf8) == 0xf0) { + *dst = *src & 0x07; + count = 3; + } else { + // Invalid sequence, consume all continuation characters + src++; + max--; + while ((max-- > 0) && ((*src++ & 0xc0) == 0x80)) + consumed++; + return consumed; + } + + src++; + max--; + + while (count--) { + consumed++; + + // Invalid or truncated sequence? + if ((max == 0) || ((*src & 0xc0) != 0x80)) { + *dst = 0xfffd; + return consumed; + } + + *dst <<= 6; + *dst |= *src & 0x3f; + + src++; + max--; + } + + return consumed; + } + + size_t ucs4ToUTF16(unsigned src, wchar_t* dst) { + if ((src < 0xd800) || ((src >= 0xe000) && (src < 0x10000))) { + *dst++ = src; + *dst++ = L'\0'; + return 1; + } else if ((src >= 0x10000) && (src < 0x110000)) { + src -= 0x10000; + *dst++ = 0xd800 | ((src >> 10) & 0x03ff); + *dst++ = 0xdc00 | (src & 0x03ff); + *dst++ = L'\0'; + return 2; + } else { + return ucs4ToUTF16(0xfffd, dst); + } + } + + size_t utf16ToUCS4(const wchar_t* src, size_t max, unsigned* dst) { + *dst = 0xfffd; + + if (max == 0) + return 0; + + if ((*src < 0xd800) || (*src >= 0xe000)) { + *dst = *src; + return 1; + } + + if (*src & 0x0400) { + size_t consumed; + + // Invalid sequence, consume all continuation characters + consumed = 0; + while ((max > 0) && (*src & 0x0400)) { + src++; + max--; + consumed++; + } + + return consumed; + } + + *dst = *src++; + max--; + + // Invalid or truncated sequence? + if ((max == 0) || ((*src & 0xfc00) != 0xdc00)) { + *dst = 0xfffd; + return 1; + } + + *dst = 0x10000 + ((*dst & 0x03ff) << 10); + *dst |= *src & 0x3ff; + + return 2; + } + + char* latin1ToUTF8(const char* src, size_t bytes) { + char* buffer; + size_t sz; + + char* out; + const char* in; + size_t in_len; + + // Always include space for a NULL + sz = 1; + + // Compute output size + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + char buf[5]; + sz += ucs4ToUTF8(*(const unsigned char*)in, buf); + in++; + in_len--; + } + + // Alloc + buffer = new char[sz]; + memset(buffer, 0, sz); + + // And convert + out = buffer; + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + out += ucs4ToUTF8(*(const unsigned char*)in, out); + in++; + in_len--; + } + + return buffer; + } + + char* utf8ToLatin1(const char* src, size_t bytes) { + char* buffer; + size_t sz; + + char* out; + const char* in; + size_t in_len; + + // Always include space for a NULL + sz = 1; + + // Compute output size + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + size_t len; + unsigned ucs; + + len = utf8ToUCS4(in, in_len, &ucs); + in += len; + in_len -= len; + sz++; + } + + // Alloc + buffer = new char[sz]; + memset(buffer, 0, sz); + + // And convert + out = buffer; + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + size_t len; + unsigned ucs; + + len = utf8ToUCS4(in, in_len, &ucs); + in += len; + in_len -= len; + + if (ucs > 0xff) + *out++ = '?'; + else + *out++ = (unsigned char)ucs; + } + + return buffer; + } + + char* utf16ToUTF8(const wchar_t* src, size_t units) + { + char* buffer; + size_t sz; + + char* out; + const wchar_t* in; + size_t in_len; + + // Always include space for a NULL + sz = 1; + + // Compute output size + in = src; + in_len = units; + while ((in_len > 0) && (*in != '\0')) { + size_t len; + unsigned ucs; + char buf[5]; + + len = utf16ToUCS4(in, in_len, &ucs); + in += len; + in_len -= len; + + sz += ucs4ToUTF8(ucs, buf); + } + + // Alloc + buffer = new char[sz]; + memset(buffer, 0, sz); + + // And convert + out = buffer; + in = src; + in_len = units; + while ((in_len > 0) && (*in != '\0')) { + size_t len; + unsigned ucs; + + len = utf16ToUCS4(in, in_len, &ucs); + in += len; + in_len -= len; + + out += ucs4ToUTF8(ucs, out); + } + + return buffer; + } + + wchar_t* utf8ToUTF16(const char* src, size_t bytes) + { + wchar_t* buffer; + size_t sz; + + wchar_t* out; + const char* in; + size_t in_len; + + // Always include space for a NULL + sz = 1; + + // Compute output size + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + size_t len; + unsigned ucs; + wchar_t buf[3]; + + len = utf8ToUCS4(in, in_len, &ucs); + in += len; + in_len -= len; + + sz += ucs4ToUTF16(ucs, buf); + } + + // Alloc + buffer = new wchar_t[sz]; + memset(buffer, 0, sz * sizeof(wchar_t)); + + // And convert + out = buffer; + in = src; + in_len = bytes; + while ((in_len > 0) && (*in != '\0')) { + size_t len; + unsigned ucs; + + len = utf8ToUCS4(in, in_len, &ucs); + in += len; + in_len -= len; + + out += ucs4ToUTF16(ucs, out); + } + + return buffer; + } + unsigned msBetween(const struct timeval *first, const struct timeval *second) { diff --git a/common/rfb/util.h b/common/rfb/util.h index 8f90ec4..3100f90 100644 --- a/common/rfb/util.h +++ b/common/rfb/util.h @@ -1,4 +1,5 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2011-2019 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -67,6 +68,7 @@ namespace rfb { char* strDup(const char* s); void strFree(char* s); + void strFree(wchar_t* s); // Returns true if split successful. Returns false otherwise. // ALWAYS *copies* first part of string to out1 buffer. @@ -83,6 +85,25 @@ namespace rfb { // Copies src to dest, up to specified length-1, and guarantees termination void strCopy(char* dest, const char* src, int destlen); + // Makes sure line endings are in a certain format + + char* convertLF(const char* src, size_t bytes = (size_t)-1); + char* convertCRLF(const char* src, size_t bytes = (size_t)-1); + + // Convertions between various Unicode formats. The returned strings are + // always null terminated and must be freed using strFree(). + + size_t ucs4ToUTF8(unsigned src, char* dst); + size_t utf8ToUCS4(const char* src, size_t max, unsigned* dst); + + size_t ucs4ToUTF16(unsigned src, wchar_t* dst); + size_t utf16ToUCS4(const wchar_t* src, size_t max, unsigned* dst); + + char* latin1ToUTF8(const char* src, size_t bytes = (size_t)-1); + char* utf8ToLatin1(const char* src, size_t bytes = (size_t)-1); + + char* utf16ToUTF8(const wchar_t* src, size_t units = (size_t)-1); + wchar_t* utf8ToUTF16(const char* src, size_t bytes = (size_t)-1); // HELPER functions for timeout handling diff --git a/kasmweb b/kasmweb new file mode 160000 index 0000000..10a7fcb --- /dev/null +++ b/kasmweb @@ -0,0 +1 @@ +Subproject commit 10a7fcb91d9ca149262e94e39c216fc2b4f02e10 diff --git a/kasmweb/.eslintignore b/kasmweb/.eslintignore deleted file mode 100644 index d381628..0000000 --- a/kasmweb/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -**/xtscancodes.js diff --git a/kasmweb/.eslintrc b/kasmweb/.eslintrc deleted file mode 100644 index 900a718..0000000 --- a/kasmweb/.eslintrc +++ /dev/null @@ -1,48 +0,0 @@ -{ - "env": { - "browser": true, - "es6": true - }, - "parserOptions": { - "sourceType": "module" - }, - "extends": "eslint:recommended", - "rules": { - // Unsafe or confusing stuff that we forbid - - "no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": true }], - "no-constant-condition": ["error", { "checkLoops": false }], - "no-var": "error", - "no-useless-constructor": "error", - "object-shorthand": ["error", "methods", { "avoidQuotes": true }], - "prefer-arrow-callback": "error", - "arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": false } ], - "arrow-parens": ["error", "as-needed", { "requireForBlockBody": true }], - "arrow-spacing": ["error"], - "no-confusing-arrow": ["error", { "allowParens": true }], - - // Enforced coding style - - "brace-style": ["error", "1tbs", { "allowSingleLine": true }], - "indent": ["error", 4, { "SwitchCase": 1, - "CallExpression": { "arguments": "first" }, - "ArrayExpression": "first", - "ObjectExpression": "first", - "ignoreComments": true }], - "comma-spacing": ["error"], - "comma-style": ["error"], - "curly": ["error", "multi-line"], - "func-call-spacing": ["error"], - "func-names": ["error"], - "func-style": ["error", "declaration", { "allowArrowFunctions": true }], - "key-spacing": ["error"], - "keyword-spacing": ["error"], - "no-trailing-spaces": ["error"], - "semi": ["error"], - "space-before-blocks": ["error"], - "space-before-function-paren": ["error", { "anonymous": "always", - "named": "never", - "asyncArrow": "always" }], - "switch-colon-spacing": ["error"], - } -} diff --git a/kasmweb/.gitignore b/kasmweb/.gitignore deleted file mode 100644 index fe13e54..0000000 --- a/kasmweb/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -*.pyc -*.o -tests/data_*.js -utils/rebind.so -utils/websockify -/node_modules -/build -/lib -recordings -*.swp -*~ -noVNC-*.tgz -/dist -index.html \ No newline at end of file diff --git a/kasmweb/.gitmodules b/kasmweb/.gitmodules deleted file mode 100644 index e69de29..0000000 diff --git a/kasmweb/.travis.yml b/kasmweb/.travis.yml deleted file mode 100644 index f3084c0..0000000 --- a/kasmweb/.travis.yml +++ /dev/null @@ -1,53 +0,0 @@ -language: node_js -sudo: false -cache: - directories: - - node_modules -node_js: - - 6 -env: - matrix: - - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='Windows 10' -# FIXME Skip tests in Linux since Sauce Labs browser versions are ancient. -# - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='Linux' - - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='OS X 10.11' - - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='Windows 10' -# - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='Linux' - - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='OS X 10.11' - - TEST_BROWSER_NAME='internet explorer' TEST_BROWSER_OS='Windows 10' - - TEST_BROWSER_NAME='internet explorer' TEST_BROWSER_OS='Windows 7' - - TEST_BROWSER_NAME=microsoftedge TEST_BROWSER_OS='Windows 10' - - TEST_BROWSER_NAME=safari TEST_BROWSER_OS='OS X 10.13' -before_script: npm install -g karma-cli -addons: - sauce_connect: - username: "directxman12" - jwt: - secure: "d3ekMYslpn6R4f0ajtRMt9SUFmNGDiItHpqaXC5T4KI0KMEsxgvEOfJot5PiFFJWg1DSpJZH6oaW2UxGZ3duJLZrXIEd/JePY8a6NtT35BNgiDPgcp+eu2Bu3rhrSNg7/HEsD1ma+JeUTnv18Ai5oMFfCCQJx2J6osIxyl/ZVxA=" -stages: -- lint -- test -- name: deploy - if: tag is PRESENT -jobs: - include: - - stage: lint - env: - addons: - before_script: - script: npm run lint - - stage: deploy - env: - addons: - script: skip - before_script: skip - deploy: - provider: npm - email: ossman@cendio.se - api_key: - secure: "Qq2Mi9xQawO2zlAigzshzMu2QMHvu1IaN9l0ZIivE99wHJj7eS5f4miJ9wB+/mWRRgb3E8uj9ZRV24+Oc36drlBTU9sz+lHhH0uFMfAIseceK64wZV9sLAZm472fmPp2xdUeTCCqPaRy7g1XBqiJ0LyZvEFLsRijqcLjPBF+b8w=" - on: - tags: true - repo: novnc/noVNC - - diff --git a/kasmweb/AUTHORS b/kasmweb/AUTHORS deleted file mode 100644 index dec0e89..0000000 --- a/kasmweb/AUTHORS +++ /dev/null @@ -1,13 +0,0 @@ -maintainers: -- Joel Martin (@kanaka) -- Solly Ross (@directxman12) -- Samuel Mannehed for Cendio AB (@samhed) -- Pierre Ossman for Cendio AB (@CendioOssman) -maintainersEmeritus: -- @astrand -contributors: -# There are a bunch of people that should be here. -# If you want to be on this list, feel free send a PR -# to add yourself. -- jalf -- NTT corp. diff --git a/kasmweb/LICENSE.txt b/kasmweb/LICENSE.txt deleted file mode 100644 index 20f3eb0..0000000 --- a/kasmweb/LICENSE.txt +++ /dev/null @@ -1,68 +0,0 @@ -noVNC is Copyright (C) 2018 The noVNC Authors -(./AUTHORS) - -The noVNC core library files are licensed under the MPL 2.0 (Mozilla -Public License 2.0). The noVNC core library is composed of the -Javascript code necessary for full noVNC operation. This includes (but -is not limited to): - - core/**/*.js - app/*.js - test/playback.js - -The HTML, CSS, font and images files that included with the noVNC -source distibution (or repository) are not considered part of the -noVNC core library and are licensed under more permissive licenses. -The intent is to allow easy integration of noVNC into existing web -sites and web applications. - -The HTML, CSS, font and image files are licensed as follows: - - *.html : 2-Clause BSD license - - app/styles/*.css : 2-Clause BSD license - - app/styles/Orbitron* : SIL Open Font License 1.1 - (Copyright 2009 Matt McInerney) - - app/images/ : Creative Commons Attribution-ShareAlike - http://creativecommons.org/licenses/by-sa/3.0/ - -Some portions of noVNC are copyright to their individual authors. -Please refer to the individual source files and/or to the noVNC commit -history: https://github.com/novnc/noVNC/commits/master - -The are several files and projects that have been incorporated into -the noVNC core library. Here is a list of those files and the original -licenses (all MPL 2.0 compatible): - - core/base64.js : MPL 2.0 - - core/des.js : Various BSD style licenses - - vendor/pako/ : MIT - - vendor/browser-es-module-loader/src/ : MIT - - vendor/browser-es-module-loader/dist/ : Various BSD style licenses - - vendor/promise.js : MIT - -Any other files not mentioned above are typically marked with -a copyright/license header at the top of the file. The default noVNC -license is MPL-2.0. - -The following license texts are included: - - docs/LICENSE.MPL-2.0 - docs/LICENSE.OFL-1.1 - docs/LICENSE.BSD-3-Clause (New BSD) - docs/LICENSE.BSD-2-Clause (Simplified BSD / FreeBSD) - vendor/pako/LICENSE (MIT) - -Or alternatively the license texts may be found here: - - http://www.mozilla.org/MPL/2.0/ - http://scripts.sil.org/OFL - http://en.wikipedia.org/wiki/BSD_licenses - https://opensource.org/licenses/MIT diff --git a/kasmweb/README.md b/kasmweb/README.md deleted file mode 100644 index 09bff7d..0000000 --- a/kasmweb/README.md +++ /dev/null @@ -1,151 +0,0 @@ -## noVNC: HTML VNC Client Library and Application - -[![Build Status](https://travis-ci.org/novnc/noVNC.svg?branch=master)](https://travis-ci.org/novnc/noVNC) - -### Description - -noVNC is both a HTML VNC client JavaScript library and an application built on -top of that library. noVNC runs well in any modern browser including mobile -browsers (iOS and Android). - -Many companies, projects and products have integrated noVNC including -[OpenStack](http://www.openstack.org), -[OpenNebula](http://opennebula.org/), -[LibVNCServer](http://libvncserver.sourceforge.net), and -[ThinLinc](https://cendio.com/thinlinc). See -[the Projects and Companies wiki page](https://github.com/novnc/noVNC/wiki/Projects-and-companies-using-noVNC) -for a more complete list with additional info and links. - -### Table of Contents - -- [News/help/contact](#newshelpcontact) -- [Features](#features) -- [Screenshots](#screenshots) -- [Browser Requirements](#browser-requirements) -- [Server Requirements](#server-requirements) -- [Quick Start](#quick-start) -- [Integration and Deployment](#integration-and-deployment) -- [Authors/Contributors](#authorscontributors) - -### News/help/contact - -The project website is found at [novnc.com](http://novnc.com). -Notable commits, announcements and news are posted to -[@noVNC](http://www.twitter.com/noVNC). - -If you are a noVNC developer/integrator/user (or want to be) please join the -[noVNC discussion group](https://groups.google.com/forum/?fromgroups#!forum/novnc). - -Bugs and feature requests can be submitted via -[github issues](https://github.com/novnc/noVNC/issues). If you have questions -about using noVNC then please first use the -[discussion group](https://groups.google.com/forum/?fromgroups#!forum/novnc). -We also have a [wiki](https://github.com/novnc/noVNC/wiki/) with lots of -helpful information. - -If you are looking for a place to start contributing to noVNC, a good place to -start would be the issues that are marked as -["patchwelcome"](https://github.com/novnc/noVNC/issues?labels=patchwelcome). -Please check our -[contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) though. - -If you want to show appreciation for noVNC you could donate to a great non- -profits such as: -[Compassion International](http://www.compassion.com/), -[SIL](http://www.sil.org), -[Habitat for Humanity](http://www.habitat.org), -[Electronic Frontier Foundation](https://www.eff.org/), -[Against Malaria Foundation](http://www.againstmalaria.com/), -[Nothing But Nets](http://www.nothingbutnets.net/), etc. -Please tweet [@noVNC](http://www.twitter.com/noVNC) if you do. - - -### Features - -* Supports all modern browsers including mobile (iOS, Android) -* Supported VNC encodings: raw, copyrect, rre, hextile, tight, tightPNG -* Supports scaling, clipping and resizing the desktop -* Local cursor rendering -* Clipboard copy/paste -* Licensed mainly under the [MPL 2.0](http://www.mozilla.org/MPL/2.0/), see - [the license document](LICENSE.txt) for details - -### Screenshots - -Running in Firefox before and after connecting: - -  - - -See more screenshots -[here](http://novnc.com/screenshots.html). - - -### Browser Requirements - -noVNC uses many modern web technologies so a formal requirement list is -not available. However these are the minimum versions we are currently -aware of: - -* Chrome 49, Firefox 44, Safari 10, Opera 36, IE 11, Edge 12 - - -### Server Requirements - -noVNC follows the standard VNC protocol, but unlike other VNC clients it does -require WebSockets support. Many servers include support (e.g. -[x11vnc/libvncserver](http://libvncserver.sourceforge.net/), -[QEMU](http://www.qemu.org/), and -[MobileVNC](http://www.smartlab.at/mobilevnc/)), but for the others you need to -use a WebSockets to TCP socket proxy. noVNC has a sister project -[websockify](https://github.com/novnc/websockify) that provides a simple such -proxy. - - -### Quick Start - -* Use the launch script to automatically download and start websockify, which - includes a mini-webserver and the WebSockets proxy. The `--vnc` option is - used to specify the location of a running VNC server: - - `./utils/launch.sh --vnc localhost:5901` - -* Point your browser to the cut-and-paste URL that is output by the launch - script. Hit the Connect button, enter a password if the VNC server has one - configured, and enjoy! - - -### Integration and Deployment - -Please see our other documents for how to integrate noVNC in your own software, -or deploying the noVNC application in production environments: - -* [Embedding](docs/EMBEDDING.md) - For the noVNC application -* [Library](docs/LIBRARY.md) - For the noVNC JavaScript library - - -### Authors/Contributors - -See [AUTHORS](AUTHORS) for a (full-ish) list of authors. If you're not on -that list and you think you should be, feel free to send a PR to fix that. - -* Core team: - * [Joel Martin](https://github.com/kanaka) - * [Samuel Mannehed](https://github.com/samhed) (Cendio) - * [Peter Åstrand](https://github.com/astrand) (Cendio) - * [Solly Ross](https://github.com/DirectXMan12) (Red Hat / OpenStack) - * [Pierre Ossman](https://github.com/CendioOssman) (Cendio) - -* Notable contributions: - * UI and Icons : Pierre Ossman, Chris Gordon - * Original Logo : Michael Sersen - * tight encoding : Michael Tinglof (Mercuri.ca) - -* Included libraries: - * base64 : Martijn Pieters (Digital Creations 2), Samuel Sieb (sieb.net) - * DES : Dave Zimmerman (Widget Workshop), Jef Poskanzer (ACME Labs) - * Pako : Vitaly Puzrin (https://github.com/nodeca/pako) - -Do you want to be on this list? Check out our -[contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) and -start hacking! diff --git a/kasmweb/VERSION b/kasmweb/VERSION deleted file mode 100644 index 3eefcb9..0000000 --- a/kasmweb/VERSION +++ /dev/null @@ -1 +0,0 @@ -1.0.0 diff --git a/kasmweb/app/error-handler.js b/kasmweb/app/error-handler.js deleted file mode 100644 index 6c90c5a..0000000 --- a/kasmweb/app/error-handler.js +++ /dev/null @@ -1,58 +0,0 @@ -// NB: this should *not* be included as a module until we have -// native support in the browsers, so that our error handler -// can catch script-loading errors. - -// No ES6 can be used in this file since it's used for the translation -/* eslint-disable prefer-arrow-callback */ - -(function _scope() { - "use strict"; - - // Fallback for all uncaught errors - function handleError(event, err) { - try { - const msg = document.getElementById('noVNC_fallback_errormsg'); - - // Only show the initial error - if (msg.hasChildNodes()) { - return false; - } - - let div = document.createElement("div"); - div.classList.add('noVNC_message'); - div.appendChild(document.createTextNode(event.message)); - msg.appendChild(div); - - if (event.filename) { - div = document.createElement("div"); - div.className = 'noVNC_location'; - let text = event.filename; - if (event.lineno !== undefined) { - text += ":" + event.lineno; - if (event.colno !== undefined) { - text += ":" + event.colno; - } - } - div.appendChild(document.createTextNode(text)); - msg.appendChild(div); - } - - if (err && err.stack) { - div = document.createElement("div"); - div.className = 'noVNC_stack'; - div.appendChild(document.createTextNode(err.stack)); - msg.appendChild(div); - } - - document.getElementById('noVNC_fallback_error') - .classList.add("noVNC_open"); - } catch (exc) { - document.write("Kasm has encountered an error."); - } - // Don't return true since this would prevent the error - // from being printed to the browser console. - return false; - } - window.addEventListener('error', function onerror(evt) { handleError(evt, evt.error); }); - window.addEventListener('unhandledrejection', function onreject(evt) { handleError(evt.reason, evt.reason); }); -})(); diff --git a/kasmweb/app/images/alt.svg b/kasmweb/app/images/alt.svg deleted file mode 100644 index e5bb461..0000000 --- a/kasmweb/app/images/alt.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - diff --git a/kasmweb/app/images/clipboard.svg b/kasmweb/app/images/clipboard.svg deleted file mode 100644 index 79af275..0000000 --- a/kasmweb/app/images/clipboard.svg +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - diff --git a/kasmweb/app/images/connect.svg b/kasmweb/app/images/connect.svg deleted file mode 100644 index 56cde41..0000000 --- a/kasmweb/app/images/connect.svg +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - diff --git a/kasmweb/app/images/ctrl.svg b/kasmweb/app/images/ctrl.svg deleted file mode 100644 index 856e939..0000000 --- a/kasmweb/app/images/ctrl.svg +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - diff --git a/kasmweb/app/images/ctrlaltdel.svg b/kasmweb/app/images/ctrlaltdel.svg deleted file mode 100644 index d7744ea..0000000 --- a/kasmweb/app/images/ctrlaltdel.svg +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - diff --git a/kasmweb/app/images/disconnect.svg b/kasmweb/app/images/disconnect.svg deleted file mode 100644 index 6be7d18..0000000 --- a/kasmweb/app/images/disconnect.svg +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/kasmweb/app/images/download.gif b/kasmweb/app/images/download.gif deleted file mode 100644 index 3a52406..0000000 Binary files a/kasmweb/app/images/download.gif and /dev/null differ diff --git a/kasmweb/app/images/drag.svg b/kasmweb/app/images/drag.svg deleted file mode 100644 index 139caf9..0000000 --- a/kasmweb/app/images/drag.svg +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/error.svg b/kasmweb/app/images/error.svg deleted file mode 100644 index 8356d3f..0000000 --- a/kasmweb/app/images/error.svg +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/esc.svg b/kasmweb/app/images/esc.svg deleted file mode 100644 index 830152b..0000000 --- a/kasmweb/app/images/esc.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - diff --git a/kasmweb/app/images/expander.svg b/kasmweb/app/images/expander.svg deleted file mode 100644 index e163535..0000000 --- a/kasmweb/app/images/expander.svg +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/fullscreen.svg b/kasmweb/app/images/fullscreen.svg deleted file mode 100644 index 29bd05d..0000000 --- a/kasmweb/app/images/fullscreen.svg +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - diff --git a/kasmweb/app/images/handle.svg b/kasmweb/app/images/handle.svg deleted file mode 100644 index 4a7a126..0000000 --- a/kasmweb/app/images/handle.svg +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/handle_bg.svg b/kasmweb/app/images/handle_bg.svg deleted file mode 100644 index 7579c42..0000000 --- a/kasmweb/app/images/handle_bg.svg +++ /dev/null @@ -1,172 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_120x120.png b/kasmweb/app/images/icons/368_kasm_logo_only_120x120.png deleted file mode 100644 index 1252383..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_120x120.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_144x144.png b/kasmweb/app/images/icons/368_kasm_logo_only_144x144.png deleted file mode 100644 index 3878a8b..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_144x144.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_152x152.png b/kasmweb/app/images/icons/368_kasm_logo_only_152x152.png deleted file mode 100644 index d6251e7..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_152x152.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_16x16.png b/kasmweb/app/images/icons/368_kasm_logo_only_16x16.png deleted file mode 100644 index db8d3e8..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_16x16.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_192x192.png b/kasmweb/app/images/icons/368_kasm_logo_only_192x192.png deleted file mode 100644 index c21124d..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_192x192.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_24x24.png b/kasmweb/app/images/icons/368_kasm_logo_only_24x24.png deleted file mode 100644 index e1e12ae..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_24x24.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_32x32.png b/kasmweb/app/images/icons/368_kasm_logo_only_32x32.png deleted file mode 100644 index 9f7dbc8..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_32x32.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_48x48.png b/kasmweb/app/images/icons/368_kasm_logo_only_48x48.png deleted file mode 100644 index 32f62e6..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_48x48.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_60x60.png b/kasmweb/app/images/icons/368_kasm_logo_only_60x60.png deleted file mode 100644 index 46c1af0..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_60x60.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_64x64.png b/kasmweb/app/images/icons/368_kasm_logo_only_64x64.png deleted file mode 100644 index 3cc43da..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_64x64.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_72x72.png b/kasmweb/app/images/icons/368_kasm_logo_only_72x72.png deleted file mode 100644 index 13dfd6b..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_72x72.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_76x76.png b/kasmweb/app/images/icons/368_kasm_logo_only_76x76.png deleted file mode 100644 index 266d27a..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_76x76.png and /dev/null differ diff --git a/kasmweb/app/images/icons/368_kasm_logo_only_96x96.png b/kasmweb/app/images/icons/368_kasm_logo_only_96x96.png deleted file mode 100644 index e71b8f4..0000000 Binary files a/kasmweb/app/images/icons/368_kasm_logo_only_96x96.png and /dev/null differ diff --git a/kasmweb/app/images/icons/Makefile b/kasmweb/app/images/icons/Makefile deleted file mode 100644 index 8aba655..0000000 --- a/kasmweb/app/images/icons/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -ICONS := \ - 368_kasm_logo_only_16x16.png \ - 368_kasm_logo_only_24x24.png \ - 368_kasm_logo_only_32x32.png \ - 368_kasm_logo_only_48x48.png \ - 368_kasm_logo_only_64x64.png - -ANDROID_LAUNCHER := \ - 368_kasm_logo_only_48x48.png \ - 368_kasm_logo_only_-72x72.png \ - 368_kasm_logo_only_96x96.png \ - 368_kasm_logo_only_144x144.png \ - 368_kasm_logo_only_192x192.png - -IPHONE_LAUNCHER := \ - 368_kasm_logo_only_60x60.png \ - 368_kasm_logo_only_120x120.png - -IPAD_LAUNCHER := \ - 368_kasm_logo_only_76x76.png \ - 368_kasm_logo_only_152x152.png - -ALL_ICONS := $(ICONS) $(ANDROID_LAUNCHER) $(IPHONE_LAUNCHER) $(IPAD_LAUNCHER) - -all: $(ALL_ICONS) - -368_kasm_logo_only_16x16.png: kasm-icon-sm.svg - convert -density 90 \ - -background transparent "$<" "$@" -368_kasm_logo_only_24x24.png: kasm-icon-sm.svg - convert -density 135 \ - -background transparent "$<" "$@" -368_kasm_logo_only_32x32.png: kasm-icon-sm.svg - convert -density 180 \ - -background transparent "$<" "$@" - -368_kasm_logo_only_%.png: kasm-icon.svg - convert -density $$[`echo $* | cut -d x -f 1` * 90 / 48] \ - -background transparent "$<" "$@" - -clean: - rm -f *.png diff --git a/kasmweb/app/images/icons/kasm_logo.png b/kasmweb/app/images/icons/kasm_logo.png deleted file mode 100644 index a58e96c..0000000 Binary files a/kasmweb/app/images/icons/kasm_logo.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-120x120.png b/kasmweb/app/images/icons/novnc-120x120.png deleted file mode 100644 index 40823ef..0000000 Binary files a/kasmweb/app/images/icons/novnc-120x120.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-144x144.png b/kasmweb/app/images/icons/novnc-144x144.png deleted file mode 100644 index eee71f1..0000000 Binary files a/kasmweb/app/images/icons/novnc-144x144.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-152x152.png b/kasmweb/app/images/icons/novnc-152x152.png deleted file mode 100644 index 0694b2d..0000000 Binary files a/kasmweb/app/images/icons/novnc-152x152.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-16x16.png b/kasmweb/app/images/icons/novnc-16x16.png deleted file mode 100644 index 42108f4..0000000 Binary files a/kasmweb/app/images/icons/novnc-16x16.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-192x192.png b/kasmweb/app/images/icons/novnc-192x192.png deleted file mode 100644 index ef9201f..0000000 Binary files a/kasmweb/app/images/icons/novnc-192x192.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-24x24.png b/kasmweb/app/images/icons/novnc-24x24.png deleted file mode 100644 index 1106135..0000000 Binary files a/kasmweb/app/images/icons/novnc-24x24.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-32x32.png b/kasmweb/app/images/icons/novnc-32x32.png deleted file mode 100644 index ff00dc3..0000000 Binary files a/kasmweb/app/images/icons/novnc-32x32.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-48x48.png b/kasmweb/app/images/icons/novnc-48x48.png deleted file mode 100644 index f24cd6c..0000000 Binary files a/kasmweb/app/images/icons/novnc-48x48.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-60x60.png b/kasmweb/app/images/icons/novnc-60x60.png deleted file mode 100644 index 06b0d60..0000000 Binary files a/kasmweb/app/images/icons/novnc-60x60.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-64x64.png b/kasmweb/app/images/icons/novnc-64x64.png deleted file mode 100644 index 6d0fb34..0000000 Binary files a/kasmweb/app/images/icons/novnc-64x64.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-72x72.png b/kasmweb/app/images/icons/novnc-72x72.png deleted file mode 100644 index 23163a2..0000000 Binary files a/kasmweb/app/images/icons/novnc-72x72.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-76x76.png b/kasmweb/app/images/icons/novnc-76x76.png deleted file mode 100644 index aef61c4..0000000 Binary files a/kasmweb/app/images/icons/novnc-76x76.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-96x96.png b/kasmweb/app/images/icons/novnc-96x96.png deleted file mode 100644 index 1a77c53..0000000 Binary files a/kasmweb/app/images/icons/novnc-96x96.png and /dev/null differ diff --git a/kasmweb/app/images/icons/novnc-icon-sm.svg b/kasmweb/app/images/icons/novnc-icon-sm.svg deleted file mode 100644 index aa1c6f1..0000000 --- a/kasmweb/app/images/icons/novnc-icon-sm.svg +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/kasmweb/app/images/icons/novnc-icon.svg b/kasmweb/app/images/icons/novnc-icon.svg deleted file mode 100644 index 1efff91..0000000 --- a/kasmweb/app/images/icons/novnc-icon.svg +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/kasmweb/app/images/info.svg b/kasmweb/app/images/info.svg deleted file mode 100644 index 557b772..0000000 --- a/kasmweb/app/images/info.svg +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/keyboard.svg b/kasmweb/app/images/keyboard.svg deleted file mode 100644 index 137b350..0000000 --- a/kasmweb/app/images/keyboard.svg +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - diff --git a/kasmweb/app/images/mouse_left.svg b/kasmweb/app/images/mouse_left.svg deleted file mode 100644 index ce4cca4..0000000 --- a/kasmweb/app/images/mouse_left.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/kasmweb/app/images/mouse_middle.svg b/kasmweb/app/images/mouse_middle.svg deleted file mode 100644 index 6603425..0000000 --- a/kasmweb/app/images/mouse_middle.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/kasmweb/app/images/mouse_none.svg b/kasmweb/app/images/mouse_none.svg deleted file mode 100644 index 3e0f838..0000000 --- a/kasmweb/app/images/mouse_none.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/kasmweb/app/images/mouse_right.svg b/kasmweb/app/images/mouse_right.svg deleted file mode 100644 index f4bad76..0000000 --- a/kasmweb/app/images/mouse_right.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/kasmweb/app/images/power.svg b/kasmweb/app/images/power.svg deleted file mode 100644 index 4925d3e..0000000 --- a/kasmweb/app/images/power.svg +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - diff --git a/kasmweb/app/images/refresh.gif b/kasmweb/app/images/refresh.gif deleted file mode 100644 index cfa80ce..0000000 Binary files a/kasmweb/app/images/refresh.gif and /dev/null differ diff --git a/kasmweb/app/images/settings.svg b/kasmweb/app/images/settings.svg deleted file mode 100644 index dbb2e80..0000000 --- a/kasmweb/app/images/settings.svg +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/tab.svg b/kasmweb/app/images/tab.svg deleted file mode 100644 index 1ccb322..0000000 --- a/kasmweb/app/images/tab.svg +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - diff --git a/kasmweb/app/images/toggleextrakeys.svg b/kasmweb/app/images/toggleextrakeys.svg deleted file mode 100644 index b578c0d..0000000 --- a/kasmweb/app/images/toggleextrakeys.svg +++ /dev/null @@ -1,90 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/kasmweb/app/images/warning.svg b/kasmweb/app/images/warning.svg deleted file mode 100644 index 7114f9b..0000000 --- a/kasmweb/app/images/warning.svg +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/kasmweb/app/images/windows.svg b/kasmweb/app/images/windows.svg deleted file mode 100644 index 270405c..0000000 --- a/kasmweb/app/images/windows.svg +++ /dev/null @@ -1,85 +0,0 @@ - - - -image/svg+xml - - - - - - - - - - \ No newline at end of file diff --git a/kasmweb/app/locale/de.json b/kasmweb/app/locale/de.json deleted file mode 100644 index 60cbcdd..0000000 --- a/kasmweb/app/locale/de.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "Connecting...": "Verbinden...", - "Disconnecting...": "Verbindung trennen...", - "Reconnecting...": "Verbindung wiederherstellen...", - "Internal error": "Interner Fehler", - "Must set host": "Richten Sie den Server ein", - "Connected (encrypted) to ": "Verbunden mit (verschlüsselt) ", - "Connected (unencrypted) to ": "Verbunden mit (unverschlüsselt) ", - "Something went wrong, connection is closed": "Etwas lief schief, Verbindung wurde getrennt", - "Disconnected": "Verbindung zum Server getrennt", - "New connection has been rejected with reason: ": "Verbindung wurde aus folgendem Grund abgelehnt: ", - "New connection has been rejected": "Verbindung wurde abgelehnt", - "Password is required": "Passwort ist erforderlich", - "Kasm encountered an error:": "Ein Fehler ist aufgetreten:", - "Hide/Show the control bar": "Kontrollleiste verstecken/anzeigen", - "Move/Drag Viewport": "Ansichtsfenster verschieben/ziehen", - "viewport drag": "Ansichtsfenster ziehen", - "Active Mouse Button": "Aktive Maustaste", - "No mousebutton": "Keine Maustaste", - "Left mousebutton": "Linke Maustaste", - "Middle mousebutton": "Mittlere Maustaste", - "Right mousebutton": "Rechte Maustaste", - "Keyboard": "Tastatur", - "Show Keyboard": "Tastatur anzeigen", - "Extra keys": "Zusatztasten", - "Show Extra Keys": "Zusatztasten anzeigen", - "Ctrl": "Strg", - "Toggle Ctrl": "Strg umschalten", - "Alt": "Alt", - "Toggle Alt": "Alt umschalten", - "Send Tab": "Tab senden", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "Escape senden", - "Ctrl+Alt+Del": "Strg+Alt+Entf", - "Send Ctrl-Alt-Del": "Strg+Alt+Entf senden", - "Shutdown/Reboot": "Herunterfahren/Neustarten", - "Shutdown/Reboot...": "Herunterfahren/Neustarten...", - "Power": "Energie", - "Shutdown": "Herunterfahren", - "Reboot": "Neustarten", - "Reset": "Zurücksetzen", - "Clipboard": "Zwischenablage", - "Clear": "Löschen", - "Fullscreen": "Vollbild", - "Settings": "Einstellungen", - "Shared Mode": "Geteilter Modus", - "View Only": "Nur betrachten", - "Clip to Window": "Auf Fenster begrenzen", - "Scaling Mode:": "Skalierungsmodus:", - "None": "Keiner", - "Local Scaling": "Lokales skalieren", - "Remote Resizing": "Serverseitiges skalieren", - "Advanced": "Erweitert", - "Repeater ID:": "Repeater ID:", - "WebSocket": "WebSocket", - "Encrypt": "Verschlüsselt", - "Host:": "Server:", - "Port:": "Port:", - "Path:": "Pfad:", - "Automatic Reconnect": "Automatisch wiederverbinden", - "Reconnect Delay (ms):": "Wiederverbindungsverzögerung (ms):", - "Logging:": "Protokollierung:", - "Disconnect": "Verbindung trennen", - "Connect": "Verbinden", - "Password:": "Passwort:", - "Cancel": "Abbrechen", - "Canvas not supported.": "Canvas nicht unterstützt." -} \ No newline at end of file diff --git a/kasmweb/app/locale/el.json b/kasmweb/app/locale/el.json deleted file mode 100644 index 622ab73..0000000 --- a/kasmweb/app/locale/el.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "Connecting...": "Συνδέεται...", - "Disconnecting...": "Aποσυνδέεται...", - "Reconnecting...": "Επανασυνδέεται...", - "Internal error": "Εσωτερικό σφάλμα", - "Must set host": "Πρέπει να οριστεί ο διακομιστής", - "Connected (encrypted) to ": "Συνδέθηκε (κρυπτογραφημένα) με το ", - "Connected (unencrypted) to ": "Συνδέθηκε (μη κρυπτογραφημένα) με το ", - "Something went wrong, connection is closed": "Κάτι πήγε στραβά, η σύνδεση διακόπηκε", - "Disconnected": "Αποσυνδέθηκε", - "New connection has been rejected with reason: ": "Η νέα σύνδεση απορρίφθηκε διότι: ", - "New connection has been rejected": "Η νέα σύνδεση απορρίφθηκε ", - "Password is required": "Απαιτείται ο κωδικός πρόσβασης", - "Kasm encountered an error:": "το kasm αντιμετώπισε ένα σφάλμα:", - "Hide/Show the control bar": "Απόκρυψη/Εμφάνιση γραμμής ελέγχου", - "Move/Drag Viewport": "Μετακίνηση/Σύρσιμο Θεατού πεδίου", - "viewport drag": "σύρσιμο θεατού πεδίου", - "Active Mouse Button": "Ενεργό Πλήκτρο Ποντικιού", - "No mousebutton": "Χωρίς Πλήκτρο Ποντικιού", - "Left mousebutton": "Αριστερό Πλήκτρο Ποντικιού", - "Middle mousebutton": "Μεσαίο Πλήκτρο Ποντικιού", - "Right mousebutton": "Δεξί Πλήκτρο Ποντικιού", - "Keyboard": "Πληκτρολόγιο", - "Show Keyboard": "Εμφάνιση Πληκτρολογίου", - "Extra keys": "Επιπλέον πλήκτρα", - "Show Extra Keys": "Εμφάνιση Επιπλέον Πλήκτρων", - "Ctrl": "Ctrl", - "Toggle Ctrl": "Εναλλαγή Ctrl", - "Alt": "Alt", - "Toggle Alt": "Εναλλαγή Alt", - "Send Tab": "Αποστολή Tab", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "Αποστολή Escape", - "Ctrl+Alt+Del": "Ctrl+Alt+Del", - "Send Ctrl-Alt-Del": "Αποστολή Ctrl-Alt-Del", - "Shutdown/Reboot": "Κλείσιμο/Επανεκκίνηση", - "Shutdown/Reboot...": "Κλείσιμο/Επανεκκίνηση...", - "Power": "Απενεργοποίηση", - "Shutdown": "Κλείσιμο", - "Reboot": "Επανεκκίνηση", - "Reset": "Επαναφορά", - "Clipboard": "Πρόχειρο", - "Clear": "Καθάρισμα", - "Fullscreen": "Πλήρης Οθόνη", - "Settings": "Ρυθμίσεις", - "Shared Mode": "Κοινόχρηστη Λειτουργία", - "View Only": "Μόνο Θέαση", - "Clip to Window": "Αποκοπή στο όριο του Παράθυρου", - "Scaling Mode:": "Λειτουργία Κλιμάκωσης:", - "None": "Καμία", - "Local Scaling": "Τοπική Κλιμάκωση", - "Remote Resizing": "Απομακρυσμένη Αλλαγή μεγέθους", - "Advanced": "Για προχωρημένους", - "Repeater ID:": "Repeater ID:", - "WebSocket": "WebSocket", - "Encrypt": "Κρυπτογράφηση", - "Host:": "Όνομα διακομιστή:", - "Port:": "Πόρτα διακομιστή:", - "Path:": "Διαδρομή:", - "Automatic Reconnect": "Αυτόματη επανασύνδεση", - "Reconnect Delay (ms):": "Καθυστέρηση επανασύνδεσης (ms):", - "Logging:": "Καταγραφή:", - "Disconnect": "Αποσύνδεση", - "Connect": "Σύνδεση", - "Password:": "Κωδικός Πρόσβασης:", - "Cancel": "Ακύρωση", - "Canvas not supported.": "Δεν υποστηρίζεται το στοιχείο Canvas" -} \ No newline at end of file diff --git a/kasmweb/app/locale/es.json b/kasmweb/app/locale/es.json deleted file mode 100644 index 23f23f4..0000000 --- a/kasmweb/app/locale/es.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "Connecting...": "Conectando...", - "Connected (encrypted) to ": "Conectado (con encriptación) a", - "Connected (unencrypted) to ": "Conectado (sin encriptación) a", - "Disconnecting...": "Desconectando...", - "Disconnected": "Desconectado", - "Must set host": "Debes configurar el host", - "Reconnecting...": "Reconectando...", - "Password is required": "Contraseña es obligatoria", - "Disconnect timeout": "Tiempo de desconexión agotado", - "noVNC encountered an error:": "noVNC ha encontrado un error:", - "Hide/Show the control bar": "Ocultar/Mostrar la barra de control", - "Move/Drag Viewport": "Mover/Arrastrar la ventana", - "viewport drag": "Arrastrar la ventana", - "Active Mouse Button": "Botón activo del ratón", - "No mousebutton": "Ningún botón del ratón", - "Left mousebutton": "Botón izquierdo del ratón", - "Middle mousebutton": "Botón central del ratón", - "Right mousebutton": "Botón derecho del ratón", - "Keyboard": "Teclado", - "Show Keyboard": "Mostrar teclado", - "Extra keys": "Teclas adicionales", - "Show Extra Keys": "Mostrar Teclas Adicionales", - "Ctrl": "Ctrl", - "Toggle Ctrl": "Pulsar/Soltar Ctrl", - "Alt": "Alt", - "Toggle Alt": "Pulsar/Soltar Alt", - "Send Tab": "Enviar Tabulación", - "Tab": "Tabulación", - "Esc": "Esc", - "Send Escape": "Enviar Escape", - "Ctrl+Alt+Del": "Ctrl+Alt+Del", - "Send Ctrl-Alt-Del": "Enviar Ctrl+Alt+Del", - "Shutdown/Reboot": "Apagar/Reiniciar", - "Shutdown/Reboot...": "Apagar/Reiniciar...", - "Power": "Encender", - "Shutdown": "Apagar", - "Reboot": "Reiniciar", - "Reset": "Restablecer", - "Clipboard": "Portapapeles", - "Clear": "Vaciar", - "Fullscreen": "Pantalla Completa", - "Settings": "Configuraciones", - "Shared Mode": "Modo Compartido", - "View Only": "Solo visualización", - "Clip to Window": "Recortar al tamaño de la ventana", - "Scaling Mode:": "Modo de escalado:", - "None": "Ninguno", - "Local Scaling": "Escalado Local", - "Local Downscaling": "Reducción de escala local", - "Remote Resizing": "Cambio de tamaño remoto", - "Advanced": "Avanzado", - "Local Cursor": "Cursor Local", - "Repeater ID:": "ID del Repetidor", - "WebSocket": "WebSocket", - "Encrypt": "", - "Host:": "Host", - "Port:": "Puesto", - "Path:": "Ruta", - "Automatic Reconnect": "Reconexión automática", - "Reconnect Delay (ms):": "Retraso en la reconexión (ms)", - "Logging:": "Logging", - "Disconnect": "Desconectar", - "Connect": "Conectar", - "Password:": "Contraseña", - "Cancel": "Cancelar", - "Canvas not supported.": "Canvas no está soportado" -} \ No newline at end of file diff --git a/kasmweb/app/locale/nl.json b/kasmweb/app/locale/nl.json deleted file mode 100644 index 85313d6..0000000 --- a/kasmweb/app/locale/nl.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "Connecting...": "Verbinden...", - "Connected (encrypted) to ": "Verbonden (versleuteld) met ", - "Connected (unencrypted) to ": "Verbonden (onversleuteld) met ", - "Disconnecting...": "Verbinding verbreken...", - "Disconnected": "Verbinding verbroken", - "Must set host": "Host moeten worden ingesteld", - "Reconnecting...": "Opnieuw verbinding maken...", - "Password is required": "Wachtwoord is vereist", - "Disconnect timeout": "Timeout tijdens verbreken van verbinding", - "noVNC encountered an error:": "noVNC heeft een fout bemerkt:", - "Hide/Show the control bar": "Verberg/Toon de bedieningsbalk", - "Move/Drag Viewport": "Verplaats/Versleep Kijkvenster", - "viewport drag": "kijkvenster slepen", - "Active Mouse Button": "Actieve Muisknop", - "No mousebutton": "Geen muisknop", - "Left mousebutton": "Linker muisknop", - "Middle mousebutton": "Middelste muisknop", - "Right mousebutton": "Rechter muisknop", - "Keyboard": "Toetsenbord", - "Show Keyboard": "Toon Toetsenbord", - "Extra keys": "Extra toetsen", - "Show Extra Keys": "Toon Extra Toetsen", - "Ctrl": "Ctrl", - "Toggle Ctrl": "Ctrl aan/uitzetten", - "Alt": "Alt", - "Toggle Alt": "Alt aan/uitzetten", - "Send Tab": "Tab Sturen", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "Escape Sturen", - "Ctrl+Alt+Del": "Ctrl-Alt-Del", - "Send Ctrl-Alt-Del": "Ctrl-Alt-Del Sturen", - "Shutdown/Reboot": "Uitschakelen/Herstarten", - "Shutdown/Reboot...": "Uitschakelen/Herstarten...", - "Power": "Systeem", - "Shutdown": "Uitschakelen", - "Reboot": "Herstarten", - "Reset": "Resetten", - "Clipboard": "Klembord", - "Clear": "Wissen", - "Fullscreen": "Volledig Scherm", - "Settings": "Instellingen", - "Shared Mode": "Gedeelde Modus", - "View Only": "Alleen Kijken", - "Clip to Window": "Randen buiten venster afsnijden", - "Scaling Mode:": "Schaalmodus:", - "None": "Geen", - "Local Scaling": "Lokaal Schalen", - "Local Downscaling": "Lokaal Neerschalen", - "Remote Resizing": "Op Afstand Formaat Wijzigen", - "Advanced": "Geavanceerd", - "Local Cursor": "Lokale Cursor", - "Repeater ID:": "Repeater ID:", - "WebSocket": "WebSocket", - "Encrypt": "Versleutelen", - "Host:": "Host:", - "Port:": "Poort:", - "Path:": "Pad:", - "Automatic Reconnect": "Automatisch Opnieuw Verbinden", - "Reconnect Delay (ms):": "Vertraging voor Opnieuw Verbinden (ms):", - "Logging:": "Logmeldingen:", - "Disconnect": "Verbinding verbreken", - "Connect": "Verbinden", - "Password:": "Wachtwoord:", - "Cancel": "Annuleren", - "Canvas not supported.": "Canvas wordt niet ondersteund." -} \ No newline at end of file diff --git a/kasmweb/app/locale/pl.json b/kasmweb/app/locale/pl.json deleted file mode 100644 index 006ac7a..0000000 --- a/kasmweb/app/locale/pl.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "Connecting...": "Łączenie...", - "Disconnecting...": "Rozłączanie...", - "Reconnecting...": "Łączenie...", - "Internal error": "Błąd wewnętrzny", - "Must set host": "Host i port są wymagane", - "Connected (encrypted) to ": "Połączenie (szyfrowane) z ", - "Connected (unencrypted) to ": "Połączenie (nieszyfrowane) z ", - "Something went wrong, connection is closed": "Coś poszło źle, połączenie zostało zamknięte", - "Disconnected": "Rozłączony", - "New connection has been rejected with reason: ": "Nowe połączenie zostało odrzucone z powodu: ", - "New connection has been rejected": "Nowe połączenie zostało odrzucone", - "Password is required": "Hasło jest wymagane", - "noVNC encountered an error:": "noVNC napotkało błąd:", - "Hide/Show the control bar": "Pokaż/Ukryj pasek ustawień", - "Move/Drag Viewport": "Ruszaj/Przeciągaj Viewport", - "viewport drag": "przeciągnij viewport", - "Active Mouse Button": "Aktywny Przycisk Myszy", - "No mousebutton": "Brak przycisku myszy", - "Left mousebutton": "Lewy przycisk myszy", - "Middle mousebutton": "Środkowy przycisk myszy", - "Right mousebutton": "Prawy przycisk myszy", - "Keyboard": "Klawiatura", - "Show Keyboard": "Pokaż klawiaturę", - "Extra keys": "Przyciski dodatkowe", - "Show Extra Keys": "Pokaż przyciski dodatkowe", - "Ctrl": "Ctrl", - "Toggle Ctrl": "Przełącz Ctrl", - "Alt": "Alt", - "Toggle Alt": "Przełącz Alt", - "Send Tab": "Wyślij Tab", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "Wyślij Escape", - "Ctrl+Alt+Del": "Ctrl+Alt+Del", - "Send Ctrl-Alt-Del": "Wyślij Ctrl-Alt-Del", - "Shutdown/Reboot": "Wyłącz/Uruchom ponownie", - "Shutdown/Reboot...": "Wyłącz/Uruchom ponownie...", - "Power": "Włączony", - "Shutdown": "Wyłącz", - "Reboot": "Uruchom ponownie", - "Reset": "Resetuj", - "Clipboard": "Schowek", - "Clear": "Wyczyść", - "Fullscreen": "Pełny ekran", - "Settings": "Ustawienia", - "Shared Mode": "Tryb Współdzielenia", - "View Only": "Tylko Podgląd", - "Clip to Window": "Przytnij do Okna", - "Scaling Mode:": "Tryb Skalowania:", - "None": "Brak", - "Local Scaling": "Skalowanie lokalne", - "Remote Resizing": "Skalowanie zdalne", - "Advanced": "Zaawansowane", - "Repeater ID:": "ID Repeatera:", - "WebSocket": "WebSocket", - "Encrypt": "Szyfrowanie", - "Host:": "Host:", - "Port:": "Port:", - "Path:": "Ścieżka:", - "Automatic Reconnect": "Automatycznie wznawiaj połączenie", - "Reconnect Delay (ms):": "Opóźnienie wznawiania (ms):", - "Logging:": "Poziom logowania:", - "Disconnect": "Rozłącz", - "Connect": "Połącz", - "Password:": "Hasło:", - "Cancel": "Anuluj", - "Canvas not supported.": "Element Canvas nie jest wspierany." -} \ No newline at end of file diff --git a/kasmweb/app/locale/sv.json b/kasmweb/app/locale/sv.json deleted file mode 100644 index cfd8867..0000000 --- a/kasmweb/app/locale/sv.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "Connecting...": "Ansluter...", - "Connected (encrypted) to ": "Ansluten (krypterat) till ", - "Connected (unencrypted) to ": "Ansluten (okrypterat) till ", - "Disconnecting...": "Kopplar ner...", - "Disconnected": "Frånkopplad", - "Must set host": "Du måste specifiera en värd", - "Reconnecting...": "Återansluter...", - "Password is required": "Lösenord krävs", - "Disconnect timeout": "Det tog för lång tid att koppla ner", - "noVNC encountered an error:": "noVNC stötte på ett problem:", - "Hide/Show the control bar": "Göm/Visa kontrollbaren", - "Move/Drag Viewport": "Flytta/Dra Vyn", - "viewport drag": "dra vy", - "Active Mouse Button": "Aktiv musknapp", - "No mousebutton": "Ingen musknapp", - "Left mousebutton": "Vänster musknapp", - "Middle mousebutton": "Mitten-musknapp", - "Right mousebutton": "Höger musknapp", - "Keyboard": "Tangentbord", - "Show Keyboard": "Visa Tangentbord", - "Extra keys": "Extraknappar", - "Show Extra Keys": "Visa Extraknappar", - "Ctrl": "Ctrl", - "Toggle Ctrl": "Växla Ctrl", - "Alt": "Alt", - "Toggle Alt": "Växla Alt", - "Send Tab": "Skicka Tab", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "Skicka Escape", - "Ctrl+Alt+Del": "Ctrl+Alt+Del", - "Send Ctrl-Alt-Del": "Skicka Ctrl-Alt-Del", - "Shutdown/Reboot": "Stäng av/Boota om", - "Shutdown/Reboot...": "Stäng av/Boota om...", - "Power": "Ström", - "Shutdown": "Stäng av", - "Reboot": "Boota om", - "Reset": "Återställ", - "Clipboard": "Urklipp", - "Clear": "Rensa", - "Fullscreen": "Fullskärm", - "Settings": "Inställningar", - "Shared Mode": "Delat Läge", - "View Only": "Endast Visning", - "Clip to Window": "Begränsa till Fönster", - "Scaling Mode:": "Skalningsläge:", - "None": "Ingen", - "Local Scaling": "Lokal Skalning", - "Local Downscaling": "Lokal Nedskalning", - "Remote Resizing": "Ändra Storlek", - "Advanced": "Avancerat", - "Local Cursor": "Lokal Muspekare", - "Repeater ID:": "Repeater-ID:", - "WebSocket": "WebSocket", - "Encrypt": "Kryptera", - "Host:": "Värd:", - "Port:": "Port:", - "Path:": "Sökväg:", - "Automatic Reconnect": "Automatisk Återanslutning", - "Reconnect Delay (ms):": "Fördröjning (ms):", - "Logging:": "Loggning:", - "Disconnect": "Koppla från", - "Connect": "Anslut", - "Password:": "Lösenord:", - "Cancel": "Avbryt", - "Canvas not supported.": "Canvas stöds ej" -} \ No newline at end of file diff --git a/kasmweb/app/locale/tr.json b/kasmweb/app/locale/tr.json deleted file mode 100644 index 451c1b8..0000000 --- a/kasmweb/app/locale/tr.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "Connecting...": "Bağlanıyor...", - "Disconnecting...": "Bağlantı kesiliyor...", - "Reconnecting...": "Yeniden bağlantı kuruluyor...", - "Internal error": "İç hata", - "Must set host": "Sunucuyu kur", - "Connected (encrypted) to ": "Bağlı (şifrelenmiş)", - "Connected (unencrypted) to ": "Bağlandı (şifrelenmemiş)", - "Something went wrong, connection is closed": "Bir şeyler ters gitti, bağlantı kesildi", - "Disconnected": "Bağlantı kesildi", - "New connection has been rejected with reason: ": "Bağlantı aşağıdaki nedenlerden dolayı reddedildi: ", - "New connection has been rejected": "Bağlantı reddedildi", - "Password is required": "Şifre gerekli", - "noVNC encountered an error:": "Bir hata oluştu:", - "Hide/Show the control bar": "Denetim masasını Gizle/Göster", - "Move/Drag Viewport": "Görünümü Taşı/Sürükle", - "viewport drag": "Görüntü penceresini sürükle", - "Active Mouse Button": "Aktif Fare Düğmesi", - "No mousebutton": "Fare düğmesi yok", - "Left mousebutton": "Farenin sol düğmesi", - "Middle mousebutton": "Farenin orta düğmesi", - "Right mousebutton": "Farenin sağ düğmesi", - "Keyboard": "Klavye", - "Show Keyboard": "Klavye Düzenini Göster", - "Extra keys": "Ekstra tuşlar", - "Show Extra Keys": "Ekstra tuşları göster", - "Ctrl": "Ctrl", - "Toggle Ctrl": "Ctrl Değiştir ", - "Alt": "Alt", - "Toggle Alt": "Alt Değiştir", - "Send Tab": "Sekme Gönder", - "Tab": "Sekme", - "Esc": "Esc", - "Send Escape": "Boşluk Gönder", - "Ctrl+Alt+Del": "Ctrl + Alt + Del", - "Send Ctrl-Alt-Del": "Ctrl-Alt-Del Gönder", - "Shutdown/Reboot": "Kapat/Yeniden Başlat", - "Shutdown/Reboot...": "Kapat/Yeniden Başlat...", - "Power": "Güç", - "Shutdown": "Kapat", - "Reboot": "Yeniden Başlat", - "Reset": "Sıfırla", - "Clipboard": "Pano", - "Clear": "Temizle", - "Fullscreen": "Tam Ekran", - "Settings": "Ayarlar", - "Shared Mode": "Paylaşım Modu", - "View Only": "Sadece Görüntüle", - "Clip to Window": "Pencereye Tıkla", - "Scaling Mode:": "Ölçekleme Modu:", - "None": "Bilinmeyen", - "Local Scaling": "Yerel Ölçeklendirme", - "Remote Resizing": "Uzaktan Yeniden Boyutlandırma", - "Advanced": "Gelişmiş", - "Repeater ID:": "Tekralayıcı ID:", - "WebSocket": "WebSocket", - "Encrypt": "Şifrele", - "Host:": "Ana makine:", - "Port:": "Port:", - "Path:": "Yol:", - "Automatic Reconnect": "Otomatik Yeniden Bağlan", - "Reconnect Delay (ms):": "Yeniden Bağlanma Süreci (ms):", - "Logging:": "Giriş yapılıyor:", - "Disconnect": "Bağlantıyı Kes", - "Connect": "Bağlan", - "Password:": "Parola:", - "Cancel": "Vazgeç", - "Canvas not supported.": "Tuval desteklenmiyor." -} \ No newline at end of file diff --git a/kasmweb/app/locale/zh_CN.json b/kasmweb/app/locale/zh_CN.json deleted file mode 100644 index ec961da..0000000 --- a/kasmweb/app/locale/zh_CN.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "Connecting...": "链接中...", - "Disconnecting...": "正在中断连接...", - "Reconnecting...": "重新链接中...", - "Internal error": "内部错误", - "Must set host": "请提供主机名", - "Connected (encrypted) to ": "已加密链接到", - "Connected (unencrypted) to ": "未加密链接到", - "Something went wrong, connection is closed": "发生错误,链接已关闭", - "Failed to connect to server": "无法链接到服务器", - "Disconnected": "链接已中断", - "New connection has been rejected with reason: ": "链接被拒绝,原因:", - "New connection has been rejected": "链接被拒绝", - "Password is required": "请提供密码", - "noVNC encountered an error:": "noVNC 遇到一个错误:", - "Hide/Show the control bar": "显示/隐藏控制列", - "Move/Drag Viewport": "拖放显示范围", - "viewport drag": "显示范围拖放", - "Active Mouse Button": "启动鼠标按鍵", - "No mousebutton": "禁用鼠标按鍵", - "Left mousebutton": "鼠标左鍵", - "Middle mousebutton": "鼠标中鍵", - "Right mousebutton": "鼠标右鍵", - "Keyboard": "键盘", - "Show Keyboard": "显示键盘", - "Extra keys": "额外按键", - "Show Extra Keys": "显示额外按键", - "Ctrl": "Ctrl", - "Toggle Ctrl": "切换 Ctrl", - "Alt": "Alt", - "Toggle Alt": "切换 Alt", - "Send Tab": "发送 Tab 键", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "发送 Escape 键", - "Ctrl+Alt+Del": "Ctrl-Alt-Del", - "Send Ctrl-Alt-Del": "发送 Ctrl-Alt-Del 键", - "Shutdown/Reboot": "关机/重新启动", - "Shutdown/Reboot...": "关机/重新启动...", - "Power": "电源", - "Shutdown": "关机", - "Reboot": "重新启动", - "Reset": "重置", - "Clipboard": "剪贴板", - "Clear": "清除", - "Fullscreen": "全屏幕", - "Settings": "设置", - "Shared Mode": "分享模式", - "View Only": "仅检视", - "Clip to Window": "限制/裁切窗口大小", - "Scaling Mode:": "缩放模式:", - "None": "无", - "Local Scaling": "本地缩放", - "Remote Resizing": "远程调整大小", - "Advanced": "高级", - "Repeater ID:": "中继站 ID", - "WebSocket": "WebSocket", - "Encrypt": "加密", - "Host:": "主机:", - "Port:": "端口:", - "Path:": "路径:", - "Automatic Reconnect": "自动重新链接", - "Reconnect Delay (ms):": "重新链接间隔 (ms):", - "Logging:": "日志级别:", - "Disconnect": "终端链接", - "Connect": "连接", - "Password:": "密码:", - "Cancel": "取消" -} \ No newline at end of file diff --git a/kasmweb/app/locale/zh_TW.json b/kasmweb/app/locale/zh_TW.json deleted file mode 100644 index 8ddf813..0000000 --- a/kasmweb/app/locale/zh_TW.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "Connecting...": "連線中...", - "Disconnecting...": "正在中斷連線...", - "Reconnecting...": "重新連線中...", - "Internal error": "內部錯誤", - "Must set host": "請提供主機資訊", - "Connected (encrypted) to ": "已加密連線到", - "Connected (unencrypted) to ": "未加密連線到", - "Something went wrong, connection is closed": "發生錯誤,連線已關閉", - "Failed to connect to server": "無法連線到伺服器", - "Disconnected": "連線已中斷", - "New connection has been rejected with reason: ": "連線被拒絕,原因:", - "New connection has been rejected": "連線被拒絕", - "Password is required": "請提供密碼", - "noVNC encountered an error:": "noVNC 遇到一個錯誤:", - "Hide/Show the control bar": "顯示/隱藏控制列", - "Move/Drag Viewport": "拖放顯示範圍", - "viewport drag": "顯示範圍拖放", - "Active Mouse Button": "啟用滑鼠按鍵", - "No mousebutton": "無滑鼠按鍵", - "Left mousebutton": "滑鼠左鍵", - "Middle mousebutton": "滑鼠中鍵", - "Right mousebutton": "滑鼠右鍵", - "Keyboard": "鍵盤", - "Show Keyboard": "顯示鍵盤", - "Extra keys": "額外按鍵", - "Show Extra Keys": "顯示額外按鍵", - "Ctrl": "Ctrl", - "Toggle Ctrl": "切換 Ctrl", - "Alt": "Alt", - "Toggle Alt": "切換 Alt", - "Send Tab": "送出 Tab 鍵", - "Tab": "Tab", - "Esc": "Esc", - "Send Escape": "送出 Escape 鍵", - "Ctrl+Alt+Del": "Ctrl-Alt-Del", - "Send Ctrl-Alt-Del": "送出 Ctrl-Alt-Del 快捷鍵", - "Shutdown/Reboot": "關機/重新啟動", - "Shutdown/Reboot...": "關機/重新啟動...", - "Power": "電源", - "Shutdown": "關機", - "Reboot": "重新啟動", - "Reset": "重設", - "Clipboard": "剪貼簿", - "Clear": "清除", - "Fullscreen": "全螢幕", - "Settings": "設定", - "Shared Mode": "分享模式", - "View Only": "僅檢視", - "Clip to Window": "限制/裁切視窗大小", - "Scaling Mode:": "縮放模式:", - "None": "無", - "Local Scaling": "本機縮放", - "Remote Resizing": "遠端調整大小", - "Advanced": "進階", - "Repeater ID:": "中繼站 ID", - "WebSocket": "WebSocket", - "Encrypt": "加密", - "Host:": "主機:", - "Port:": "連接埠:", - "Path:": "路徑:", - "Automatic Reconnect": "自動重新連線", - "Reconnect Delay (ms):": "重新連線間隔 (ms):", - "Logging:": "日誌級別:", - "Disconnect": "中斷連線", - "Connect": "連線", - "Password:": "密碼:", - "Cancel": "取消" -} \ No newline at end of file diff --git a/kasmweb/app/localization.js b/kasmweb/app/localization.js deleted file mode 100644 index 100901c..0000000 --- a/kasmweb/app/localization.js +++ /dev/null @@ -1,172 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -/* - * Localization Utilities - */ - -export class Localizer { - constructor() { - // Currently configured language - this.language = 'en'; - - // Current dictionary of translations - this.dictionary = undefined; - } - - // Configure suitable language based on user preferences - setup(supportedLanguages) { - this.language = 'en'; // Default: US English - - /* - * Navigator.languages only available in Chrome (32+) and FireFox (32+) - * Fall back to navigator.language for other browsers - */ - let userLanguages; - if (typeof window.navigator.languages == 'object') { - userLanguages = window.navigator.languages; - } else { - userLanguages = [navigator.language || navigator.userLanguage]; - } - - for (let i = 0;i < userLanguages.length;i++) { - const userLang = userLanguages[i] - .toLowerCase() - .replace("_", "-") - .split("-"); - - // Built-in default? - if ((userLang[0] === 'en') && - ((userLang[1] === undefined) || (userLang[1] === 'us'))) { - return; - } - - // First pass: perfect match - for (let j = 0; j < supportedLanguages.length; j++) { - const supLang = supportedLanguages[j] - .toLowerCase() - .replace("_", "-") - .split("-"); - - if (userLang[0] !== supLang[0]) { - continue; - } - if (userLang[1] !== supLang[1]) { - continue; - } - - this.language = supportedLanguages[j]; - return; - } - - // Second pass: fallback - for (let j = 0;j < supportedLanguages.length;j++) { - const supLang = supportedLanguages[j] - .toLowerCase() - .replace("_", "-") - .split("-"); - - if (userLang[0] !== supLang[0]) { - continue; - } - if (supLang[1] !== undefined) { - continue; - } - - this.language = supportedLanguages[j]; - return; - } - } - } - - // Retrieve localised text - get(id) { - if (typeof this.dictionary !== 'undefined' && this.dictionary[id]) { - return this.dictionary[id]; - } else { - return id; - } - } - - // Traverses the DOM and translates relevant fields - // See https://html.spec.whatwg.org/multipage/dom.html#attr-translate - translateDOM() { - const self = this; - - function process(elem, enabled) { - function isAnyOf(searchElement, items) { - return items.indexOf(searchElement) !== -1; - } - - function translateAttribute(elem, attr) { - const str = self.get(elem.getAttribute(attr)); - elem.setAttribute(attr, str); - } - - function translateTextNode(node) { - const str = self.get(node.data.trim()); - node.data = str; - } - - if (elem.hasAttribute("translate")) { - if (isAnyOf(elem.getAttribute("translate"), ["", "yes"])) { - enabled = true; - } else if (isAnyOf(elem.getAttribute("translate"), ["no"])) { - enabled = false; - } - } - - if (enabled) { - if (elem.hasAttribute("abbr") && - elem.tagName === "TH") { - translateAttribute(elem, "abbr"); - } - if (elem.hasAttribute("alt") && - isAnyOf(elem.tagName, ["AREA", "IMG", "INPUT"])) { - translateAttribute(elem, "alt"); - } - if (elem.hasAttribute("download") && - isAnyOf(elem.tagName, ["A", "AREA"])) { - translateAttribute(elem, "download"); - } - if (elem.hasAttribute("label") && - isAnyOf(elem.tagName, ["MENUITEM", "MENU", "OPTGROUP", - "OPTION", "TRACK"])) { - translateAttribute(elem, "label"); - } - // FIXME: Should update "lang" - if (elem.hasAttribute("placeholder") && - isAnyOf(elem.tagName, ["INPUT", "TEXTAREA"])) { - translateAttribute(elem, "placeholder"); - } - if (elem.hasAttribute("title")) { - translateAttribute(elem, "title"); - } - if (elem.hasAttribute("value") && - elem.tagName === "INPUT" && - isAnyOf(elem.getAttribute("type"), ["reset", "button", "submit"])) { - translateAttribute(elem, "value"); - } - } - - for (let i = 0; i < elem.childNodes.length; i++) { - const node = elem.childNodes[i]; - if (node.nodeType === node.ELEMENT_NODE) { - process(node, enabled); - } else if (node.nodeType === node.TEXT_NODE && enabled) { - translateTextNode(node); - } - } - } - - process(document.body, true); - } -} - -export const l10n = new Localizer(); -export default l10n.get.bind(l10n); diff --git a/kasmweb/app/sounds/CREDITS b/kasmweb/app/sounds/CREDITS deleted file mode 100644 index ec1fb55..0000000 --- a/kasmweb/app/sounds/CREDITS +++ /dev/null @@ -1,4 +0,0 @@ -bell - Copyright: Dr. Richard Boulanger et al - URL: http://www.archive.org/details/Berklee44v12 - License: CC-BY Attribution 3.0 Unported diff --git a/kasmweb/app/sounds/bell.mp3 b/kasmweb/app/sounds/bell.mp3 deleted file mode 100644 index fdbf149..0000000 Binary files a/kasmweb/app/sounds/bell.mp3 and /dev/null differ diff --git a/kasmweb/app/sounds/bell.oga b/kasmweb/app/sounds/bell.oga deleted file mode 100644 index 144d2b3..0000000 Binary files a/kasmweb/app/sounds/bell.oga and /dev/null differ diff --git a/kasmweb/app/styles/Orbitron700.ttf b/kasmweb/app/styles/Orbitron700.ttf deleted file mode 100644 index e28729d..0000000 Binary files a/kasmweb/app/styles/Orbitron700.ttf and /dev/null differ diff --git a/kasmweb/app/styles/Orbitron700.woff b/kasmweb/app/styles/Orbitron700.woff deleted file mode 100644 index 61db630..0000000 Binary files a/kasmweb/app/styles/Orbitron700.woff and /dev/null differ diff --git a/kasmweb/app/styles/base.css b/kasmweb/app/styles/base.css deleted file mode 100644 index 78e8fd4..0000000 --- a/kasmweb/app/styles/base.css +++ /dev/null @@ -1,926 +0,0 @@ -/* - * noVNC base CSS - * Copyright (C) 2018 The noVNC Authors - * noVNC is licensed under the MPL 2.0 (see LICENSE.txt) - * This file is licensed under the 2-Clause BSD license (see LICENSE.txt). - */ - -/* - * Z index layers: - * - * 0: Main screen - * 10: Control bar - * 50: Transition blocker - * 60: Connection popups - * 100: Status bar - * ... - * 1000: Javascript crash - * ... - * 10000: Max (used for polyfills) - */ - -body { - margin:0; - padding:0; - font-family: Helvetica; - /*Background image with light grey curve.*/ - /*background-color:#494949; - background-repeat:no-repeat; - background-position:right bottom; */ - background: white url('../images/icons/kasm_logo.png') no-repeat fixed center; - height:100%; - touch-action: none; -} - -html { - height:100%; -} - -.noVNC_only_touch.noVNC_hidden { - display: none; -} - -.noVNC_disabled { - color: rgb(128, 128, 128); -} - -/* ---------------------------------------- - * Spinner - * ---------------------------------------- - */ - -.noVNC_spinner { - position: relative; -} -.noVNC_spinner, .noVNC_spinner::before, .noVNC_spinner::after { - width: 10px; - height: 10px; - border-radius: 2px; - box-shadow: -60px 10px 0 white; - animation: noVNC_spinner 1.0s linear infinite; -} -.noVNC_spinner::before { - content: ""; - position: absolute; - left: 0px; - top: 0px; - animation-delay: -0.1s; -} -.noVNC_spinner::after { - content: ""; - position: absolute; - top: 0px; - left: 0px; - animation-delay: 0.1s; -} -@keyframes noVNC_spinner { - 0% { box-shadow: -60px 10px 0 rgba(0, 135, 200, 0); width: 20px; } - 25% { box-shadow: 20px 10px 0 rgba(0, 135, 200, 1); width: 10px; } - 50% { box-shadow: 60px 10px 0 rgba(0, 135, 200, 0); width: 10px; } -} - -/* ---------------------------------------- - * Input Elements - * ---------------------------------------- - */ - -input[type=input], input[type=password], input[type=number], -input:not([type]), textarea { - /* Disable default rendering */ - -webkit-appearance: none; - -moz-appearance: none; - background: none; - - margin: 2px; - padding: 2px; - border: 1px solid rgb(192, 192, 192); - border-radius: 5px; - color: black; - background: linear-gradient(to top, rgb(255, 255, 255) 80%, rgb(240, 240, 240)); -} - -input[type=button], input[type=submit], select { - /* Disable default rendering */ - -webkit-appearance: none; - -moz-appearance: none; - background: none; - - margin: 2px; - padding: 2px; - border: 1px solid rgb(192, 192, 192); - border-bottom-width: 2px; - border-radius: 5px; - color: black; - background: linear-gradient(to top, rgb(255, 255, 255), rgb(240, 240, 240)); - - /* This avoids it jumping around when :active */ - vertical-align: middle; -} - -input[type=button], input[type=submit] { - padding-left: 20px; - padding-right: 20px; -} - -option { - color: black; - background: white; -} - -input[type=input]:focus, input[type=password]:focus, -input:not([type]):focus, input[type=button]:focus, -input[type=submit]:focus, -textarea:focus, select:focus { - box-shadow: 0px 0px 3px rgba(74, 144, 217, 0.5); - border-color: rgb(74, 144, 217); - outline: none; -} - -input[type=button]::-moz-focus-inner, -input[type=submit]::-moz-focus-inner { - border: none; -} - -input[type=input]:disabled, input[type=password]:disabled, -input:not([type]):disabled, input[type=button]:disabled, -input[type=submit]:disabled, input[type=number]:disabled, -textarea:disabled, select:disabled { - color: rgb(128, 128, 128); - background: rgb(240, 240, 240); -} - -input[type=button]:active, input[type=submit]:active, -select:active { - border-bottom-width: 1px; - margin-top: 3px; -} - -:root:not(.noVNC_touch) input[type=button]:hover:not(:disabled), -:root:not(.noVNC_touch) input[type=submit]:hover:not(:disabled), -:root:not(.noVNC_touch) select:hover:not(:disabled) { - background: linear-gradient(to top, rgb(255, 255, 255), rgb(250, 250, 250)); -} - -/* ---------------------------------------- - * WebKit centering hacks - * ---------------------------------------- - */ - -.noVNC_center { - /* - * This is a workaround because webkit misrenders transforms and - * uses non-integer coordinates, resulting in blurry content. - * Ideally we'd use "top: 50%; transform: translateY(-50%);" on - * the objects instead. - */ - display: flex; - align-items: center; - justify-content: center; - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - pointer-events: none; -} -.noVNC_center > * { - pointer-events: auto; -} -.noVNC_vcenter { - display: flex; - flex-direction: column; - justify-content: center; - position: fixed; - top: 0; - left: 0; - height: 100%; - pointer-events: none; -} -.noVNC_vcenter > * { - pointer-events: auto; -} - -/* ---------------------------------------- - * Layering - * ---------------------------------------- - */ - -.noVNC_connect_layer { - z-index: 60; -} - -/* ---------------------------------------- - * Fallback error - * ---------------------------------------- - */ - -#noVNC_fallback_error { - z-index: 1000; - visibility: hidden; -} -#noVNC_fallback_error.noVNC_open { - visibility: visible; -} - -#noVNC_fallback_error > div { - max-width: 90%; - padding: 15px; - - transition: 0.5s ease-in-out; - - transform: translateY(-50px); - opacity: 0; - - text-align: center; - font-weight: bold; - color: #fff; - - - box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); - background: rgba(33, 130, 177, 0.8); -} -#noVNC_fallback_error.noVNC_open > div { - transform: translateY(0); - opacity: 1; -} - -#noVNC_fallback_errormsg { - font-weight: normal; -} - -#noVNC_fallback_errormsg .noVNC_message { - display: inline-block; - text-align: left; - font-family: monospace; - white-space: pre-wrap; -} - -#noVNC_fallback_error .noVNC_location { - font-style: italic; - font-size: 0.8em; - color: rgba(255, 255, 255, 0.8); -} - -#noVNC_fallback_error .noVNC_stack { - max-height: 50vh; - padding: 10px; - margin: 10px; - font-size: 0.8em; - text-align: left; - font-family: monospace; - white-space: pre; - border: 1px solid rgba(0, 0, 0, 0.5); - background: rgba(0, 0, 0, 0.2); - overflow: auto; -} - -/* ---------------------------------------- - * Connection Stats - * ---------------------------------------- - */ -#noVNC_connection_stats { - top: 0; - left: auto; - right: 0; - position: fixed; - background: #9fa5a2d4; - color: #00ffa2d4; - visibility: hidden; -} - -/* ---------------------------------------- - * Control Bar - * ---------------------------------------- - */ - -#noVNC_control_bar_anchor { - /* The anchor is needed to get z-stacking to work */ - position: fixed; - z-index: 10; - - transition: 0.5s ease-in-out; - - /* Edge misrenders animations wihthout this */ - transform: translateX(0); -} -:root.noVNC_connected #noVNC_control_bar_anchor.noVNC_idle { - opacity: 0.8; -} -#noVNC_control_bar_anchor.noVNC_right { - left: auto; - right: 0; -} - -#noVNC_control_bar { - position: relative; - left: -100%; - - transition: 0.5s ease-in-out; - - background-color: rgb(80, 89, 101); - border-radius: 0 10px 10px 0; - -} -#noVNC_control_bar.noVNC_open { - box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); - left: 0; -} -#noVNC_control_bar::before { - /* This extra element is to get a proper shadow */ - content: ""; - position: absolute; - z-index: -1; - height: 100%; - width: 30px; - left: -30px; - transition: box-shadow 0.5s ease-in-out; -} -#noVNC_control_bar.noVNC_open::before { - box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); -} -.noVNC_right #noVNC_control_bar { - left: 100%; - border-radius: 10px 0 0 10px; -} -.noVNC_right #noVNC_control_bar.noVNC_open { - left: 0; -} -.noVNC_right #noVNC_control_bar::before { - visibility: hidden; -} - -#noVNC_control_bar_handle { - position: absolute; - left: -15px; - top: 0; - transform: translateY(35px); - width: calc(100% + 30px); - height: 50px; - z-index: -1; - cursor: pointer; - border-radius: 5px; - background-color: rgb(83, 99, 122); - background-image: url("../images/handle_bg.svg"); - background-repeat: no-repeat; - background-position: right; - box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.5); -} -#noVNC_control_bar_handle:after { - content: ""; - transition: transform 0.5s ease-in-out; - background: url("../images/handle.svg"); - position: absolute; - top: 22px; /* (50px-6px)/2 */ - right: 5px; - width: 5px; - height: 6px; -} -#noVNC_control_bar.noVNC_open #noVNC_control_bar_handle:after { - transform: translateX(1px) rotate(180deg); -} -:root:not(.noVNC_connected) #noVNC_control_bar_handle { - display: none; -} -.noVNC_right #noVNC_control_bar_handle { - background-position: left; -} -.noVNC_right #noVNC_control_bar_handle:after { - left: 5px; - right: 0; - transform: translateX(1px) rotate(180deg); -} -.noVNC_right #noVNC_control_bar.noVNC_open #noVNC_control_bar_handle:after { - transform: none; -} -#noVNC_control_bar_handle div { - position: absolute; - right: -35px; - top: 0; - width: 50px; - height: 50px; -} -:root:not(.noVNC_touch) #noVNC_control_bar_handle div { - display: none; -} -.noVNC_right #noVNC_control_bar_handle div { - left: -35px; - right: auto; -} - -#noVNC_control_bar .noVNC_scroll { - max-height: 100vh; /* Chrome is buggy with 100% */ - overflow-x: hidden; - overflow-y: auto; - padding: 0 10px 0 5px; -} -.noVNC_right #noVNC_control_bar .noVNC_scroll { - padding: 0 5px 0 10px; -} - -/* Control bar hint */ -#noVNC_control_bar_hint { - position: fixed; - left: calc(100vw - 50px); - right: auto; - top: 50%; - transform: translateY(-50%) scale(0); - width: 100px; - height: 50%; - max-height: 600px; - - visibility: hidden; - opacity: 0; - transition: 0.2s ease-in-out; - background: transparent; - box-shadow: 0 0 10px black, inset 0 0 10px 10px rgba(110, 132, 163, 0.8); - border-radius: 10px; - transition-delay: 0s; -} -#noVNC_control_bar_anchor.noVNC_right #noVNC_control_bar_hint{ - left: auto; - right: calc(100vw - 50px); -} -#noVNC_control_bar_hint.noVNC_active { - visibility: visible; - opacity: 1; - transition-delay: 0.2s; - transform: translateY(-50%) scale(1); -} - -/* General button style */ -.noVNC_button { - display: block; - padding: 4px 4px; - margin: 10px 0; - vertical-align: middle; - border:1px solid rgba(255, 255, 255, 0.2); - border-radius: 6px; -} -.noVNC_button.noVNC_selected { - border-color: rgba(0, 0, 0, 0.8); - background: rgba(0, 0, 0, 0.5); -} -.noVNC_button:disabled { - opacity: 0.4; -} -.noVNC_button:focus { - outline: none; -} -.noVNC_button:active { - padding-top: 5px; - padding-bottom: 3px; -} -/* Android browsers don't properly update hover state if touch events - * are intercepted, but focus should be safe to display */ -:root:not(.noVNC_touch) .noVNC_button.noVNC_selected:hover, -.noVNC_button.noVNC_selected:focus { - border-color: rgba(0, 0, 0, 0.4); - background: rgba(0, 0, 0, 0.2); -} -:root:not(.noVNC_touch) .noVNC_button:hover, -.noVNC_button:focus { - background: rgba(255, 255, 255, 0.2); -} -.noVNC_button.noVNC_hidden { - display: none; -} - -/* Panels */ -.noVNC_panel { - transform: translateX(25px); - - transition: 0.5s ease-in-out; - - max-height: 100vh; /* Chrome is buggy with 100% */ - overflow-x: hidden; - overflow-y: auto; - - visibility: hidden; - opacity: 0; - - padding: 15px; - - background: #fff; - border-radius: 10px; - color: #000; - border: 2px solid #E0E0E0; - box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); -} -.noVNC_panel.noVNC_open { - visibility: visible; - opacity: 1; - transform: translateX(75px); -} -.noVNC_right .noVNC_vcenter { - left: auto; - right: 0; -} -.noVNC_right .noVNC_panel { - transform: translateX(-25px); -} -.noVNC_right .noVNC_panel.noVNC_open { - transform: translateX(-75px); -} - -.noVNC_panel hr { - border: none; - border-top: 1px solid rgb(192, 192, 192); -} - -.noVNC_panel label { - display: block; - white-space: nowrap; -} - -.noVNC_panel .noVNC_heading { - background-color: rgb(110, 132, 163); - border-radius: 5px; - padding: 5px; - /* Compensate for padding in image */ - padding-right: 8px; - color: white; - font-size: 20px; - margin-bottom: 10px; - white-space: nowrap; -} -.noVNC_panel .noVNC_heading img { - vertical-align: bottom; -} - -.noVNC_submit { - float: right; -} - -/* Expanders */ -.noVNC_expander { - cursor: pointer; -} -.noVNC_expander::before { - content: url("../images/expander.svg"); - display: inline-block; - margin-right: 5px; - transition: 0.2s ease-in-out; -} -.noVNC_expander.noVNC_open::before { - transform: rotateZ(90deg); -} -.noVNC_expander ~ * { - margin: 5px; - margin-left: 10px; - padding: 5px; - background: rgba(0, 0, 0, 0.05); - border-radius: 5px; -} -.noVNC_expander:not(.noVNC_open) ~ * { - display: none; -} - -/* Control bar content */ - -#noVNC_control_bar .noVNC_logo { - font-size: 13px; - text-align: center; -} - -:root:not(.noVNC_connected) #noVNC_view_drag_button { - display: none; -} - -/* noVNC Touch Device only buttons */ -:root:not(.noVNC_connected) #noVNC_mobile_buttons { - display: none; -} -:root:not(.noVNC_touch) #noVNC_mobile_buttons { - display: none; -} - -/* Extra manual keys */ -:root:not(.noVNC_connected) #noVNC_extra_keys { - display: none; -} - -#noVNC_modifiers { - background-color: rgb(92, 92, 92); - border: none; - padding: 0 10px; -} - -/* Shutdown/Reboot */ -:root:not(.noVNC_connected) #noVNC_power_button { - display: none; -} -#noVNC_power { -} -#noVNC_power_buttons { - display: none; -} - -#noVNC_power input[type=button] { - width: 100%; -} - -/* Clipboard */ -:root:not(.noVNC_connected) #noVNC_clipboard_button { - display: none; -} -#noVNC_clipboard { - /* Full screen, minus padding and left and right margins */ - max-width: calc(100vw - 2*15px - 75px - 25px); -} -#noVNC_clipboard_text { - width: 500px; - max-width: 100%; -} - -/* Settings */ -#noVNC_settings { -} -#noVNC_settings ul { - list-style: none; - margin: 0px; - padding: 0px; -} -#noVNC_setting_port { - width: 80px; -} -#noVNC_setting_path { - width: 100px; -} - -/* Connection Controls */ -:root:not(.noVNC_connected) #noVNC_disconnect_button { - display: none; -} - -/* ---------------------------------------- - * Status Dialog - * ---------------------------------------- - */ - -#noVNC_status { - position: fixed; - top: 0; - left: 0; - width: 100%; - z-index: 100; - transform: translateY(-100%); - - cursor: pointer; - - transition: 0.5s ease-in-out; - - visibility: hidden; - opacity: 0; - - padding: 5px; - - display: flex; - flex-direction: row; - justify-content: center; - align-content: center; - - line-height: 25px; - word-wrap: break-word; - color: #fff; - - border-bottom: 1px solid rgba(0, 0, 0, 0.9); -} -#noVNC_status.noVNC_open { - transform: translateY(0); - visibility: visible; - opacity: 1; -} - -#noVNC_status::before { - content: ""; - display: inline-block; - width: 25px; - height: 25px; - margin-right: 5px; -} - -#noVNC_status.noVNC_status_normal { - background: rgba(128,128,128,0.9); -} -#noVNC_status.noVNC_status_normal::before { - content: url("../images/info.svg") " "; -} -#noVNC_status.noVNC_status_error { - background: rgba(200,55,55,0.9); -} -#noVNC_status.noVNC_status_error::before { - content: url("../images/error.svg") " "; -} -#noVNC_status.noVNC_status_warn { - background: rgba(180,180,30,0.9); -} -#noVNC_status.noVNC_status_warn::before { - content: url("../images/warning.svg") " "; -} - -/* ---------------------------------------- - * Connect Dialog - * ---------------------------------------- - */ - -#noVNC_connect_dlg { - transition: 0.5s ease-in-out; - - transform: scale(0, 0); - visibility: hidden; - opacity: 0; -} -#noVNC_connect_dlg.noVNC_open { - transform: scale(1, 1); - visibility: visible; - opacity: 1; -} -#noVNC_connect_dlg .noVNC_logo { - transition: 0.5s ease-in-out; - padding: 10px; - margin-bottom: 10px; - - font-size: 80px; - text-align: center; - - border-radius: 5px; -} -@media (max-width: 440px) { - #noVNC_connect_dlg { - max-width: calc(100vw - 100px); - } - #noVNC_connect_dlg .noVNC_logo { - font-size: calc(25vw - 30px); - } -} -#noVNC_connect_button { - cursor: pointer; - - /* - padding: 10px; - - color: white; - background-color: rgb(110, 132, 163); - border-radius: 12px; - box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); - */ - - text-align: center; - font-size: 20px; - margin-top: 130px; -} -#noVNC_connect_button div { - margin: 2px; - padding: 5px 30px; - border: 1px solid rgb(83, 99, 122); - border-bottom-width: 2px; - border-radius: 5px; - background: linear-gradient(to top, rgb(110, 132, 163), rgb(99, 119, 147)); - - /* This avoids it jumping around when :active */ - vertical-align: middle; - color: white; -} -#noVNC_connect_button div:active { - border-bottom-width: 1px; - margin-top: 3px; -} -:root:not(.noVNC_touch) #noVNC_connect_button div:hover { - background: linear-gradient(to top, rgb(110, 132, 163), rgb(105, 125, 155)); -} - -#noVNC_connect_button img { - vertical-align: bottom; - height: 1.3em; -} - -/* ---------------------------------------- - * Password Dialog - * ---------------------------------------- - */ - -#noVNC_password_dlg { - position: relative; - - transform: translateY(-50px); -} -#noVNC_password_dlg.noVNC_open { - transform: translateY(0); -} -#noVNC_password_dlg ul { - list-style: none; - margin: 0px; - padding: 0px; -} - -/* ---------------------------------------- - * Main Area - * ---------------------------------------- - */ - -/* Transition screen */ -#noVNC_transition { - display: none; - - position: fixed; - top: 0; - left: 0; - bottom: 0; - right: 0; - - color: #0084C2; - background: white url('../images/icons/kasm_logo.png') no-repeat fixed center; - z-index: 50; - - /*display: flex;*/ - align-items: center; - justify-content: center; - flex-direction: column; - - -webkit-transition: opacity 1s ease-in-out; - -moz-transition: opacity 1s ease-in-out; - -ms-transition: opacity 1s ease-in-out; - -o-transition: opacity 1s ease-in-out; - opacity: 1; -} -:root.noVNC_loading #noVNC_transition, -:root.noVNC_connecting #noVNC_transition, -:root.noVNC_disconnecting #noVNC_transition, -:root.noVNC_reconnecting #noVNC_transition { - display: flex; -} -:root:not(.noVNC_reconnecting) #noVNC_cancel_reconnect_button { - display: none; -} -#noVNC_transition_text { - font-size: 1.5em; - margin-top: 125px; -} - -/* Main container */ -#noVNC_container { - width: 100%; - height: 100%; - background-color: rgb(74, 144, 217, 0.5); - border-bottom-right-radius: 800px 600px; - /*border-top-left-radius: 800px 600px;*/ -} - -#noVNC_keyboardinput { - width: 1px; - height: 1px; - background-color: #fff; - color: #fff; - border: 0; - position: absolute; - left: -40px; - z-index: -1; - ime-mode: disabled; -} - -/*Default noVNC logo.*/ -/* From: http://fonts.googleapis.com/css?family=Orbitron:700 */ -@font-face { - font-family: 'Orbitron'; - font-style: normal; - font-weight: 700; - src: local('?'), url('Orbitron700.woff') format('woff'), - url('Orbitron700.ttf') format('truetype'); -} - -.noVNC_logo { - color:yellow; - font-family: 'Orbitron', 'OrbitronTTF', sans-serif; - line-height:90%; - text-shadow: 0.1em 0.1em 0 black; -} -.noVNC_logo span{ - color:green; -} - -#noVNC_bell { - display: none; -} - -/* ---------------------------------------- - * Media sizing - * ---------------------------------------- - */ - -@media screen and (max-width: 640px){ - #noVNC_logo { - font-size: 150px; - } -} - -@media screen and (min-width: 321px) and (max-width: 480px) { - #noVNC_logo { - font-size: 110px; - } -} - -@media screen and (max-width: 320px) { - #noVNC_logo { - font-size: 90px; - } -} diff --git a/kasmweb/app/styles/bootstrap.min.css b/kasmweb/app/styles/bootstrap.min.css deleted file mode 100644 index ed3905e..0000000 --- a/kasmweb/app/styles/bootstrap.min.css +++ /dev/null @@ -1,6 +0,0 @@ -/*! - * Bootstrap v3.3.7 (http://getbootstrap.com) - * Copyright 2011-2016 Twitter, Inc. - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) - *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\002a"}.glyphicon-plus:before{content:"\002b"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-cd:before{content:"\e201"}.glyphicon-save-file:before{content:"\e202"}.glyphicon-open-file:before{content:"\e203"}.glyphicon-level-up:before{content:"\e204"}.glyphicon-copy:before{content:"\e205"}.glyphicon-paste:before{content:"\e206"}.glyphicon-alert:before{content:"\e209"}.glyphicon-equalizer:before{content:"\e210"}.glyphicon-king:before{content:"\e211"}.glyphicon-queen:before{content:"\e212"}.glyphicon-pawn:before{content:"\e213"}.glyphicon-bishop:before{content:"\e214"}.glyphicon-knight:before{content:"\e215"}.glyphicon-baby-formula:before{content:"\e216"}.glyphicon-tent:before{content:"\26fa"}.glyphicon-blackboard:before{content:"\e218"}.glyphicon-bed:before{content:"\e219"}.glyphicon-apple:before{content:"\f8ff"}.glyphicon-erase:before{content:"\e221"}.glyphicon-hourglass:before{content:"\231b"}.glyphicon-lamp:before{content:"\e223"}.glyphicon-duplicate:before{content:"\e224"}.glyphicon-piggy-bank:before{content:"\e225"}.glyphicon-scissors:before{content:"\e226"}.glyphicon-bitcoin:before{content:"\e227"}.glyphicon-btc:before{content:"\e227"}.glyphicon-xbt:before{content:"\e227"}.glyphicon-yen:before{content:"\00a5"}.glyphicon-jpy:before{content:"\00a5"}.glyphicon-ruble:before{content:"\20bd"}.glyphicon-rub:before{content:"\20bd"}.glyphicon-scale:before{content:"\e230"}.glyphicon-ice-lolly:before{content:"\e231"}.glyphicon-ice-lolly-tasted:before{content:"\e232"}.glyphicon-education:before{content:"\e233"}.glyphicon-option-horizontal:before{content:"\e234"}.glyphicon-option-vertical:before{content:"\e235"}.glyphicon-menu-hamburger:before{content:"\e236"}.glyphicon-modal-window:before{content:"\e237"}.glyphicon-oil:before{content:"\e238"}.glyphicon-grain:before{content:"\e239"}.glyphicon-sunglasses:before{content:"\e240"}.glyphicon-text-size:before{content:"\e241"}.glyphicon-text-color:before{content:"\e242"}.glyphicon-text-background:before{content:"\e243"}.glyphicon-object-align-top:before{content:"\e244"}.glyphicon-object-align-bottom:before{content:"\e245"}.glyphicon-object-align-horizontal:before{content:"\e246"}.glyphicon-object-align-left:before{content:"\e247"}.glyphicon-object-align-vertical:before{content:"\e248"}.glyphicon-object-align-right:before{content:"\e249"}.glyphicon-triangle-right:before{content:"\e250"}.glyphicon-triangle-left:before{content:"\e251"}.glyphicon-triangle-bottom:before{content:"\e252"}.glyphicon-triangle-top:before{content:"\e253"}.glyphicon-console:before{content:"\e254"}.glyphicon-superscript:before{content:"\e255"}.glyphicon-subscript:before{content:"\e256"}.glyphicon-menu-left:before{content:"\e257"}.glyphicon-menu-right:before{content:"\e258"}.glyphicon-menu-down:before{content:"\e259"}.glyphicon-menu-up:before{content:"\e260"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.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}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:focus,a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:focus,a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:focus,a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:focus,a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:focus,a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:focus,a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:focus,a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:focus,a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:focus,a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:focus,a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:''}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=checkbox]:focus,input[type=radio]:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control::-ms-expand{background-color:transparent;border:0}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date].form-control,input[type=time].form-control,input[type=datetime-local].form-control,input[type=month].form-control{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=time],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=time],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-top:4px\9;margin-left:-20px}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.checkbox-inline.disabled,.radio-inline.disabled,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio-inline{cursor:not-allowed}.checkbox.disabled label,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .radio label{cursor:not-allowed}.form-control-static{min-height:34px;padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.form-group-sm select.form-control{height:30px;line-height:30px}.form-group-sm select[multiple].form-control,.form-group-sm textarea.form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:32px;padding:6px 10px;font-size:12px;line-height:1.5}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.form-group-lg select.form-control{height:46px;line-height:46px}.form-group-lg select[multiple].form-control,.form-group-lg textarea.form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:38px;padding:11px 16px;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.form-group-lg .form-control+.form-control-feedback,.input-group-lg+.form-control-feedback,.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.form-group-sm .form-control+.form-control-feedback,.input-group-sm+.form-control-feedback,.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:11px;font-size:18px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px;font-size:12px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.focus,.btn-default:focus{color:#333;background-color:#e6e6e6;border-color:#8c8c8c}.btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active.focus,.btn-default.active:focus,.btn-default.active:hover,.btn-default:active.focus,.btn-default:active:focus,.btn-default:active:hover,.open>.dropdown-toggle.btn-default.focus,.open>.dropdown-toggle.btn-default:focus,.open>.dropdown-toggle.btn-default:hover{color:#333;background-color:#d4d4d4;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled.focus,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled].focus,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#286090;border-color:#122b40}.btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active.focus,.btn-primary.active:focus,.btn-primary.active:hover,.btn-primary:active.focus,.btn-primary:active:focus,.btn-primary:active:hover,.open>.dropdown-toggle.btn-primary.focus,.open>.dropdown-toggle.btn-primary:focus,.open>.dropdown-toggle.btn-primary:hover{color:#fff;background-color:#204d74;border-color:#122b40}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled.focus,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled].focus,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#449d44;border-color:#255625}.btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active.focus,.btn-success.active:focus,.btn-success.active:hover,.btn-success:active.focus,.btn-success:active:focus,.btn-success:active:hover,.open>.dropdown-toggle.btn-success.focus,.open>.dropdown-toggle.btn-success:focus,.open>.dropdown-toggle.btn-success:hover{color:#fff;background-color:#398439;border-color:#255625}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled.focus,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled].focus,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#31b0d5;border-color:#1b6d85}.btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active.focus,.btn-info.active:focus,.btn-info.active:hover,.btn-info:active.focus,.btn-info:active:focus,.btn-info:active:hover,.open>.dropdown-toggle.btn-info.focus,.open>.dropdown-toggle.btn-info:focus,.open>.dropdown-toggle.btn-info:hover{color:#fff;background-color:#269abc;border-color:#1b6d85}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled.focus,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled].focus,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.focus,.btn-warning:focus{color:#fff;background-color:#ec971f;border-color:#985f0d}.btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active.focus,.btn-warning.active:focus,.btn-warning.active:hover,.btn-warning:active.focus,.btn-warning:active:focus,.btn-warning:active:hover,.open>.dropdown-toggle.btn-warning.focus,.open>.dropdown-toggle.btn-warning:focus,.open>.dropdown-toggle.btn-warning:hover{color:#fff;background-color:#d58512;border-color:#985f0d}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled.focus,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled].focus,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c9302c;border-color:#761c19}.btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active.focus,.btn-danger.active:focus,.btn-danger.active:hover,.btn-danger:active.focus,.btn-danger:active:focus,.btn-danger:active:hover,.open>.dropdown-toggle.btn-danger.focus,.open>.dropdown-toggle.btn-danger:focus,.open>.dropdown-toggle.btn-danger:hover{color:#fff;background-color:#ac2925;border-color:#761c19}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled.focus,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled].focus,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#337ab7;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-top:4px solid\9;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px dashed;border-bottom:4px solid\9}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn,.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group .form-control:focus{z-index:3}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{z-index:2;margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#337ab7;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{z-index:2;color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:3;color:#fff;cursor:default;background-color:#337ab7;border-color:#337ab7}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px;line-height:1.3333333}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px;line-height:1.5}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding-top:30px;padding-bottom:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{padding-right:15px;padding-left:15px;border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron,.container-fluid .jumbotron{padding-right:60px;padding-left:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-right:auto;margin-left:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{overflow:hidden;zoom:1}.media-body{width:10000px}.media-object{display:block}.media-object.img-thumbnail{max-width:none}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item,button.list-group-item{color:#555}a.list-group-item .list-group-item-heading,button.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover,button.list-group-item:focus,button.list-group-item:hover{color:#555;text-decoration:none;background-color:#f5f5f5}button.list-group-item{width:100%;text-align:left}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success,button.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading,button.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover,button.list-group-item-success.active,button.list-group-item-success.active:focus,button.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info,button.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading,button.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover,button.list-group-item-info.active,button.list-group-item-info.active:focus,button.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning,button.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading,button.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover,button.list-group-item-warning.active,button.list-group-item-warning.active:focus,button.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger,button.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading,button.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover,button.list-group-item-danger.active,button.list-group-item-danger.active:focus,button.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child{border-top-left-radius:0;border-top-right-radius:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-right:15px;padding-left:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;filter:alpha(opacity=0);opacity:0;line-break:auto}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px;bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);line-break:auto}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-inner>.item.active.right,.carousel-inner>.item.next{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);background-color:rgba(0,0,0,0);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:focus,.carousel-control:hover{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block;margin-top:-10px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;font-family:serif;line-height:1}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000\9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-10px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-10px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.modal-header:after,.modal-header:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{display:table;content:" "}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.modal-header:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-md,.visible-sm,.visible-xs{display:none!important}.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table!important}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table!important}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table!important}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table!important}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table!important}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} -/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/kasmweb/app/ui.js b/kasmweb/app/ui.js deleted file mode 100644 index 1e2d7a6..0000000 --- a/kasmweb/app/ui.js +++ /dev/null @@ -1,2034 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ -window._noVNC_has_module_support = true; -window.addEventListener("load", function() { - if (window._noVNC_has_module_support) return; - var loader = document.createElement("script"); - loader.src = "vendor/browser-es-module-loader/dist/browser-es-module-loader.js"; - document.head.appendChild(loader); -}); -window.addEventListener("load", function() { - var connect_btn_el = document.getElementById("noVNC_connect_button"); - if (typeof(connect_btn_el) != 'undefined' && connect_btn_el != null) - { - connect_btn_el.click(); - } -}); - -import * as Log from '../core/util/logging.js'; -import _, { l10n } from './localization.js'; -import { isTouchDevice, isSafari, isIOS, isAndroid, dragThreshold } - from '../core/util/browser.js'; -import { setCapture, getPointerEvent } from '../core/util/events.js'; -import KeyTable from "../core/input/keysym.js"; -import keysyms from "../core/input/keysymdef.js"; -import Keyboard from "../core/input/keyboard.js"; -import RFB from "../core/rfb.js"; -import * as WebUtil from "./webutil.js"; - - -var delta = 500; -var lastKeypressTime = 0; -var currentEventCount = -1; -var idleCounter = 0; - -const UI = { - - connected: false, - desktopName: "", - - statusTimeout: null, - hideKeyboardTimeout: null, - idleControlbarTimeout: null, - closeControlbarTimeout: null, - - controlbarGrabbed: false, - controlbarDrag: false, - controlbarMouseDownClientY: 0, - controlbarMouseDownOffsetY: 0, - - lastKeyboardinput: null, - defaultKeyboardinputLen: 100, - needToCheckClipboardChange: false, - - inhibit_reconnect: true, - reconnect_callback: null, - reconnect_password: null, - - prime(callback) { - if (document.readyState === "interactive" || document.readyState === "complete") { - UI.load(callback); - } else { - document.addEventListener('DOMContentLoaded', UI.load.bind(UI, callback)); - } - }, - - // Setup rfb object, load settings from browser storage, then call - // UI.init to setup the UI/menus - load(callback) { - WebUtil.initSettings(UI.start, callback); - }, - - // Render default UI and initialize settings menu - start(callback) { - - UI.initSettings(); - - // Translate the DOM - l10n.translateDOM(); - - // Adapt the interface for touch screen devices - if (isTouchDevice) { - document.documentElement.classList.add("noVNC_touch"); - // Remove the address bar - setTimeout(() => window.scrollTo(0, 1), 100); - } - - // Restore control bar position - if (WebUtil.readSetting('controlbar_pos') === 'right') { - UI.toggleControlbarSide(); - } - - UI.initFullscreen(); - - // Setup event handlers - UI.addControlbarHandlers(); - UI.addTouchSpecificHandlers(); - UI.addExtraKeysHandlers(); - UI.addMachineHandlers(); - UI.addConnectionControlHandlers(); - UI.addClipboardHandlers(); - UI.addSettingsHandlers(); - document.getElementById("noVNC_status") - .addEventListener('click', UI.hideStatus); - - // Bootstrap fallback input handler - UI.keyboardinputReset(); - - UI.openControlbar(); - - UI.updateVisualState('init'); - - document.documentElement.classList.remove("noVNC_loading"); - - let autoconnect = WebUtil.getConfigVar('autoconnect', false); - if (autoconnect === 'true' || autoconnect == '1') { - autoconnect = true; - UI.connect(); - } else { - autoconnect = false; - // Show the connect panel on first load unless autoconnecting - UI.openConnectPanel(); - } - - if (typeof callback === "function") { - callback(UI.rfb); - } - }, - - initFullscreen() { - // Only show the button if fullscreen is properly supported - // * Safari doesn't support alphanumerical input while in fullscreen - if (!isSafari() && - (document.documentElement.requestFullscreen || - document.documentElement.mozRequestFullScreen || - document.documentElement.webkitRequestFullscreen || - document.body.msRequestFullscreen)) { - document.getElementById('noVNC_fullscreen_button') - .classList.remove("noVNC_hidden"); - UI.addFullscreenHandlers(); - } - }, - - initSettings() { - // Logging selection dropdown - const llevels = ['error', 'warn', 'info', 'debug']; - for (let i = 0; i < llevels.length; i += 1) { - UI.addOption(document.getElementById('noVNC_setting_logging'), llevels[i], llevels[i]); - } - - // Settings with immediate effects - UI.initSetting('logging', 'warn'); - UI.updateLogging(); - - // if port == 80 (or 443) then it won't be present and should be - // set manually - let port = window.location.port; - if (!port) { - if (window.location.protocol.substring(0, 5) == 'https') { - port = 443; - } else if (window.location.protocol.substring(0, 4) == 'http') { - port = 80; - } - } - - /* Populate the controls if defaults are provided in the URL */ - UI.initSetting('host', window.location.hostname); - UI.initSetting('port', port); - UI.initSetting('encrypt', (window.location.protocol === "https:")); - UI.initSetting('view_clip', false); - UI.initSetting('shared', true); - UI.initSetting('view_only', false); - UI.initSetting('show_dot', false); - UI.initSetting('path', 'websockify'); - UI.initSetting('repeaterID', ''); - UI.initSetting('reconnect', false); - UI.initSetting('reconnect_delay', 5000); - UI.initSetting('idle_disconnect', 20); - UI.initSetting('prefer_local_cursor', true); - UI.initSetting('toggle_control_panel', false); - UI.initSetting('enable_perf_stats', false); - - if (WebUtil.isInsideKasmVDI()) { - UI.initSetting('video_quality', 1); - UI.initSetting('clipboard_up', false); - UI.initSetting('clipboard_down', false); - UI.initSetting('clipboard_seamless', false); - UI.initSetting('enable_webp', false); - UI.initSetting('resize', 'off'); - } else { - UI.initSetting('video_quality', 3); - UI.initSetting('clipboard_up', true); - UI.initSetting('clipboard_down', true); - UI.initSetting('clipboard_seamless', true); - UI.initSetting('enable_webp', true); - UI.initSetting('resize', 'remote'); - } - - UI.setupSettingLabels(); - }, - // Adds a link to the label elements on the corresponding input elements - setupSettingLabels() { - const labels = document.getElementsByTagName('LABEL'); - for (let i = 0; i < labels.length; i++) { - const htmlFor = labels[i].htmlFor; - if (htmlFor != '') { - const elem = document.getElementById(htmlFor); - if (elem) elem.label = labels[i]; - } else { - // If 'for' isn't set, use the first input element child - const children = labels[i].children; - for (let j = 0; j < children.length; j++) { - if (children[j].form !== undefined) { - children[j].label = labels[i]; - break; - } - } - } - } - }, - -/* ------^------- -* /INIT -* ============== -* EVENT HANDLERS -* ------v------*/ - - addControlbarHandlers() { - document.getElementById("noVNC_control_bar") - .addEventListener('mousemove', UI.activateControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('mouseup', UI.activateControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('mousedown', UI.activateControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('keydown', UI.activateControlbar); - - document.getElementById("noVNC_control_bar") - .addEventListener('mousedown', UI.keepControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('keydown', UI.keepControlbar); - - document.getElementById("noVNC_view_drag_button") - .addEventListener('click', UI.toggleViewDrag); - - document.getElementById("noVNC_control_bar_handle") - .addEventListener('mousedown', UI.controlbarHandleMouseDown); - document.getElementById("noVNC_control_bar_handle") - .addEventListener('mouseup', UI.controlbarHandleMouseUp); - document.getElementById("noVNC_control_bar_handle") - .addEventListener('mousemove', UI.dragControlbarHandle); - // resize events aren't available for elements - window.addEventListener('resize', UI.updateControlbarHandle); - - const exps = document.getElementsByClassName("noVNC_expander"); - for (let i = 0;i < exps.length;i++) { - exps[i].addEventListener('click', UI.toggleExpander); - } - }, - - addTouchSpecificHandlers() { - document.getElementById("noVNC_mouse_button0") - .addEventListener('click', () => UI.setMouseButton(1)); - document.getElementById("noVNC_mouse_button1") - .addEventListener('click', () => UI.setMouseButton(2)); - document.getElementById("noVNC_mouse_button2") - .addEventListener('click', () => UI.setMouseButton(4)); - document.getElementById("noVNC_mouse_button4") - .addEventListener('click', () => UI.setMouseButton(0)); - document.getElementById("noVNC_keyboard_button") - .addEventListener('click', UI.toggleVirtualKeyboard); - - UI.touchKeyboard = new Keyboard(document.getElementById('noVNC_keyboardinput')); - UI.touchKeyboard.onkeyevent = UI.keyEvent; - UI.touchKeyboard.grab(); - document.getElementById("noVNC_keyboardinput") - .addEventListener('input', UI.keyInput); - document.getElementById("noVNC_keyboardinput") - .addEventListener('focus', UI.onfocusVirtualKeyboard); - document.getElementById("noVNC_keyboardinput") - .addEventListener('blur', UI.onblurVirtualKeyboard); - document.getElementById("noVNC_keyboardinput") - .addEventListener('submit', () => false); - - document.documentElement - .addEventListener('mousedown', UI.keepVirtualKeyboard, true); - - document.getElementById("noVNC_control_bar") - .addEventListener('touchstart', UI.activateControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('touchmove', UI.activateControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('touchend', UI.activateControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('input', UI.activateControlbar); - - document.getElementById("noVNC_control_bar") - .addEventListener('touchstart', UI.keepControlbar); - document.getElementById("noVNC_control_bar") - .addEventListener('input', UI.keepControlbar); - - document.getElementById("noVNC_control_bar_handle") - .addEventListener('touchstart', UI.controlbarHandleMouseDown); - document.getElementById("noVNC_control_bar_handle") - .addEventListener('touchend', UI.controlbarHandleMouseUp); - document.getElementById("noVNC_control_bar_handle") - .addEventListener('touchmove', UI.dragControlbarHandle); - }, - - addExtraKeysHandlers() { - document.getElementById("noVNC_toggle_extra_keys_button") - .addEventListener('click', UI.toggleExtraKeys); - document.getElementById("noVNC_toggle_ctrl_button") - .addEventListener('click', UI.toggleCtrl); - document.getElementById("noVNC_toggle_windows_button") - .addEventListener('click', UI.toggleWindows); - document.getElementById("noVNC_toggle_alt_button") - .addEventListener('click', UI.toggleAlt); - document.getElementById("noVNC_send_tab_button") - .addEventListener('click', UI.sendTab); - document.getElementById("noVNC_send_esc_button") - .addEventListener('click', UI.sendEsc); - document.getElementById("noVNC_send_ctrl_alt_del_button") - .addEventListener('click', UI.sendCtrlAltDel); - }, - - addMachineHandlers() { - document.getElementById("noVNC_shutdown_button") - .addEventListener('click', () => UI.rfb.machineShutdown()); - document.getElementById("noVNC_reboot_button") - .addEventListener('click', () => UI.rfb.machineReboot()); - document.getElementById("noVNC_reset_button") - .addEventListener('click', () => UI.rfb.machineReset()); - document.getElementById("noVNC_power_button") - .addEventListener('click', UI.togglePowerPanel); - }, - - addConnectionControlHandlers() { - document.getElementById("noVNC_disconnect_button") - .addEventListener('click', UI.disconnect); - document.getElementById("noVNC_connect_button") - .addEventListener('click', UI.connect); - document.getElementById("noVNC_cancel_reconnect_button") - .addEventListener('click', UI.cancelReconnect); - - document.getElementById("noVNC_password_button") - .addEventListener('click', UI.setPassword); - }, - - addClipboardHandlers() { - document.getElementById("noVNC_clipboard_button") - .addEventListener('click', UI.toggleClipboardPanel); - document.getElementById("noVNC_clipboard_text") - .addEventListener('change', UI.clipboardSend); - document.getElementById("noVNC_clipboard_clear_button") - .addEventListener('click', UI.clipboardClear); - }, - - // Add a call to save settings when the element changes, - // unless the optional parameter changeFunc is used instead. - addSettingChangeHandler(name, changeFunc) { - const settingElem = document.getElementById("noVNC_setting_" + name); - if (changeFunc === undefined) { - changeFunc = () => UI.saveSetting(name); - } - settingElem.addEventListener('change', changeFunc); - }, - - addSettingsHandlers() { - document.getElementById("noVNC_settings_button") - .addEventListener('click', UI.toggleSettingsPanel); - - document.getElementById("noVNC_setting_enable_perf_stats").addEventListener('click', UI.showStats); - - UI.addSettingChangeHandler('encrypt'); - UI.addSettingChangeHandler('resize'); - UI.addSettingChangeHandler('resize', UI.applyResizeMode); - UI.addSettingChangeHandler('resize', UI.updateViewClip); - UI.addSettingChangeHandler('view_clip'); - UI.addSettingChangeHandler('view_clip', UI.updateViewClip); - UI.addSettingChangeHandler('shared'); - UI.addSettingChangeHandler('view_only'); - UI.addSettingChangeHandler('view_only', UI.updateViewOnly); - UI.addSettingChangeHandler('show_dot'); - UI.addSettingChangeHandler('show_dot', UI.updateShowDotCursor); - UI.addSettingChangeHandler('host'); - UI.addSettingChangeHandler('port'); - UI.addSettingChangeHandler('path'); - UI.addSettingChangeHandler('repeaterID'); - UI.addSettingChangeHandler('logging'); - UI.addSettingChangeHandler('logging', UI.updateLogging); - UI.addSettingChangeHandler('reconnect'); - UI.addSettingChangeHandler('reconnect_delay'); - UI.addSettingChangeHandler('enable_webp'); - UI.addSettingChangeHandler('clipboard_seamless'); - UI.addSettingChangeHandler('clipboard_up'); - UI.addSettingChangeHandler('clipboard_down'); - }, - - addFullscreenHandlers() { - document.getElementById("noVNC_fullscreen_button") - .addEventListener('click', UI.toggleFullscreen); - - window.addEventListener('fullscreenchange', UI.updateFullscreenButton); - window.addEventListener('mozfullscreenchange', UI.updateFullscreenButton); - window.addEventListener('webkitfullscreenchange', UI.updateFullscreenButton); - window.addEventListener('msfullscreenchange', UI.updateFullscreenButton); - }, - -/* ------^------- - * /EVENT HANDLERS - * ============== - * VISUAL - * ------v------*/ - - // Disable/enable controls depending on connection state - updateVisualState(state) { - - document.documentElement.classList.remove("noVNC_connecting"); - document.documentElement.classList.remove("noVNC_connected"); - document.documentElement.classList.remove("noVNC_disconnecting"); - document.documentElement.classList.remove("noVNC_reconnecting"); - - const transition_elem = document.getElementById("noVNC_transition_text"); - if (WebUtil.isInsideKasmVDI()) - { - parent.postMessage({ action: 'connection_state', value: state}, '*' ); - } - switch (state) { - case 'init': - break; - case 'connecting': - transition_elem.textContent = _("Connecting..."); - document.documentElement.classList.add("noVNC_connecting"); - break; - case 'connected': - document.documentElement.classList.add("noVNC_connected"); - break; - case 'disconnecting': - transition_elem.textContent = _("Disconnecting..."); - document.documentElement.classList.add("noVNC_disconnecting"); - break; - case 'disconnected': - break; - case 'reconnecting': - transition_elem.textContent = _("Reconnecting..."); - document.documentElement.classList.add("noVNC_reconnecting"); - break; - default: - Log.Error("Invalid visual state: " + state); - UI.showStatus(_("Internal error"), 'error'); - return; - } - - if (UI.connected) { - UI.updateViewClip(); - - UI.disableSetting('encrypt'); - UI.disableSetting('shared'); - UI.disableSetting('host'); - UI.disableSetting('port'); - UI.disableSetting('path'); - UI.disableSetting('repeaterID'); - UI.setMouseButton(1); - - // Hide the controlbar after 2 seconds - UI.closeControlbarTimeout = setTimeout(UI.closeControlbar, 2000); - } else { - UI.enableSetting('encrypt'); - UI.enableSetting('shared'); - UI.enableSetting('host'); - UI.enableSetting('port'); - UI.enableSetting('path'); - UI.enableSetting('repeaterID'); - UI.updatePowerButton(); - UI.keepControlbar(); - } - - // State change closes the password dialog - document.getElementById('noVNC_password_dlg') - .classList.remove('noVNC_open'); - }, - - showStats() { - UI.saveSetting('enable_perf_stats'); - - let enable_stats = UI.getSetting('enable_perf_stats'); - if (enable_stats === true && UI.statsInterval == undefined) { - document.getElementById("noVNC_connection_stats").style.visibility = "visible"; - UI.statsInterval = setInterval(function() { - if (UI.rfb !== undefined) { - UI.rfb.requestBottleneckStats(); - } - } , 5000); - } else { - document.getElementById("noVNC_connection_stats").style.visibility = "hidden"; - UI.statsInterval = null; - } - - }, - - showStatus(text, status_type, time) { - const statusElem = document.getElementById('noVNC_status'); - - clearTimeout(UI.statusTimeout); - - if (typeof status_type === 'undefined') { - status_type = 'normal'; - } - - // Don't overwrite more severe visible statuses and never - // errors. Only shows the first error. - let visible_status_type = 'none'; - if (statusElem.classList.contains("noVNC_open")) { - if (statusElem.classList.contains("noVNC_status_error")) { - visible_status_type = 'error'; - } else if (statusElem.classList.contains("noVNC_status_warn")) { - visible_status_type = 'warn'; - } else { - visible_status_type = 'normal'; - } - } - if (visible_status_type === 'error' || - (visible_status_type === 'warn' && status_type === 'normal')) { - return; - } - - switch (status_type) { - case 'error': - statusElem.classList.remove("noVNC_status_warn"); - statusElem.classList.remove("noVNC_status_normal"); - statusElem.classList.add("noVNC_status_error"); - break; - case 'warning': - case 'warn': - statusElem.classList.remove("noVNC_status_error"); - statusElem.classList.remove("noVNC_status_normal"); - statusElem.classList.add("noVNC_status_warn"); - break; - case 'normal': - case 'info': - default: - statusElem.classList.remove("noVNC_status_error"); - statusElem.classList.remove("noVNC_status_warn"); - statusElem.classList.add("noVNC_status_normal"); - break; - } - - statusElem.textContent = text; - statusElem.classList.add("noVNC_open"); - - // If no time was specified, show the status for 1.5 seconds - if (typeof time === 'undefined') { - time = 1500; - } - - // Error messages do not timeout - if (status_type !== 'error') { - UI.statusTimeout = window.setTimeout(UI.hideStatus, time); - } - }, - - hideStatus() { - clearTimeout(UI.statusTimeout); - document.getElementById('noVNC_status').classList.remove("noVNC_open"); - }, - - activateControlbar(event) { - clearTimeout(UI.idleControlbarTimeout); - // We manipulate the anchor instead of the actual control - // bar in order to avoid creating new a stacking group - document.getElementById('noVNC_control_bar_anchor') - .classList.remove("noVNC_idle"); - UI.idleControlbarTimeout = window.setTimeout(UI.idleControlbar, 2000); - }, - - idleControlbar() { - document.getElementById('noVNC_control_bar_anchor') - .classList.add("noVNC_idle"); - }, - - keepControlbar() { - clearTimeout(UI.closeControlbarTimeout); - }, - - openControlbar() { - document.getElementById('noVNC_control_bar') - .classList.add("noVNC_open"); - }, - - closeControlbar() { - UI.closeAllPanels(); - document.getElementById('noVNC_control_bar') - .classList.remove("noVNC_open"); - }, - - toggleControlbar() { - if (document.getElementById('noVNC_control_bar') - .classList.contains("noVNC_open")) { - UI.closeControlbar(); - } else { - UI.openControlbar(); - } - }, - - toggleControlbarSide() { - // Temporarily disable animation, if bar is displayed, to avoid weird - // movement. The transitionend-event will not fire when display=none. - const bar = document.getElementById('noVNC_control_bar'); - const barDisplayStyle = window.getComputedStyle(bar).display; - if (barDisplayStyle !== 'none') { - bar.style.transitionDuration = '0s'; - bar.addEventListener('transitionend', () => bar.style.transitionDuration = ''); - } - - const anchor = document.getElementById('noVNC_control_bar_anchor'); - if (anchor.classList.contains("noVNC_right")) { - WebUtil.writeSetting('controlbar_pos', 'left'); - anchor.classList.remove("noVNC_right"); - } else { - WebUtil.writeSetting('controlbar_pos', 'right'); - anchor.classList.add("noVNC_right"); - } - - // Consider this a movement of the handle - UI.controlbarDrag = true; - }, - - showControlbarHint(show) { - const hint = document.getElementById('noVNC_control_bar_hint'); - if (show) { - hint.classList.add("noVNC_active"); - } else { - hint.classList.remove("noVNC_active"); - } - }, - - dragControlbarHandle(e) { - if (!UI.controlbarGrabbed) return; - - const ptr = getPointerEvent(e); - - const anchor = document.getElementById('noVNC_control_bar_anchor'); - if (ptr.clientX < (window.innerWidth * 0.1)) { - if (anchor.classList.contains("noVNC_right")) { - UI.toggleControlbarSide(); - } - } else if (ptr.clientX > (window.innerWidth * 0.9)) { - if (!anchor.classList.contains("noVNC_right")) { - UI.toggleControlbarSide(); - } - } - - if (!UI.controlbarDrag) { - const dragDistance = Math.abs(ptr.clientY - UI.controlbarMouseDownClientY); - - if (dragDistance < dragThreshold) return; - - UI.controlbarDrag = true; - } - - const eventY = ptr.clientY - UI.controlbarMouseDownOffsetY; - - UI.moveControlbarHandle(eventY); - - e.preventDefault(); - e.stopPropagation(); - UI.keepControlbar(); - UI.activateControlbar(); - }, - - // Move the handle but don't allow any position outside the bounds - moveControlbarHandle(viewportRelativeY) { - const handle = document.getElementById("noVNC_control_bar_handle"); - const handleHeight = handle.getBoundingClientRect().height; - const controlbarBounds = document.getElementById("noVNC_control_bar") - .getBoundingClientRect(); - const margin = 10; - - // These heights need to be non-zero for the below logic to work - if (handleHeight === 0 || controlbarBounds.height === 0) { - return; - } - - let newY = viewportRelativeY; - - // Check if the coordinates are outside the control bar - if (newY < controlbarBounds.top + margin) { - // Force coordinates to be below the top of the control bar - newY = controlbarBounds.top + margin; - - } else if (newY > controlbarBounds.top + - controlbarBounds.height - handleHeight - margin) { - // Force coordinates to be above the bottom of the control bar - newY = controlbarBounds.top + - controlbarBounds.height - handleHeight - margin; - } - - // Corner case: control bar too small for stable position - if (controlbarBounds.height < (handleHeight + margin * 2)) { - newY = controlbarBounds.top + - (controlbarBounds.height - handleHeight) / 2; - } - - // The transform needs coordinates that are relative to the parent - const parentRelativeY = newY - controlbarBounds.top; - handle.style.transform = "translateY(" + parentRelativeY + "px)"; - }, - - updateControlbarHandle() { - // Since the control bar is fixed on the viewport and not the page, - // the move function expects coordinates relative the the viewport. - const handle = document.getElementById("noVNC_control_bar_handle"); - const handleBounds = handle.getBoundingClientRect(); - UI.moveControlbarHandle(handleBounds.top); - }, - - controlbarHandleMouseUp(e) { - if ((e.type == "mouseup") && (e.button != 0)) return; - - // mouseup and mousedown on the same place toggles the controlbar - if (UI.controlbarGrabbed && !UI.controlbarDrag) { - UI.toggleControlbar(); - e.preventDefault(); - e.stopPropagation(); - UI.keepControlbar(); - UI.activateControlbar(); - } - UI.controlbarGrabbed = false; - UI.showControlbarHint(false); - }, - - controlbarHandleMouseDown(e) { - if ((e.type == "mousedown") && (e.button != 0)) return; - - const ptr = getPointerEvent(e); - - const handle = document.getElementById("noVNC_control_bar_handle"); - const bounds = handle.getBoundingClientRect(); - - // Touch events have implicit capture - if (e.type === "mousedown") { - setCapture(handle); - } - - UI.controlbarGrabbed = true; - UI.controlbarDrag = false; - - UI.showControlbarHint(true); - - UI.controlbarMouseDownClientY = ptr.clientY; - UI.controlbarMouseDownOffsetY = ptr.clientY - bounds.top; - e.preventDefault(); - e.stopPropagation(); - UI.keepControlbar(); - UI.activateControlbar(); - }, - - toggleExpander(e) { - if (this.classList.contains("noVNC_open")) { - this.classList.remove("noVNC_open"); - } else { - this.classList.add("noVNC_open"); - } - }, - -/* ------^------- - * /VISUAL - * ============== - * SETTINGS - * ------v------*/ - - // Initial page load read/initialization of settings - initSetting(name, defVal) { - // Check Query string followed by cookie - let val = WebUtil.getConfigVar(name); - if (val === null) { - val = WebUtil.readSetting(name, defVal); - } - WebUtil.setSetting(name, val); - UI.updateSetting(name); - return val; - }, - - // Set the new value, update and disable form control setting - forceSetting(name, val) { - WebUtil.setSetting(name, val); - UI.updateSetting(name); - UI.disableSetting(name); - }, - - // Update cookie and form control setting. If value is not set, then - // updates from control to current cookie setting. - updateSetting(name) { - - // Update the settings control - let value = UI.getSetting(name); - - const ctrl = document.getElementById('noVNC_setting_' + name); - if (ctrl.type === 'checkbox') { - ctrl.checked = value; - - } else if (typeof ctrl.options !== 'undefined') { - for (let i = 0; i < ctrl.options.length; i += 1) { - if (ctrl.options[i].value === value) { - ctrl.selectedIndex = i; - break; - } - } - } else { - /*Weird IE9 error leads to 'null' appearring - in textboxes instead of ''.*/ - if (value === null) { - value = ""; - } - ctrl.value = value; - } - }, - - // Save control setting to cookie - saveSetting(name) { - const ctrl = document.getElementById('noVNC_setting_' + name); - let val; - if (ctrl.type === 'checkbox') { - val = ctrl.checked; - } else if (typeof ctrl.options !== 'undefined') { - val = ctrl.options[ctrl.selectedIndex].value; - } else { - val = ctrl.value; - } - WebUtil.writeSetting(name, val); - //Log.Debug("Setting saved '" + name + "=" + val + "'"); - return val; - }, - - // Read form control compatible setting from cookie - getSetting(name) { - const ctrl = document.getElementById('noVNC_setting_' + name); - let val = WebUtil.readSetting(name); - if (typeof val !== 'undefined' && val !== null && ctrl.type === 'checkbox') { - if (val.toString().toLowerCase() in {'0': 1, 'no': 1, 'false': 1}) { - val = false; - } else { - val = true; - } - } - return val; - }, - - // These helpers compensate for the lack of parent-selectors and - // previous-sibling-selectors in CSS which are needed when we want to - // disable the labels that belong to disabled input elements. - disableSetting(name) { - const ctrl = document.getElementById('noVNC_setting_' + name); - ctrl.disabled = true; - ctrl.label.classList.add('noVNC_disabled'); - }, - - enableSetting(name) { - const ctrl = document.getElementById('noVNC_setting_' + name); - ctrl.disabled = false; - ctrl.label.classList.remove('noVNC_disabled'); - }, - -/* ------^------- - * /SETTINGS - * ============== - * PANELS - * ------v------*/ - - closeAllPanels() { - UI.closeSettingsPanel(); - UI.closePowerPanel(); - UI.closeClipboardPanel(); - UI.closeExtraKeys(); - }, - -/* ------^------- - * /PANELS - * ============== - * SETTINGS (panel) - * ------v------*/ - - openSettingsPanel() { - UI.closeAllPanels(); - UI.openControlbar(); - - // Refresh UI elements from saved cookies - UI.updateSetting('encrypt'); - UI.updateSetting('view_clip'); - UI.updateSetting('resize'); - UI.updateSetting('shared'); - UI.updateSetting('view_only'); - UI.updateSetting('path'); - UI.updateSetting('repeaterID'); - UI.updateSetting('logging'); - UI.updateSetting('reconnect'); - UI.updateSetting('reconnect_delay'); - - document.getElementById('noVNC_settings') - .classList.add("noVNC_open"); - document.getElementById('noVNC_settings_button') - .classList.add("noVNC_selected"); - }, - - closeSettingsPanel() { - document.getElementById('noVNC_settings') - .classList.remove("noVNC_open"); - document.getElementById('noVNC_settings_button') - .classList.remove("noVNC_selected"); - }, - - toggleSettingsPanel() { - if (document.getElementById('noVNC_settings') - .classList.contains("noVNC_open")) { - UI.closeSettingsPanel(); - } else { - UI.openSettingsPanel(); - } - }, - -/* ------^------- - * /SETTINGS - * ============== - * POWER - * ------v------*/ - - openPowerPanel() { - UI.closeAllPanels(); - UI.openControlbar(); - - document.getElementById('noVNC_power') - .classList.add("noVNC_open"); - document.getElementById('noVNC_power_button') - .classList.add("noVNC_selected"); - }, - - closePowerPanel() { - document.getElementById('noVNC_power') - .classList.remove("noVNC_open"); - document.getElementById('noVNC_power_button') - .classList.remove("noVNC_selected"); - }, - - togglePowerPanel() { - if (document.getElementById('noVNC_power') - .classList.contains("noVNC_open")) { - UI.closePowerPanel(); - } else { - UI.openPowerPanel(); - } - }, - - // Disable/enable power button - updatePowerButton() { - if (UI.connected && - UI.rfb.capabilities.power && - !UI.rfb.viewOnly) { - document.getElementById('noVNC_power_button') - .classList.remove("noVNC_hidden"); - } else { - document.getElementById('noVNC_power_button') - .classList.add("noVNC_hidden"); - // Close power panel if open - UI.closePowerPanel(); - } - }, - -/* ------^------- - * /POWER - * ============== - * CLIPBOARD - * ------v------*/ - - openClipboardPanel() { - UI.closeAllPanels(); - UI.openControlbar(); - - document.getElementById('noVNC_clipboard') - .classList.add("noVNC_open"); - document.getElementById('noVNC_clipboard_button') - .classList.add("noVNC_selected"); - }, - - closeClipboardPanel() { - document.getElementById('noVNC_clipboard') - .classList.remove("noVNC_open"); - document.getElementById('noVNC_clipboard_button') - .classList.remove("noVNC_selected"); - }, - - toggleClipboardPanel() { - if (document.getElementById('noVNC_clipboard') - .classList.contains("noVNC_open")) { - UI.closeClipboardPanel(); - } else { - UI.openClipboardPanel(); - } - }, - - readClipboard: function readClipboard(callback) { - if (navigator.clipboard && navigator.clipboard.readText) { - navigator.clipboard.readText().then(function (text) { - return callback(text); - }).catch(function () { - return Log.Debug("Failed to read system clipboard"); - }); - } - }, - - // Copy text from NoVNC desktop to local computer - clipboardReceive(e) { - if (UI.rfb.clipboardDown && UI.rfb.clipboardSeamless ) { - var curvalue = document.getElementById('noVNC_clipboard_text').value; - if (curvalue != e.detail.text) { - Log.Debug(">> UI.clipboardReceive: " + e.detail.text.substr(0, 40) + "..."); - document.getElementById('noVNC_clipboard_text').value = e.detail.text; - Log.Debug("<< UI.clipboardReceive"); - if (navigator.clipboard && navigator.clipboard.writeText){ - navigator.clipboard.writeText(e.detail.text) - .then(function () { - //UI.popupMessage("Selection Copied"); - }, function () { - console.error("Failed to write system clipboard (trying to copy from NoVNC clipboard)") - }); - } - } - } - }, - - //recieved bottleneck stats - bottleneckStatsRecieve(e) { - var obj = JSON.parse(e.detail.text); - document.getElementById("noVNC_connection_stats").innerHTML = "CPU: " + obj[0] + "/" + obj[1] + " | Network: " + obj[2] + "/" + obj[3]; - console.log(e.detail.text); - }, - - popupMessage: function(msg, secs) { - if (!secs){ - secs = 500; - } - // Quick popup to give feedback that selection was copied - setTimeout(UI.showOverlay.bind(this, msg, secs), 200); - }, - - // Enter and focus events come when we return to NoVNC. - // In both cases, check the local clipboard to see if it changed. - focusVNC: function() { - UI.copyFromLocalClipboard(); - }, - enterVNC: function() { - UI.copyFromLocalClipboard(); - }, - copyFromLocalClipboard: function copyFromLocalClipboard() { - if (UI.rfb && UI.rfb.clipboardUp && UI.rfb.clipboardSeamless) { - UI.readClipboard(function (text) { - var maximumBufferSize = 10000; - var clipVal = document.getElementById('noVNC_clipboard_text').value; - - if (clipVal != text) { - document.getElementById('noVNC_clipboard_text').value = text; // The websocket has a maximum buffer array size - - if (text.length > maximumBufferSize) { - UI.popupMessage("Clipboard contents too large. Data truncated", 2000); - UI.rfb.clipboardPasteFrom(text.slice(0, maximumBufferSize)); - } else { - //UI.popupMessage("Copied from Local Clipboard"); - UI.rfb.clipboardPasteFrom(text); - } - } // Reset flag to prevent checking too often - - - UI.needToCheckClipboardChange = false; - }); - } - }, - - // These 3 events indicate the focus has gone outside the NoVNC. - // When outside the NoVNC, the system clipboard could change. - leaveVNC: function() { - UI.needToCheckClipboardChange = true; - }, - blurVNC: function() { - UI.needToCheckClipboardChange = true; - }, - focusoutVNC: function() { - UI.needToCheckClipboardChange = true; - }, - - // On these 2 events, check if we need to look at clipboard. - mouseMoveVNC: function() { - if ( UI.needToCheckClipboardChange ) { - UI.copyFromLocalClipboard(); - } - }, - mouseDownVNC: function() { - if ( UI.needToCheckClipboardChange ) { - UI.copyFromLocalClipboard(); - } - }, - - clipboardClear() { - document.getElementById('noVNC_clipboard_text').value = ""; - UI.rfb.clipboardPasteFrom(""); - }, - - clipboardSend() { - const text = document.getElementById('noVNC_clipboard_text').value; - Log.Debug(">> UI.clipboardSend: " + text.substr(0, 40) + "..."); - UI.rfb.clipboardPasteFrom(text); - Log.Debug("<< UI.clipboardSend"); - }, - - /** - * Show the terminal overlay for a given amount of time. - * - * The terminal overlay appears in inverse video in a large font, centered - * over the terminal. You should probably keep the overlay message brief, - * since it's in a large font and you probably aren't going to check the size - * of the terminal first. - * - * @param {string} msg The text (not HTML) message to display in the overlay. - * @param {number} opt_timeout The amount of time to wait before fading out - * the overlay. Defaults to 1.5 seconds. Pass null to have the overlay - * stay up forever (or until the next overlay). - */ - showOverlay: function(msg, opt_timeout) { - if (!UI.overlayNode) { - UI.overlayNode = document.createElement('div'); - UI.overlayNode.style.cssText = ( - 'border-radius: 15px;' + - 'font-size: xx-large;' + - 'opacity: 0.90;' + - 'padding: 0.2em 0.5em 0.2em 0.5em;' + - 'position: absolute;' + - '-webkit-user-select: none;' + - '-webkit-transition: opacity 180ms ease-in;' + - '-moz-user-select: none;' + - '-moz-transition: opacity 180ms ease-in;'); - UI.overlayNode.style.color = 'rgb(16,16,16)'; - UI.overlayNode.style.backgroundColor = 'rgb(240,240,240)'; - UI.overlayNode.style.fontFamily = '"DejaVu Sans Mono", "Noto Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace"'; - UI.overlayNode.style.opacity = '0.90'; - - //UI.overlayNode.addEventListener('mousedown', function(e) { - // e.preventDefault(); - // e.stopPropagation(); - // }, true); - } - - UI.overlayNode.textContent = msg; - - if (!UI.overlayNode.parentNode_) { - UI.overlayNode.parentNode_ = document.getElementById('noVNC_container'); - } - UI.overlayNode.parentNode_.appendChild(UI.overlayNode); - - var divWidth = UI.overlayNode.parentNode_.offsetWidth; - var divHeight = UI.overlayNode.parentNode_.offsetHeight; - var overlayWidth = UI.overlayNode.offsetWidth; - var overlayHeight = UI.overlayNode.offsetHeight; - - UI.overlayNode.style.top = - (divHeight - overlayHeight) / 2 + 'px'; - UI.overlayNode.style.left = - (divWidth - overlayWidth) / 2 + 'px'; - - if (UI.overlayTimeout) - clearTimeout(UI.overlayTimeout); - - if (opt_timeout === null) - opt_timeout = 500; - - UI.overlayTimeout = setTimeout(function () { - UI.overlayNode.style.opacity = '0'; - UI.overlayTimeout = setTimeout(function () { - return UI.hideOverlay(); - }, 200); - }, opt_timeout || 1500); - }, - - /** - * Hide the terminal overlay immediately. - * - * Useful when we show an overlay for an event with an unknown end time. - */ - hideOverlay: function() { - if (UI.overlayTimeout) - clearTimeout(UI.overlayTimeout); - UI.overlayTimeout = null; - - if (UI.overlayNode.parentNode_) - UI.overlayNode.parentNode_.removeChild(UI.overlayNode); - UI.overlayNode.style.opacity = '0.90'; - }, - -/* ------^------- - * /CLIPBOARD - * ============== - * CONNECTION - * ------v------*/ - - openConnectPanel() { - document.getElementById('noVNC_connect_dlg') - .classList.add("noVNC_open"); - }, - - closeConnectPanel() { - document.getElementById('noVNC_connect_dlg') - .classList.remove("noVNC_open"); - }, - - connect(event, password) { - - // Ignore when rfb already exists - if (typeof UI.rfb !== 'undefined') { - return; - } - - const host = UI.getSetting('host'); - const port = UI.getSetting('port'); - const path = UI.getSetting('path'); - - if (typeof password === 'undefined') { - password = WebUtil.getConfigVar('password'); - UI.reconnect_password = password; - } - - if (password === null) { - password = undefined; - } - - UI.hideStatus(); - - if (!host) { - Log.Error("Can't connect when host is: " + host); - UI.showStatus(_("Must set host"), 'error'); - return; - } - - UI.closeAllPanels(); - UI.closeConnectPanel(); - - UI.updateVisualState('connecting'); - - let url; - - url = UI.getSetting('encrypt') ? 'wss' : 'ws'; - - url += '://' + host; - if (port) { - url += ':' + port; - } - url += '/' + path; - - UI.rfb = new RFB(document.getElementById('noVNC_container'), url, - { shared: UI.getSetting('shared'), - showDotCursor: UI.getSetting('show_dot'), - repeaterID: UI.getSetting('repeaterID'), - credentials: { password: password } }); - UI.rfb.addEventListener("connect", UI.connectFinished); - UI.rfb.addEventListener("disconnect", UI.disconnectFinished); - UI.rfb.addEventListener("credentialsrequired", UI.credentials); - UI.rfb.addEventListener("securityfailure", UI.securityFailed); - UI.rfb.addEventListener("capabilities", UI.updatePowerButton); - UI.rfb.addEventListener("clipboard", UI.clipboardReceive); - UI.rfb.addEventListener("bottleneck_stats", UI.bottleneckStatsRecieve); - - document.addEventListener('mouseenter', UI.enterVNC); - document.addEventListener('mouseleave', UI.leaveVNC); - document.addEventListener('blur', UI.blurVNC); - document.addEventListener('focus', UI.focusVNC); - document.addEventListener('focusout', UI.focusoutVNC); - document.addEventListener('mousemove', UI.mouseMoveVNC); - document.addEventListener('mousedown', UI.mouseDownVNC); - - UI.rfb.addEventListener("bell", UI.bell); - UI.rfb.addEventListener("desktopname", UI.updateDesktopName); - UI.rfb.clipViewport = UI.getSetting('view_clip'); - UI.rfb.scaleViewport = UI.getSetting('resize') === 'scale'; - UI.rfb.resizeSession = UI.getSetting('resize') === 'remote'; - UI.rfb.idleDisconnect = UI.getSetting('idle_disconnect'); - UI.rfb.videoQuality = UI.getSetting('video_quality'); - UI.rfb.clipboardUp = UI.getSetting('clipboard_up'); - UI.rfb.clipboardDown = UI.getSetting('clipboard_down'); - UI.rfb.clipboardSeamless = UI.getSetting('clipboard_seamless'); - // KASM-960 workaround, disable seamless on Safari - if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) - { - UI.rfb.clipboardSeamless = false; - } - UI.rfb.preferLocalCursor = UI.getSetting('prefer_local_cursor'); - UI.rfb.enableWebP = UI.getSetting('enable_webp'); - UI.updateViewOnly(); // requires UI.rfb - - /**** - * Kasm VDI specific - *****/ - if (WebUtil.isInsideKasmVDI()) - { - if (window.addEventListener) { // Mozilla, Netscape, Firefox - //window.addEventListener('load', WindowLoad, false); - window.addEventListener('message', UI.receiveMessage, false); - } else if (window.attachEvent) { //IE - window.attachEvent('onload', WindowLoad); - window.attachEvent('message', UI.receiveMessage); - } - if (UI.rfb.clipboardDown){ - UI.rfb.addEventListener("clipboard", UI.clipboardRx); - } - UI.rfb.addEventListener("disconnect", UI.disconnectedRx); - document.getElementById('noVNC_control_bar_anchor').setAttribute('style', 'display: none'); - document.getElementById('noVNC_connect_dlg').innerHTML = ''; - - //keep alive for websocket connection to stay open, since we may not control reverse proxies - //send a keep alive within a window that we control - setInterval(function() { - if (currentEventCount!=UI.rfb.sentEventsCounter) { - idleCounter=0; - currentEventCount=UI.rfb.sentEventsCounter; - } else { - idleCounter+=1; - var idleDisconnect = parseFloat(UI.rfb.idleDisconnect); - if ((idleCounter / 2) >= idleDisconnect) { - //idle for longer than the limit, disconnect - currentEventCount = -1; - idleCounter = 0; - parent.postMessage({ action: 'idle_session_timeout', value: 'Idle session timeout exceeded'}, '*' ); - //UI.rfb.disconnect(); - } else { - //send a keep alive - UI.rfb.sendKey(1, null, false); - currentEventCount=UI.rfb.sentEventsCounter; - } - } - }, 30000); - } - - - // Send an event to the parent document (kasm app) to toggle the control panel when ctl is double clicked - if (UI.getSetting('toggle_control_panel', false)) { - - document.addEventListener('keyup', function (event) { - // CTRL and the various implementations of the mac command key - if ([17, 224, 91, 93].indexOf(event.keyCode) > -1) { - var thisKeypressTime = new Date(); - - if (thisKeypressTime - lastKeypressTime <= delta) { - UI.toggleNav(); - thisKeypressTime = 0; - } - - lastKeypressTime = thisKeypressTime; - } - }, true); - } - - }, - - disconnect() { - UI.closeAllPanels(); - UI.rfb.disconnect(); - - UI.connected = false; - - // Disable automatic reconnecting - UI.inhibit_reconnect = true; - - UI.updateVisualState('disconnecting'); - - // Don't display the connection settings until we're actually disconnected - }, - - reconnect() { - UI.reconnect_callback = null; - - // if reconnect has been disabled in the meantime, do nothing. - if (UI.inhibit_reconnect) { - return; - } - - UI.connect(null, UI.reconnect_password); - }, - - cancelReconnect() { - if (UI.reconnect_callback !== null) { - clearTimeout(UI.reconnect_callback); - UI.reconnect_callback = null; - } - - UI.updateVisualState('disconnected'); - - UI.openControlbar(); - UI.openConnectPanel(); - }, - - connectFinished(e) { - UI.connected = true; - UI.inhibit_reconnect = false; - - let msg; - if (UI.getSetting('encrypt')) { - msg = _("Connected (encrypted) to ") + UI.desktopName; - } else { - msg = _("Connected (unencrypted) to ") + UI.desktopName; - } - UI.showStatus(msg); - UI.showStats(); - UI.updateVisualState('connected'); - - // Do this last because it can only be used on rendered elements - UI.rfb.focus(); - }, - - disconnectFinished(e) { - const wasConnected = UI.connected; - - // This variable is ideally set when disconnection starts, but - // when the disconnection isn't clean or if it is initiated by - // the server, we need to do it here as well since - // UI.disconnect() won't be used in those cases. - UI.connected = false; - - UI.rfb = undefined; - - if (!e.detail.clean) { - UI.updateVisualState('disconnected'); - if (wasConnected) { - UI.showStatus(_("Something went wrong, connection is closed"), - 'error'); - } else { - UI.showStatus(_("Failed to connect to server"), 'error'); - } - } else if (UI.getSetting('reconnect', false) === true && !UI.inhibit_reconnect) { - UI.updateVisualState('reconnecting'); - - const delay = parseInt(UI.getSetting('reconnect_delay')); - UI.reconnect_callback = setTimeout(UI.reconnect, delay); - return; - } else { - UI.updateVisualState('disconnected'); - UI.showStatus(_("Disconnected"), 'normal'); - } - - UI.openControlbar(); - UI.openConnectPanel(); - }, - - securityFailed(e) { - let msg = ""; - // On security failures we might get a string with a reason - // directly from the server. Note that we can't control if - // this string is translated or not. - if ('reason' in e.detail) { - msg = _("New connection has been rejected with reason: ") + - e.detail.reason; - } else { - msg = _("New connection has been rejected"); - } - UI.showStatus(msg, 'error'); - }, - - /* - Menu.js Additions - */ - receiveMessage(event) { - //TODO: UNCOMMENT FOR PRODUCTION - //if (event.origin !== "https://kasmweb.com") - // return; - - if (event.data && event.data.action) { - switch (event.data.action) { - case 'clipboardsnd': - if (UI.rfb.clipboardUp) { - UI.rfb.clipboardPasteFrom(event.data.value); - } - break; - case 'setvideoquality': - UI.rfb.videoQuality = event.data.value; - break; - } - } - }, - - disconnectedRx(event) { - parent.postMessage({ action: 'disconnectrx', value: event.detail.reason}, '*' ); - }, - - toggleNav(){ - parent.postMessage({ action: 'togglenav', value: null}, '*' ); - }, - - clipboardRx(event) { - parent.postMessage({ action: 'clipboardrx', value: event.detail.text}, '*' ); //TODO fix star - }, - -/* ------^------- - * /CONNECTION - * ============== - * PASSWORD - * ------v------*/ - - credentials(e) { - // FIXME: handle more types - document.getElementById('noVNC_password_dlg') - .classList.add('noVNC_open'); - - setTimeout(() => document - .getElementById('noVNC_password_input').focus(), 100); - - Log.Warn("Server asked for a password"); - UI.showStatus(_("Password is required"), "warning"); - }, - - setPassword(e) { - // Prevent actually submitting the form - e.preventDefault(); - - const inputElem = document.getElementById('noVNC_password_input'); - const password = inputElem.value; - // Clear the input after reading the password - inputElem.value = ""; - UI.rfb.sendCredentials({ password: password }); - UI.reconnect_password = password; - document.getElementById('noVNC_password_dlg') - .classList.remove('noVNC_open'); - }, - -/* ------^------- - * /PASSWORD - * ============== - * FULLSCREEN - * ------v------*/ - - toggleFullscreen() { - if (document.fullscreenElement || // alternative standard method - document.mozFullScreenElement || // currently working methods - document.webkitFullscreenElement || - document.msFullscreenElement) { - if (document.exitFullscreen) { - document.exitFullscreen(); - } else if (document.mozCancelFullScreen) { - document.mozCancelFullScreen(); - } else if (document.webkitExitFullscreen) { - document.webkitExitFullscreen(); - } else if (document.msExitFullscreen) { - document.msExitFullscreen(); - } - } else { - if (document.documentElement.requestFullscreen) { - document.documentElement.requestFullscreen(); - } else if (document.documentElement.mozRequestFullScreen) { - document.documentElement.mozRequestFullScreen(); - } else if (document.documentElement.webkitRequestFullscreen) { - document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); - } else if (document.body.msRequestFullscreen) { - document.body.msRequestFullscreen(); - } - } - UI.updateFullscreenButton(); - }, - - updateFullscreenButton() { - if (document.fullscreenElement || // alternative standard method - document.mozFullScreenElement || // currently working methods - document.webkitFullscreenElement || - document.msFullscreenElement ) { - document.getElementById('noVNC_fullscreen_button') - .classList.add("noVNC_selected"); - } else { - document.getElementById('noVNC_fullscreen_button') - .classList.remove("noVNC_selected"); - } - }, - -/* ------^------- - * /FULLSCREEN - * ============== - * RESIZE - * ------v------*/ - - // Apply remote resizing or local scaling - applyResizeMode() { - if (!UI.rfb) return; - - UI.rfb.scaleViewport = UI.getSetting('resize') === 'scale'; - UI.rfb.resizeSession = UI.getSetting('resize') === 'remote'; - UI.rfb.idleDisconnect = UI.getSetting('idle_disconnect'); - UI.rfb.videoQuality = UI.getSetting('video_quality'); - UI.rfb.enableWebP = UI.getSetting('enable_webp'); - }, - -/* ------^------- - * /RESIZE - * ============== - * VIEW CLIPPING - * ------v------*/ - - // Update viewport clipping property for the connection. The normal - // case is to get the value from the setting. There are special cases - // for when the viewport is scaled or when a touch device is used. - updateViewClip() { - if (!UI.rfb) return; - - const scaling = UI.getSetting('resize') === 'scale'; - - if (scaling) { - // Can't be clipping if viewport is scaled to fit - UI.forceSetting('view_clip', false); - UI.rfb.clipViewport = false; - } else if (isIOS() || isAndroid()) { - // iOS and Android usually have shit scrollbars - UI.forceSetting('view_clip', true); - UI.rfb.clipViewport = true; - } else { - UI.enableSetting('view_clip'); - UI.rfb.clipViewport = UI.getSetting('view_clip'); - } - - // Changing the viewport may change the state of - // the dragging button - UI.updateViewDrag(); - }, - -/* ------^------- - * /VIEW CLIPPING - * ============== - * VIEWDRAG - * ------v------*/ - - toggleViewDrag() { - if (!UI.rfb) return; - - UI.rfb.dragViewport = !UI.rfb.dragViewport; - UI.updateViewDrag(); - }, - - updateViewDrag() { - if (!UI.connected) return; - - const viewDragButton = document.getElementById('noVNC_view_drag_button'); - - if (!UI.rfb.clipViewport && UI.rfb.dragViewport) { - // We are no longer clipping the viewport. Make sure - // viewport drag isn't active when it can't be used. - UI.rfb.dragViewport = false; - } - - if (UI.rfb.dragViewport) { - viewDragButton.classList.add("noVNC_selected"); - } else { - viewDragButton.classList.remove("noVNC_selected"); - } - - // Different behaviour for touch vs non-touch - // The button is disabled instead of hidden on touch devices - if (isTouchDevice) { - viewDragButton.classList.remove("noVNC_hidden"); - - if (UI.rfb.clipViewport) { - viewDragButton.disabled = false; - } else { - viewDragButton.disabled = true; - } - } else { - viewDragButton.disabled = false; - - if (UI.rfb.clipViewport) { - viewDragButton.classList.remove("noVNC_hidden"); - } else { - viewDragButton.classList.add("noVNC_hidden"); - } - } - }, - -/* ------^------- - * /VIEWDRAG - * ============== - * KEYBOARD - * ------v------*/ - - showVirtualKeyboard() { - if (!isTouchDevice) return; - - const input = document.getElementById('noVNC_keyboardinput'); - - if (document.activeElement == input) return; - - input.focus(); - - try { - const l = input.value.length; - // Move the caret to the end - input.setSelectionRange(l, l); - } catch (err) { - // setSelectionRange is undefined in Google Chrome - } - }, - - hideVirtualKeyboard() { - if (!isTouchDevice) return; - - const input = document.getElementById('noVNC_keyboardinput'); - - if (document.activeElement != input) return; - - input.blur(); - }, - - toggleVirtualKeyboard() { - if (document.getElementById('noVNC_keyboard_button') - .classList.contains("noVNC_selected")) { - UI.hideVirtualKeyboard(); - } else { - UI.showVirtualKeyboard(); - } - }, - - onfocusVirtualKeyboard(event) { - document.getElementById('noVNC_keyboard_button') - .classList.add("noVNC_selected"); - if (UI.rfb) { - UI.rfb.focusOnClick = false; - } - }, - - onblurVirtualKeyboard(event) { - document.getElementById('noVNC_keyboard_button') - .classList.remove("noVNC_selected"); - if (UI.rfb) { - UI.rfb.focusOnClick = true; - } - }, - - keepVirtualKeyboard(event) { - const input = document.getElementById('noVNC_keyboardinput'); - if ( UI.needToCheckClipboardChange ) { - UI.copyFromLocalClipboard(); - } - - // Only prevent focus change if the virtual keyboard is active - if (document.activeElement != input) { - return; - } - - // Only allow focus to move to other elements that need - // focus to function properly - if (event.target.form !== undefined) { - switch (event.target.type) { - case 'text': - case 'email': - case 'search': - case 'password': - case 'tel': - case 'url': - case 'textarea': - case 'select-one': - case 'select-multiple': - return; - } - } - - event.preventDefault(); - }, - - keyboardinputReset() { - const kbi = document.getElementById('noVNC_keyboardinput'); - kbi.value = new Array(UI.defaultKeyboardinputLen).join("_"); - UI.lastKeyboardinput = kbi.value; - }, - - keyEvent(keysym, code, down) { - if (!UI.rfb) return; - - UI.rfb.sendKey(keysym, code, down); - }, - - // When normal keyboard events are left uncought, use the input events from - // the keyboardinput element instead and generate the corresponding key events. - // This code is required since some browsers on Android are inconsistent in - // sending keyCodes in the normal keyboard events when using on screen keyboards. - keyInput(event) { - - if (!UI.rfb) return; - - const newValue = event.target.value; - - if (!UI.lastKeyboardinput) { - UI.keyboardinputReset(); - } - const oldValue = UI.lastKeyboardinput; - - let newLen; - try { - // Try to check caret position since whitespace at the end - // will not be considered by value.length in some browsers - newLen = Math.max(event.target.selectionStart, newValue.length); - } catch (err) { - // selectionStart is undefined in Google Chrome - newLen = newValue.length; - } - const oldLen = oldValue.length; - - let inputs = newLen - oldLen; - let backspaces = inputs < 0 ? -inputs : 0; - - // Compare the old string with the new to account for - // text-corrections or other input that modify existing text - for (let i = 0; i < Math.min(oldLen, newLen); i++) { - if (newValue.charAt(i) != oldValue.charAt(i)) { - inputs = newLen - i; - backspaces = oldLen - i; - break; - } - } - - // Send the key events - for (let i = 0; i < backspaces; i++) { - UI.rfb.sendKey(KeyTable.XK_BackSpace, "Backspace"); - } - for (let i = newLen - inputs; i < newLen; i++) { - UI.rfb.sendKey(keysyms.lookup(newValue.charCodeAt(i))); - } - - // Control the text content length in the keyboardinput element - if (newLen > 2 * UI.defaultKeyboardinputLen) { - UI.keyboardinputReset(); - } else if (newLen < 1) { - // There always have to be some text in the keyboardinput - // element with which backspace can interact. - UI.keyboardinputReset(); - // This sometimes causes the keyboard to disappear for a second - // but it is required for the android keyboard to recognize that - // text has been added to the field - event.target.blur(); - // This has to be ran outside of the input handler in order to work - setTimeout(event.target.focus.bind(event.target), 0); - } else { - UI.lastKeyboardinput = newValue; - } - }, - -/* ------^------- - * /KEYBOARD - * ============== - * EXTRA KEYS - * ------v------*/ - - openExtraKeys() { - UI.closeAllPanels(); - UI.openControlbar(); - - document.getElementById('noVNC_modifiers') - .classList.add("noVNC_open"); - document.getElementById('noVNC_toggle_extra_keys_button') - .classList.add("noVNC_selected"); - }, - - closeExtraKeys() { - document.getElementById('noVNC_modifiers') - .classList.remove("noVNC_open"); - document.getElementById('noVNC_toggle_extra_keys_button') - .classList.remove("noVNC_selected"); - }, - - toggleExtraKeys() { - if (document.getElementById('noVNC_modifiers') - .classList.contains("noVNC_open")) { - UI.closeExtraKeys(); - } else { - UI.openExtraKeys(); - } - }, - - sendEsc() { - UI.rfb.sendKey(KeyTable.XK_Escape, "Escape"); - }, - - sendTab() { - UI.rfb.sendKey(KeyTable.XK_Tab); - }, - - toggleCtrl() { - const btn = document.getElementById('noVNC_toggle_ctrl_button'); - if (btn.classList.contains("noVNC_selected")) { - UI.rfb.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); - btn.classList.remove("noVNC_selected"); - } else { - UI.rfb.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); - btn.classList.add("noVNC_selected"); - } - }, - - toggleWindows() { - const btn = document.getElementById('noVNC_toggle_windows_button'); - if (btn.classList.contains("noVNC_selected")) { - UI.rfb.sendKey(KeyTable.XK_Super_L, "MetaLeft", false); - btn.classList.remove("noVNC_selected"); - } else { - UI.rfb.sendKey(KeyTable.XK_Super_L, "MetaLeft", true); - btn.classList.add("noVNC_selected"); - } - }, - - toggleAlt() { - const btn = document.getElementById('noVNC_toggle_alt_button'); - if (btn.classList.contains("noVNC_selected")) { - UI.rfb.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); - btn.classList.remove("noVNC_selected"); - } else { - UI.rfb.sendKey(KeyTable.XK_Alt_L, "AltLeft", true); - btn.classList.add("noVNC_selected"); - } - }, - - sendCtrlAltDel() { - UI.rfb.sendCtrlAltDel(); - }, - -/* ------^------- - * /EXTRA KEYS - * ============== - * MISC - * ------v------*/ - - setMouseButton(num) { - const view_only = UI.rfb.viewOnly; - if (UI.rfb && !view_only) { - UI.rfb.touchButton = num; - } - - const blist = [0, 1, 2, 4]; - for (let b = 0; b < blist.length; b++) { - const button = document.getElementById('noVNC_mouse_button' + - blist[b]); - if (blist[b] === num && !view_only) { - button.classList.remove("noVNC_hidden"); - } else { - button.classList.add("noVNC_hidden"); - } - } - }, - - updateViewOnly() { - if (!UI.rfb) return; - UI.rfb.viewOnly = UI.getSetting('view_only'); - - // Hide input related buttons in view only mode - if (UI.rfb.viewOnly) { - document.getElementById('noVNC_keyboard_button') - .classList.add('noVNC_hidden'); - document.getElementById('noVNC_toggle_extra_keys_button') - .classList.add('noVNC_hidden'); - document.getElementById('noVNC_mouse_button' + UI.rfb.touchButton) - .classList.add('noVNC_hidden'); - } else { - document.getElementById('noVNC_keyboard_button') - .classList.remove('noVNC_hidden'); - document.getElementById('noVNC_toggle_extra_keys_button') - .classList.remove('noVNC_hidden'); - document.getElementById('noVNC_mouse_button' + UI.rfb.touchButton) - .classList.remove('noVNC_hidden'); - } - }, - - updateShowDotCursor() { - if (!UI.rfb) return; - UI.rfb.showDotCursor = UI.getSetting('show_dot'); - }, - - updateLogging() { - WebUtil.init_logging(UI.getSetting('logging')); - }, - - updateDesktopName(e) { - UI.desktopName = e.detail.name; - // Display the desktop name in the document title - document.title = e.detail.name + " - noVNC"; - }, - - bell(e) { - if (WebUtil.getConfigVar('bell', 'on') === 'on') { - const promise = document.getElementById('noVNC_bell').play(); - // The standards disagree on the return value here - if (promise) { - promise.catch((e) => { - if (e.name === "NotAllowedError") { - // Ignore when the browser doesn't let us play audio. - // It is common that the browsers require audio to be - // initiated from a user action. - } else { - Log.Error("Unable to play bell: " + e); - } - }); - } - } - }, - - //Helper to add options to dropdown. - addOption(selectbox, text, value) { - const optn = document.createElement("OPTION"); - optn.text = text; - optn.value = value; - selectbox.options.add(optn); - }, - -/* ------^------- - * /MISC - * ============== - */ -}; - -// Set up translations -const LINGUAS = ["cs", "de", "el", "es", "ko", "nl", "pl", "sv", "tr", "zh_CN", "zh_TW"]; -l10n.setup(LINGUAS); -if (l10n.language !== "en" && l10n.dictionary === undefined) { - WebUtil.fetchJSON('app/locale/' + l10n.language + '.json', (translations) => { - l10n.dictionary = translations; - - // wait for translations to load before loading the UI - UI.prime(); - }, (err) => { - Log.Error("Failed to load translations: " + err); - UI.prime(); - }); -} else { - UI.prime(); -} - -export default UI; diff --git a/kasmweb/app/webutil.js b/kasmweb/app/webutil.js deleted file mode 100644 index 72a1355..0000000 --- a/kasmweb/app/webutil.js +++ /dev/null @@ -1,255 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -import { init_logging as main_init_logging } from '../core/util/logging.js'; - -// init log level reading the logging HTTP param -export function init_logging(level) { - "use strict"; - if (typeof level !== "undefined") { - main_init_logging(level); - } else { - const param = document.location.href.match(/logging=([A-Za-z0-9._-]*)/); - main_init_logging(param || undefined); - } -} - -// Read a query string variable -export function getQueryVar(name, defVal) { - "use strict"; - const re = new RegExp('.*[?&]' + name + '=([^&#]*)'), - match = document.location.href.match(re); - if (typeof defVal === 'undefined') { defVal = null; } - - if (match) { - return decodeURIComponent(match[1]); - } - - return defVal; -} - -// Read a hash fragment variable -export function getHashVar(name, defVal) { - "use strict"; - const re = new RegExp('.*[&#]' + name + '=([^&]*)'), - match = document.location.hash.match(re); - if (typeof defVal === 'undefined') { defVal = null; } - - if (match) { - return decodeURIComponent(match[1]); - } - - return defVal; -} - -// Read a variable from the fragment or the query string -// Fragment takes precedence -export function getConfigVar(name, defVal) { - "use strict"; - const val = getHashVar(name); - - if (val === null) { - return getQueryVar(name, defVal); - } - - return val; -} - -/* - * Cookie handling. Dervied from: http://www.quirksmode.org/js/cookies.html - */ - -// No days means only for this browser session -export function createCookie(name, value, days) { - "use strict"; - let date, expires; - if (days) { - date = new Date(); - date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); - expires = "; expires=" + date.toGMTString(); - } else { - expires = ""; - } - - let secure; - if (document.location.protocol === "https:") { - secure = "; secure"; - } else { - secure = ""; - } - document.cookie = name + "=" + value + expires + "; path=/" + secure; -} - -export function readCookie(name, defaultValue) { - "use strict"; - const nameEQ = name + "="; - const ca = document.cookie.split(';'); - - for (let i = 0; i < ca.length; i += 1) { - let c = ca[i]; - while (c.charAt(0) === ' ') { - c = c.substring(1, c.length); - } - if (c.indexOf(nameEQ) === 0) { - return c.substring(nameEQ.length, c.length); - } - } - - return (typeof defaultValue !== 'undefined') ? defaultValue : null; -} - -export function eraseCookie(name) { - "use strict"; - createCookie(name, "", -1); -} - -/* - * Setting handling. - */ - -let settings = {}; - -export function initSettings(callback /*, ...callbackArgs */) { - "use strict"; - const callbackArgs = Array.prototype.slice.call(arguments, 1); - if (window.chrome && window.chrome.storage) { - window.chrome.storage.sync.get((cfg) => { - settings = cfg; - if (callback) { - callback.apply(this, callbackArgs); - } - }); - } else { - settings = {}; - if (callback) { - callback.apply(this, callbackArgs); - } - } -} - -// Update the settings cache, but do not write to permanent storage -export function setSetting(name, value) { - settings[name] = value; -} - -// No days means only for this browser session -export function writeSetting(name, value) { - "use strict"; - if (settings[name] === value) return; - settings[name] = value; - if (window.chrome && window.chrome.storage) { - window.chrome.storage.sync.set(settings); - } else { - localStorage.setItem(name, value); - } -} - -export function readSetting(name, defaultValue) { - "use strict"; - let value; - if ((name in settings) || (window.chrome && window.chrome.storage)) { - value = settings[name]; - } else { - value = localStorage.getItem(name); - settings[name] = value; - } - if (typeof value === "undefined") { - value = null; - } - - if (value === null && typeof defaultValue !== "undefined") { - return defaultValue; - } - - return value; -} - -export function eraseSetting(name) { - "use strict"; - // Deleting here means that next time the setting is read when using local - // storage, it will be pulled from local storage again. - // If the setting in local storage is changed (e.g. in another tab) - // between this delete and the next read, it could lead to an unexpected - // value change. - delete settings[name]; - if (window.chrome && window.chrome.storage) { - window.chrome.storage.sync.remove(name); - } else { - localStorage.removeItem(name); - } -} - -export function injectParamIfMissing(path, param, value) { - // force pretend that we're dealing with a relative path - // (assume that we wanted an extra if we pass one in) - path = "/" + path; - - const elem = document.createElement('a'); - elem.href = path; - - const param_eq = encodeURIComponent(param) + "="; - let query; - if (elem.search) { - query = elem.search.slice(1).split('&'); - } else { - query = []; - } - - if (!query.some(v => v.startsWith(param_eq))) { - query.push(param_eq + encodeURIComponent(value)); - elem.search = "?" + query.join("&"); - } - - // some browsers (e.g. IE11) may occasionally omit the leading slash - // in the elem.pathname string. Handle that case gracefully. - if (elem.pathname.charAt(0) == "/") { - return elem.pathname.slice(1) + elem.search + elem.hash; - } - - return elem.pathname + elem.search + elem.hash; -} - -// sadly, we can't use the Fetch API until we decide to drop -// IE11 support or polyfill promises and fetch in IE11. -// resolve will receive an object on success, while reject -// will receive either an event or an error on failure. -export function fetchJSON(path, resolve, reject) { - // NB: IE11 doesn't support JSON as a responseType - const req = new XMLHttpRequest(); - req.open('GET', path); - - req.onload = () => { - if (req.status === 200) { - let resObj; - try { - resObj = JSON.parse(req.responseText); - } catch (err) { - reject(err); - } - resolve(resObj); - } else { - reject(new Error("XHR got non-200 status while trying to load '" + path + "': " + req.status)); - } - }; - - req.onerror = evt => reject(new Error("XHR encountered an error while trying to load '" + path + "': " + evt.message)); - - req.ontimeout = evt => reject(new Error("XHR timed out while trying to load '" + path + "'")); - - req.send(); -} - -//Are we running inside the Kasm VDI Framework -export function isInsideKasmVDI() { - //TODO: We should use a more explicit way to detect we are running inside KasmVDI - try { - return window.self !== window.top; - } catch (e) { - return true; - } -} \ No newline at end of file diff --git a/kasmweb/bitbucket-pipelines.yml b/kasmweb/bitbucket-pipelines.yml deleted file mode 100644 index 920a62a..0000000 --- a/kasmweb/bitbucket-pipelines.yml +++ /dev/null @@ -1,26 +0,0 @@ -image: ubuntu:xenial - -pipelines: - default: - - step: - script: - - export BASE_DIR="$(readlink -f .)" - - export KASM_BUILD_ID="${RELEASE_VERSION}.${BITBUCKET_COMMIT:0:6}" - - export S3_BUILD_DIRECTORY="kasm_desktop_rx/${BITBUCKET_COMMIT}" - - export SANITIZED_BRANCH="$(echo $BITBUCKET_BRANCH | sed 's/\//_/g')" - - export BUILD_FILE="kasm_desktop_rx_${SANITIZED_BRANCH}.${BITBUCKET_COMMIT:0:6}.tar.gz" - - # Remove unnecessary files - - find ./ -maxdepth 1 -type f -name ".*" -delete - - rm bitbucket-pipelines.yml - - - tar -czzf ${BASE_DIR}/${BUILD_FILE} ./* --transform 's,^\.,kasm_desktop_rx,' - - - apt-get update - - apt-get install -y python-pip git curl - - pip install boto3==1.3.0 - - git clone https://bitbucket.org/awslabs/amazon-s3-bitbucket-pipelines-python.git - - python amazon-s3-bitbucket-pipelines-python/s3_upload.py "${S3_BUCKET}" ${BASE_DIR}/${BUILD_FILE} "${S3_BUILD_DIRECTORY}/${BUILD_FILE}" - - export S3_URL="https://${S3_BUCKET}.s3.amazonaws.com/${S3_BUILD_DIRECTORY}/${BUILD_FILE}" - - export BUILD_STATUS="{\"key\":\"doc\", \"state\":\"SUCCESSFUL\", \"name\":\"${BUILD_FILE}\", \"url\":\"${S3_URL}\"}" - - curl -H "Content-Type:application/json" -X POST --user "${BB_AUTH_STRING}" -d "${BUILD_STATUS}" "https://api.bitbucket.org/2.0/repositories/${BITBUCKET_REPO_OWNER}/${BITBUCKET_REPO_SLUG}/commit/${BITBUCKET_COMMIT}/statuses/build" \ No newline at end of file diff --git a/kasmweb/core/base64.js b/kasmweb/core/base64.js deleted file mode 100644 index 42ba53b..0000000 --- a/kasmweb/core/base64.js +++ /dev/null @@ -1,106 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// From: http://hg.mozilla.org/mozilla-central/raw-file/ec10630b1a54/js/src/devtools/jint/sunspider/string-base64.js - -import * as Log from './util/logging.js'; - -export default { - /* Convert data (an array of integers) to a Base64 string. */ - toBase64Table: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''), - base64Pad: '=', - - encode(data) { - "use strict"; - let result = ''; - const length = data.length; - const lengthpad = (length % 3); - // Convert every three bytes to 4 ascii characters. - - for (let i = 0; i < (length - 2); i += 3) { - result += this.toBase64Table[data[i] >> 2]; - result += this.toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)]; - result += this.toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)]; - result += this.toBase64Table[data[i + 2] & 0x3f]; - } - - // Convert the remaining 1 or 2 bytes, pad out to 4 characters. - const j = length - lengthpad; - if (lengthpad === 2) { - result += this.toBase64Table[data[j] >> 2]; - result += this.toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)]; - result += this.toBase64Table[(data[j + 1] & 0x0f) << 2]; - result += this.toBase64Table[64]; - } else if (lengthpad === 1) { - result += this.toBase64Table[data[j] >> 2]; - result += this.toBase64Table[(data[j] & 0x03) << 4]; - result += this.toBase64Table[64]; - result += this.toBase64Table[64]; - } - - return result; - }, - - /* Convert Base64 data to a string */ - /* eslint-disable comma-spacing */ - toBinaryTable: [ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, - -1, 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,-1, -1,-1,-1,-1, - -1,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,-1, -1,-1,-1,-1 - ], - /* eslint-enable comma-spacing */ - - decode(data, offset) { - offset = typeof(offset) !== 'undefined' ? offset : 0; - - let data_length = data.indexOf('=') - offset; - if (data_length < 0) { data_length = data.length - offset; } - - /* Every four characters is 3 resulting numbers */ - const result_length = (data_length >> 2) * 3 + Math.floor((data_length % 4) / 1.5); - const result = new Array(result_length); - - // Convert one by one. - - let leftbits = 0; // number of bits decoded, but yet to be appended - let leftdata = 0; // bits decoded, but yet to be appended - for (let idx = 0, i = offset; i < data.length; i++) { - const c = this.toBinaryTable[data.charCodeAt(i) & 0x7f]; - const padding = (data.charAt(i) === this.base64Pad); - // Skip illegal characters and whitespace - if (c === -1) { - Log.Error("Illegal character code " + data.charCodeAt(i) + " at position " + i); - continue; - } - - // Collect data into leftdata, update bitcount - leftdata = (leftdata << 6) | c; - leftbits += 6; - - // If we have 8 or more bits, append 8 bits to the result - if (leftbits >= 8) { - leftbits -= 8; - // Append if not padding. - if (!padding) { - result[idx++] = (leftdata >> leftbits) & 0xff; - } - leftdata &= (1 << leftbits) - 1; - } - } - - // If there are any bits left, the base64 string was corrupted - if (leftbits) { - const err = new Error('Corrupted base64 string'); - err.name = 'Base64-Error'; - throw err; - } - - return result; - } -}; /* End of Base64 namespace */ diff --git a/kasmweb/core/decoders/copyrect.js b/kasmweb/core/decoders/copyrect.js deleted file mode 100644 index a78ded7..0000000 --- a/kasmweb/core/decoders/copyrect.js +++ /dev/null @@ -1,24 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -export default class CopyRectDecoder { - decodeRect(x, y, width, height, sock, display, depth) { - if (sock.rQwait("COPYRECT", 4)) { - return false; - } - - let deltaX = sock.rQshift16(); - let deltaY = sock.rQshift16(); - display.copyImage(deltaX, deltaY, x, y, width, height); - - return true; - } -} diff --git a/kasmweb/core/decoders/hextile.js b/kasmweb/core/decoders/hextile.js deleted file mode 100644 index 07c86db..0000000 --- a/kasmweb/core/decoders/hextile.js +++ /dev/null @@ -1,138 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -import * as Log from '../util/logging.js'; - -export default class HextileDecoder { - constructor() { - this._tiles = 0; - this._lastsubencoding = 0; - } - - decodeRect(x, y, width, height, sock, display, depth) { - if (this._tiles === 0) { - this._tiles_x = Math.ceil(width / 16); - this._tiles_y = Math.ceil(height / 16); - this._total_tiles = this._tiles_x * this._tiles_y; - this._tiles = this._total_tiles; - } - - while (this._tiles > 0) { - let bytes = 1; - - if (sock.rQwait("HEXTILE", bytes)) { - return false; - } - - let rQ = sock.rQ; - let rQi = sock.rQi; - - let subencoding = rQ[rQi]; // Peek - if (subencoding > 30) { // Raw - throw new Error("Illegal hextile subencoding (subencoding: " + - subencoding + ")"); - } - - const curr_tile = this._total_tiles - this._tiles; - const tile_x = curr_tile % this._tiles_x; - const tile_y = Math.floor(curr_tile / this._tiles_x); - const tx = x + tile_x * 16; - const ty = y + tile_y * 16; - const tw = Math.min(16, (x + width) - tx); - const th = Math.min(16, (y + height) - ty); - - // Figure out how much we are expecting - if (subencoding & 0x01) { // Raw - bytes += tw * th * 4; - } else { - if (subencoding & 0x02) { // Background - bytes += 4; - } - if (subencoding & 0x04) { // Foreground - bytes += 4; - } - if (subencoding & 0x08) { // AnySubrects - bytes++; // Since we aren't shifting it off - - if (sock.rQwait("HEXTILE", bytes)) { - return false; - } - - let subrects = rQ[rQi + bytes - 1]; // Peek - if (subencoding & 0x10) { // SubrectsColoured - bytes += subrects * (4 + 2); - } else { - bytes += subrects * 2; - } - } - } - - if (sock.rQwait("HEXTILE", bytes)) { - return false; - } - - // We know the encoding and have a whole tile - rQi++; - if (subencoding === 0) { - if (this._lastsubencoding & 0x01) { - // Weird: ignore blanks are RAW - Log.Debug(" Ignoring blank after RAW"); - } else { - display.fillRect(tx, ty, tw, th, this._background); - } - } else if (subencoding & 0x01) { // Raw - display.blitImage(tx, ty, tw, th, rQ, rQi); - rQi += bytes - 1; - } else { - if (subencoding & 0x02) { // Background - this._background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]]; - rQi += 4; - } - if (subencoding & 0x04) { // Foreground - this._foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]]; - rQi += 4; - } - - display.startTile(tx, ty, tw, th, this._background); - if (subencoding & 0x08) { // AnySubrects - let subrects = rQ[rQi]; - rQi++; - - for (let s = 0; s < subrects; s++) { - let color; - if (subencoding & 0x10) { // SubrectsColoured - color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]]; - rQi += 4; - } else { - color = this._foreground; - } - const xy = rQ[rQi]; - rQi++; - const sx = (xy >> 4); - const sy = (xy & 0x0f); - - const wh = rQ[rQi]; - rQi++; - const sw = (wh >> 4) + 1; - const sh = (wh & 0x0f) + 1; - - display.subTile(sx, sy, sw, sh, color); - } - } - display.finishTile(); - } - this._lastsubencoding = subencoding; - this._tiles--; - } - - return true; - } -} diff --git a/kasmweb/core/decoders/raw.js b/kasmweb/core/decoders/raw.js deleted file mode 100644 index f676e0d..0000000 --- a/kasmweb/core/decoders/raw.js +++ /dev/null @@ -1,58 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -export default class RawDecoder { - constructor() { - this._lines = 0; - } - - decodeRect(x, y, width, height, sock, display, depth) { - if (this._lines === 0) { - this._lines = height; - } - - const pixelSize = depth == 8 ? 1 : 4; - const bytesPerLine = width * pixelSize; - - if (sock.rQwait("RAW", bytesPerLine)) { - return false; - } - - const cur_y = y + (height - this._lines); - const curr_height = Math.min(this._lines, - Math.floor(sock.rQlen / bytesPerLine)); - let data = sock.rQ; - let index = sock.rQi; - - // Convert data if needed - if (depth == 8) { - const pixels = width * curr_height; - const newdata = new Uint8Array(pixels * 4); - for (let i = 0; i < pixels; i++) { - newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3; - newdata[i * 4 + 1] = ((data[index + i] >> 2) & 0x3) * 255 / 3; - newdata[i * 4 + 2] = ((data[index + i] >> 4) & 0x3) * 255 / 3; - newdata[i * 4 + 4] = 0; - } - data = newdata; - index = 0; - } - - display.blitImage(x, cur_y, width, curr_height, data, index); - sock.rQskipBytes(curr_height * bytesPerLine); - this._lines -= curr_height; - if (this._lines > 0) { - return false; - } - - return true; - } -} diff --git a/kasmweb/core/decoders/rre.js b/kasmweb/core/decoders/rre.js deleted file mode 100644 index 57414a0..0000000 --- a/kasmweb/core/decoders/rre.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -export default class RREDecoder { - constructor() { - this._subrects = 0; - } - - decodeRect(x, y, width, height, sock, display, depth) { - if (this._subrects === 0) { - if (sock.rQwait("RRE", 4 + 4)) { - return false; - } - - this._subrects = sock.rQshift32(); - - let color = sock.rQshiftBytes(4); // Background - display.fillRect(x, y, width, height, color); - } - - while (this._subrects > 0) { - if (sock.rQwait("RRE", 4 + 8)) { - return false; - } - - let color = sock.rQshiftBytes(4); - let sx = sock.rQshift16(); - let sy = sock.rQshift16(); - let swidth = sock.rQshift16(); - let sheight = sock.rQshift16(); - display.fillRect(x + sx, y + sy, swidth, sheight, color); - - this._subrects--; - } - - return true; - } -} diff --git a/kasmweb/core/decoders/tight.js b/kasmweb/core/decoders/tight.js deleted file mode 100644 index 24a24cd..0000000 --- a/kasmweb/core/decoders/tight.js +++ /dev/null @@ -1,333 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca) - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -import * as Log from '../util/logging.js'; -import Inflator from "../inflator.js"; - -export default class TightDecoder { - constructor() { - this._ctl = null; - this._filter = null; - this._numColors = 0; - this._palette = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel) - this._len = 0; - - this._zlibs = []; - for (let i = 0; i < 4; i++) { - this._zlibs[i] = new Inflator(); - } - } - - decodeRect(x, y, width, height, sock, display, depth) { - if (this._ctl === null) { - if (sock.rQwait("TIGHT compression-control", 1)) { - return false; - } - - this._ctl = sock.rQshift8(); - - // Reset streams if the server requests it - for (let i = 0; i < 4; i++) { - if ((this._ctl >> i) & 1) { - this._zlibs[i].reset(); - Log.Info("Reset zlib stream " + i); - } - } - - // Figure out filter - this._ctl = this._ctl >> 4; - } - - let ret; - - if (this._ctl === 0x08) { - ret = this._fillRect(x, y, width, height, - sock, display, depth); - } else if (this._ctl === 0x09) { - ret = this._jpegRect(x, y, width, height, - sock, display, depth); - } else if (this._ctl === 0x0A) { - ret = this._pngRect(x, y, width, height, - sock, display, depth); - } else if (this._ctl === 0x0B) { - ret = this._webpRect(x, y, width, height, - sock, display, depth); - } else if ((this._ctl & 0x80) == 0) { - ret = this._basicRect(this._ctl, x, y, width, height, - sock, display, depth); - } else { - throw new Error("Illegal tight compression received (ctl: " + - this._ctl + ")"); - } - - if (ret) { - this._ctl = null; - } - - return ret; - } - - _fillRect(x, y, width, height, sock, display, depth) { - if (sock.rQwait("TIGHT", 3)) { - return false; - } - - const rQi = sock.rQi; - const rQ = sock.rQ; - - display.fillRect(x, y, width, height, - [rQ[rQi + 2], rQ[rQi + 1], rQ[rQi]], false); - sock.rQskipBytes(3); - - return true; - } - - _jpegRect(x, y, width, height, sock, display, depth) { - let data = this._readData(sock); - if (data === null) { - return false; - } - - display.imageRect(x, y, width, height, "image/jpeg", data); - - return true; - } - - _webpRect(x, y, width, height, sock, display, depth) { - let data = this._readData(sock); - if (data === null) { - return false; - } - - display.imageRect(x, y, width, height, "image/webp", data); - - return true; - } - - _pngRect(x, y, width, height, sock, display, depth) { - throw new Error("PNG received in standard Tight rect"); - } - - _basicRect(ctl, x, y, width, height, sock, display, depth) { - if (this._filter === null) { - if (ctl & 0x4) { - if (sock.rQwait("TIGHT", 1)) { - return false; - } - - this._filter = sock.rQshift8(); - } else { - // Implicit CopyFilter - this._filter = 0; - } - } - - let streamId = ctl & 0x3; - - let ret; - - switch (this._filter) { - case 0: // CopyFilter - ret = this._copyFilter(streamId, x, y, width, height, - sock, display, depth); - break; - case 1: // PaletteFilter - ret = this._paletteFilter(streamId, x, y, width, height, - sock, display, depth); - break; - case 2: // GradientFilter - ret = this._gradientFilter(streamId, x, y, width, height, - sock, display, depth); - break; - default: - throw new Error("Illegal tight filter received (ctl: " + - this._filter + ")"); - } - - if (ret) { - this._filter = null; - } - - return ret; - } - - _copyFilter(streamId, x, y, width, height, sock, display, depth) { - const uncompressedSize = width * height * 3; - let data; - - if (uncompressedSize < 12) { - if (sock.rQwait("TIGHT", uncompressedSize)) { - return false; - } - - data = sock.rQshiftBytes(uncompressedSize); - } else { - data = this._readData(sock); - if (data === null) { - return false; - } - - data = this._zlibs[streamId].inflate(data, true, uncompressedSize); - if (data.length != uncompressedSize) { - throw new Error("Incomplete zlib block"); - } - } - - display.blitRgbImage(x, y, width, height, data, 0, false); - - return true; - } - - _paletteFilter(streamId, x, y, width, height, sock, display, depth) { - if (this._numColors === 0) { - if (sock.rQwait("TIGHT palette", 1)) { - return false; - } - - const numColors = sock.rQpeek8() + 1; - const paletteSize = numColors * 3; - - if (sock.rQwait("TIGHT palette", 1 + paletteSize)) { - return false; - } - - this._numColors = numColors; - sock.rQskipBytes(1); - - sock.rQshiftTo(this._palette, paletteSize); - } - - const bpp = (this._numColors <= 2) ? 1 : 8; - const rowSize = Math.floor((width * bpp + 7) / 8); - const uncompressedSize = rowSize * height; - - let data; - - if (uncompressedSize < 12) { - if (sock.rQwait("TIGHT", uncompressedSize)) { - return false; - } - - data = sock.rQshiftBytes(uncompressedSize); - } else { - data = this._readData(sock); - if (data === null) { - return false; - } - - data = this._zlibs[streamId].inflate(data, true, uncompressedSize); - if (data.length != uncompressedSize) { - throw new Error("Incomplete zlib block"); - } - } - - // Convert indexed (palette based) image data to RGB - if (this._numColors == 2) { - this._monoRect(x, y, width, height, data, this._palette, display); - } else { - this._paletteRect(x, y, width, height, data, this._palette, display); - } - - this._numColors = 0; - - return true; - } - - _monoRect(x, y, width, height, data, palette, display) { - // Convert indexed (palette based) image data to RGB - // TODO: reduce number of calculations inside loop - const dest = this._getScratchBuffer(width * height * 4); - const w = Math.floor((width + 7) / 8); - const w1 = Math.floor(width / 8); - - for (let y = 0; y < height; y++) { - let dp, sp, x; - for (x = 0; x < w1; x++) { - for (let b = 7; b >= 0; b--) { - dp = (y * width + x * 8 + 7 - b) * 4; - sp = (data[y * w + x] >> b & 1) * 3; - dest[dp] = palette[sp]; - dest[dp + 1] = palette[sp + 1]; - dest[dp + 2] = palette[sp + 2]; - dest[dp + 3] = 255; - } - } - - for (let b = 7; b >= 8 - width % 8; b--) { - dp = (y * width + x * 8 + 7 - b) * 4; - sp = (data[y * w + x] >> b & 1) * 3; - dest[dp] = palette[sp]; - dest[dp + 1] = palette[sp + 1]; - dest[dp + 2] = palette[sp + 2]; - dest[dp + 3] = 255; - } - } - - display.blitRgbxImage(x, y, width, height, dest, 0, false); - } - - _paletteRect(x, y, width, height, data, palette, display) { - // Convert indexed (palette based) image data to RGB - const dest = this._getScratchBuffer(width * height * 4); - const total = width * height * 4; - for (let i = 0, j = 0; i < total; i += 4, j++) { - const sp = data[j] * 3; - dest[i] = palette[sp]; - dest[i + 1] = palette[sp + 1]; - dest[i + 2] = palette[sp + 2]; - dest[i + 3] = 255; - } - - display.blitRgbxImage(x, y, width, height, dest, 0, false); - } - - _gradientFilter(streamId, x, y, width, height, sock, display, depth) { - throw new Error("Gradient filter not implemented"); - } - - _readData(sock) { - if (this._len === 0) { - if (sock.rQwait("TIGHT", 3)) { - return null; - } - - let byte; - - byte = sock.rQshift8(); - this._len = byte & 0x7f; - if (byte & 0x80) { - byte = sock.rQshift8(); - this._len |= (byte & 0x7f) << 7; - if (byte & 0x80) { - byte = sock.rQshift8(); - this._len |= byte << 14; - } - } - } - - if (sock.rQwait("TIGHT", this._len)) { - return null; - } - - let data = sock.rQshiftBytes(this._len); - this._len = 0; - - return data; - } - - _getScratchBuffer(size) { - if (!this._scratchBuffer || (this._scratchBuffer.length < size)) { - this._scratchBuffer = new Uint8Array(size); - } - return this._scratchBuffer; - } -} diff --git a/kasmweb/core/decoders/tightpng.js b/kasmweb/core/decoders/tightpng.js deleted file mode 100644 index 163da98..0000000 --- a/kasmweb/core/decoders/tightpng.js +++ /dev/null @@ -1,29 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -import TightDecoder from './tight.js'; - -export default class TightPNGDecoder extends TightDecoder { - _pngRect(x, y, width, height, sock, display, depth) { - let data = this._readData(sock); - if (data === null) { - return false; - } - - display.imageRect(x, y, width, height, "image/png", data); - - return true; - } - - _basicRect(ctl, x, y, width, height, sock, display, depth) { - throw new Error("BasicCompression received in TightPNG rect"); - } -} diff --git a/kasmweb/core/des.js b/kasmweb/core/des.js deleted file mode 100644 index 175066b..0000000 --- a/kasmweb/core/des.js +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Ported from Flashlight VNC ActionScript implementation: - * http://www.wizhelp.com/flashlight-vnc/ - * - * Full attribution follows: - * - * ------------------------------------------------------------------------- - * - * This DES class has been extracted from package Acme.Crypto for use in VNC. - * The unnecessary odd parity code has been removed. - * - * These changes are: - * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - - * DesCipher - the DES encryption method - * - * The meat of this code is by Dave Zimmerman , and is: - * - * Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved. - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and - * without fee is hereby granted, provided that this copyright notice is kept - * intact. - * - * WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY - * OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED - * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE - * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. - * - * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE - * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE - * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT - * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE - * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE - * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE - * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP - * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR - * HIGH RISK ACTIVITIES. - * - * - * The rest is: - * - * Copyright (C) 1996 by Jef Poskanzer . 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. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. - * - * Visit the ACME Labs Java page for up-to-date versions of this and other - * fine Java utilities: http://www.acme.com/java/ - */ - -/* eslint-disable comma-spacing */ - -export default function DES(passwd) { - "use strict"; - - // Tables, permutations, S-boxes, etc. - const PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3, - 25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39, - 50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ], - totrot = [ 1, 2, 4, 6, 8,10,12,14,15,17,19,21,23,25,27,28], - z = 0x0, - keys = []; - let a,b,c,d,e,f; - - a=1<<16; b=1<<24; c=a|b; d=1<<2; e=1<<10; f=d|e; - const SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d, - z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z, - a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f, - c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d]; - a=1<<20; b=1<<31; c=a|b; d=1<<5; e=1<<15; f=d|e; - const SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d, - a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f, - z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z, - z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e]; - a=1<<17; b=1<<27; c=a|b; d=1<<3; e=1<<9; f=d|e; - const SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f, - b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z, - c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d, - b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e]; - a=1<<13; b=1<<23; c=a|b; d=1<<0; e=1<<7; f=d|e; - const SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d, - z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f, - b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e, - c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e]; - a=1<<25; b=1<<30; c=a|b; d=1<<8; e=1<<19; f=d|e; - const SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z, - a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f, - z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e, - c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d]; - a=1<<22; b=1<<29; c=a|b; d=1<<4; e=1<<14; f=d|e; - const SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f, - z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z, - b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z, - a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f]; - a=1<<21; b=1<<26; c=a|b; d=1<<1; e=1<<11; f=d|e; - const SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f, - b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e, - b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e, - z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d]; - a=1<<18; b=1<<28; c=a|b; d=1<<6; e=1<<12; f=d|e; - const SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d, - c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z, - a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f, - z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e]; - - // Set the key. - function setKeys(keyBlock) { - const pc1m = [], pcr = [], kn = []; - - for (let j = 0, l = 56; j < 56; ++j, l -= 8) { - l += l < -5 ? 65 : l < -3 ? 31 : l < -1 ? 63 : l === 27 ? 35 : 0; // PC1 - const m = l & 0x7; - pc1m[j] = ((keyBlock[l >>> 3] & (1<>> 10; - keys[KnLi] |= (raw1 & 0x00000fc0) >>> 6; - ++KnLi; - keys[KnLi] = (raw0 & 0x0003f000) << 12; - keys[KnLi] |= (raw0 & 0x0000003f) << 16; - keys[KnLi] |= (raw1 & 0x0003f000) >>> 4; - keys[KnLi] |= (raw1 & 0x0000003f); - ++KnLi; - } - } - - // Encrypt 8 bytes of text - function enc8(text) { - const b = text.slice(); - let i = 0, l, r, x; // left, right, accumulator - - // Squash 8 bytes to 2 ints - l = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; - r = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; - - x = ((l >>> 4) ^ r) & 0x0f0f0f0f; - r ^= x; - l ^= (x << 4); - x = ((l >>> 16) ^ r) & 0x0000ffff; - r ^= x; - l ^= (x << 16); - x = ((r >>> 2) ^ l) & 0x33333333; - l ^= x; - r ^= (x << 2); - x = ((r >>> 8) ^ l) & 0x00ff00ff; - l ^= x; - r ^= (x << 8); - r = (r << 1) | ((r >>> 31) & 1); - x = (l ^ r) & 0xaaaaaaaa; - l ^= x; - r ^= x; - l = (l << 1) | ((l >>> 31) & 1); - - for (let i = 0, keysi = 0; i < 8; ++i) { - x = (r << 28) | (r >>> 4); - x ^= keys[keysi++]; - let fval = SP7[x & 0x3f]; - fval |= SP5[(x >>> 8) & 0x3f]; - fval |= SP3[(x >>> 16) & 0x3f]; - fval |= SP1[(x >>> 24) & 0x3f]; - x = r ^ keys[keysi++]; - fval |= SP8[x & 0x3f]; - fval |= SP6[(x >>> 8) & 0x3f]; - fval |= SP4[(x >>> 16) & 0x3f]; - fval |= SP2[(x >>> 24) & 0x3f]; - l ^= fval; - x = (l << 28) | (l >>> 4); - x ^= keys[keysi++]; - fval = SP7[x & 0x3f]; - fval |= SP5[(x >>> 8) & 0x3f]; - fval |= SP3[(x >>> 16) & 0x3f]; - fval |= SP1[(x >>> 24) & 0x3f]; - x = l ^ keys[keysi++]; - fval |= SP8[x & 0x0000003f]; - fval |= SP6[(x >>> 8) & 0x3f]; - fval |= SP4[(x >>> 16) & 0x3f]; - fval |= SP2[(x >>> 24) & 0x3f]; - r ^= fval; - } - - r = (r << 31) | (r >>> 1); - x = (l ^ r) & 0xaaaaaaaa; - l ^= x; - r ^= x; - l = (l << 31) | (l >>> 1); - x = ((l >>> 8) ^ r) & 0x00ff00ff; - r ^= x; - l ^= (x << 8); - x = ((l >>> 2) ^ r) & 0x33333333; - r ^= x; - l ^= (x << 2); - x = ((r >>> 16) ^ l) & 0x0000ffff; - l ^= x; - r ^= (x << 16); - x = ((r >>> 4) ^ l) & 0x0f0f0f0f; - l ^= x; - r ^= (x << 4); - - // Spread ints to bytes - x = [r, l]; - for (i = 0; i < 8; i++) { - b[i] = (x[i>>>2] >>> (8 * (3 - (i % 4)))) % 256; - if (b[i] < 0) { b[i] += 256; } // unsigned - } - return b; - } - - // Encrypt 16 bytes of text using passwd as key - function encrypt(t) { - return enc8(t.slice(0, 8)).concat(enc8(t.slice(8, 16))); - } - - setKeys(passwd); // Setup keys - return {'encrypt': encrypt}; // Public interface - -} diff --git a/kasmweb/core/display.js b/kasmweb/core/display.js deleted file mode 100644 index 041daee..0000000 --- a/kasmweb/core/display.js +++ /dev/null @@ -1,656 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -import * as Log from './util/logging.js'; -import Base64 from "./base64.js"; - -let SUPPORTS_IMAGEDATA_CONSTRUCTOR = false; -try { - new ImageData(new Uint8ClampedArray(4), 1, 1); - SUPPORTS_IMAGEDATA_CONSTRUCTOR = true; -} catch (ex) { - // ignore failure -} - -export default class Display { - constructor(target) { - this._drawCtx = null; - this._c_forceCanvas = false; - - this._renderQ = []; // queue drawing actions for in-oder rendering - this._flushing = false; - - // the full frame buffer (logical canvas) size - this._fb_width = 0; - this._fb_height = 0; - - this._prevDrawStyle = ""; - this._tile = null; - this._tile16x16 = null; - this._tile_x = 0; - this._tile_y = 0; - - Log.Debug(">> Display.constructor"); - - // The visible canvas - this._target = target; - - if (!this._target) { - throw new Error("Target must be set"); - } - - if (typeof this._target === 'string') { - throw new Error('target must be a DOM element'); - } - - if (!this._target.getContext) { - throw new Error("no getContext method"); - } - - this._targetCtx = this._target.getContext('2d'); - - // the visible canvas viewport (i.e. what actually gets seen) - this._viewportLoc = { 'x': 0, 'y': 0, 'w': this._target.width, 'h': this._target.height }; - - // The hidden canvas, where we do the actual rendering - this._backbuffer = document.createElement('canvas'); - this._drawCtx = this._backbuffer.getContext('2d'); - - this._damageBounds = { left: 0, top: 0, - right: this._backbuffer.width, - bottom: this._backbuffer.height }; - - Log.Debug("User Agent: " + navigator.userAgent); - - this.clear(); - - // Check canvas features - if (!('createImageData' in this._drawCtx)) { - throw new Error("Canvas does not support createImageData"); - } - - this._tile16x16 = this._drawCtx.createImageData(16, 16); - Log.Debug("<< Display.constructor"); - - // ===== PROPERTIES ===== - - this._scale = 1.0; - this._clipViewport = false; - this.logo = null; - - // ===== EVENT HANDLERS ===== - - this.onflush = () => {}; // A flush request has finished - } - - // ===== PROPERTIES ===== - - get scale() { return this._scale; } - set scale(scale) { - this._rescale(scale); - } - - get clipViewport() { return this._clipViewport; } - set clipViewport(viewport) { - this._clipViewport = viewport; - // May need to readjust the viewport dimensions - const vp = this._viewportLoc; - this.viewportChangeSize(vp.w, vp.h); - this.viewportChangePos(0, 0); - } - - get width() { - return this._fb_width; - } - - get height() { - return this._fb_height; - } - - // ===== PUBLIC METHODS ===== - - viewportChangePos(deltaX, deltaY) { - const vp = this._viewportLoc; - deltaX = Math.floor(deltaX); - deltaY = Math.floor(deltaY); - - if (!this._clipViewport) { - deltaX = -vp.w; // clamped later of out of bounds - deltaY = -vp.h; - } - - const vx2 = vp.x + vp.w - 1; - const vy2 = vp.y + vp.h - 1; - - // Position change - - if (deltaX < 0 && vp.x + deltaX < 0) { - deltaX = -vp.x; - } - if (vx2 + deltaX >= this._fb_width) { - deltaX -= vx2 + deltaX - this._fb_width + 1; - } - - if (vp.y + deltaY < 0) { - deltaY = -vp.y; - } - if (vy2 + deltaY >= this._fb_height) { - deltaY -= (vy2 + deltaY - this._fb_height + 1); - } - - if (deltaX === 0 && deltaY === 0) { - return; - } - Log.Debug("viewportChange deltaX: " + deltaX + ", deltaY: " + deltaY); - - vp.x += deltaX; - vp.y += deltaY; - - this._damage(vp.x, vp.y, vp.w, vp.h); - - this.flip(); - } - - viewportChangeSize(width, height) { - - if (!this._clipViewport || - typeof(width) === "undefined" || - typeof(height) === "undefined") { - - Log.Debug("Setting viewport to full display region"); - width = this._fb_width; - height = this._fb_height; - } - - width = Math.floor(width); - height = Math.floor(height); - - if (width > this._fb_width) { - width = this._fb_width; - } - if (height > this._fb_height) { - height = this._fb_height; - } - - const vp = this._viewportLoc; - if (vp.w !== width || vp.h !== height) { - vp.w = width; - vp.h = height; - - const canvas = this._target; - canvas.width = width; - canvas.height = height; - - // The position might need to be updated if we've grown - this.viewportChangePos(0, 0); - - this._damage(vp.x, vp.y, vp.w, vp.h); - this.flip(); - - // Update the visible size of the target canvas - this._rescale(this._scale); - } - } - - absX(x) { - return x / this._scale + this._viewportLoc.x; - } - - absY(y) { - return y / this._scale + this._viewportLoc.y; - } - - resize(width, height) { - this._prevDrawStyle = ""; - - this._fb_width = width; - this._fb_height = height; - - const canvas = this._backbuffer; - if (canvas.width !== width || canvas.height !== height) { - - // We have to save the canvas data since changing the size will clear it - let saveImg = null; - if (canvas.width > 0 && canvas.height > 0) { - saveImg = this._drawCtx.getImageData(0, 0, canvas.width, canvas.height); - } - - if (canvas.width !== width) { - canvas.width = width; - } - if (canvas.height !== height) { - canvas.height = height; - } - - if (saveImg) { - this._drawCtx.putImageData(saveImg, 0, 0); - } - } - - // Readjust the viewport as it may be incorrectly sized - // and positioned - const vp = this._viewportLoc; - this.viewportChangeSize(vp.w, vp.h); - this.viewportChangePos(0, 0); - } - - // Track what parts of the visible canvas that need updating - _damage(x, y, w, h) { - if (x < this._damageBounds.left) { - this._damageBounds.left = x; - } - if (y < this._damageBounds.top) { - this._damageBounds.top = y; - } - if ((x + w) > this._damageBounds.right) { - this._damageBounds.right = x + w; - } - if ((y + h) > this._damageBounds.bottom) { - this._damageBounds.bottom = y + h; - } - } - - // Update the visible canvas with the contents of the - // rendering canvas - flip(from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - this._renderQ_push({ - 'type': 'flip' - }); - } else { - let x = this._damageBounds.left; - let y = this._damageBounds.top; - let w = this._damageBounds.right - x; - let h = this._damageBounds.bottom - y; - - let vx = x - this._viewportLoc.x; - let vy = y - this._viewportLoc.y; - - if (vx < 0) { - w += vx; - x -= vx; - vx = 0; - } - if (vy < 0) { - h += vy; - y -= vy; - vy = 0; - } - - if ((vx + w) > this._viewportLoc.w) { - w = this._viewportLoc.w - vx; - } - if ((vy + h) > this._viewportLoc.h) { - h = this._viewportLoc.h - vy; - } - - if ((w > 0) && (h > 0)) { - // FIXME: We may need to disable image smoothing here - // as well (see copyImage()), but we haven't - // noticed any problem yet. - this._targetCtx.drawImage(this._backbuffer, - x, y, w, h, - vx, vy, w, h); - } - - this._damageBounds.left = this._damageBounds.top = 65535; - this._damageBounds.right = this._damageBounds.bottom = 0; - } - } - - clear() { - if (this._logo) { - this.resize(this._logo.width, this._logo.height); - this.imageRect(0, 0, - this._logo.width, this._logo.height, - this._logo.type, this._logo.data); - } else { - this.resize(240, 20); - this._drawCtx.clearRect(0, 0, this._fb_width, this._fb_height); - } - this.flip(); - } - - pending() { - return this._renderQ.length > 0; - } - - flush() { - if (this._renderQ.length === 0) { - this.onflush(); - } else { - this._flushing = true; - } - } - - fillRect(x, y, width, height, color, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - this._renderQ_push({ - 'type': 'fill', - 'x': x, - 'y': y, - 'width': width, - 'height': height, - 'color': color - }); - } else { - this._setFillColor(color); - this._drawCtx.fillRect(x, y, width, height); - this._damage(x, y, width, height); - } - } - - copyImage(old_x, old_y, new_x, new_y, w, h, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - this._renderQ_push({ - 'type': 'copy', - 'old_x': old_x, - 'old_y': old_y, - 'x': new_x, - 'y': new_y, - 'width': w, - 'height': h, - }); - } else { - // Due to this bug among others [1] we need to disable the image-smoothing to - // avoid getting a blur effect when copying data. - // - // 1. https://bugzilla.mozilla.org/show_bug.cgi?id=1194719 - // - // We need to set these every time since all properties are reset - // when the the size is changed - this._drawCtx.mozImageSmoothingEnabled = false; - this._drawCtx.webkitImageSmoothingEnabled = false; - this._drawCtx.msImageSmoothingEnabled = false; - this._drawCtx.imageSmoothingEnabled = false; - - this._drawCtx.drawImage(this._backbuffer, - old_x, old_y, w, h, - new_x, new_y, w, h); - this._damage(new_x, new_y, w, h); - } - } - - imageRect(x, y, w, h, mime, arr) { - const img = new Image(); - img.src = "data: " + mime + ";base64," + Base64.encode(arr); - this._renderQ_push({ - 'type': 'img', - 'img': img, - 'x': x, - 'y': y, - 'w': w, - 'h': h - }); - } - - // start updating a tile - startTile(x, y, width, height, color) { - this._tile_x = x; - this._tile_y = y; - if (width === 16 && height === 16) { - this._tile = this._tile16x16; - } else { - this._tile = this._drawCtx.createImageData(width, height); - } - - const red = color[2]; - const green = color[1]; - const blue = color[0]; - - const data = this._tile.data; - for (let i = 0; i < width * height * 4; i += 4) { - data[i] = red; - data[i + 1] = green; - data[i + 2] = blue; - data[i + 3] = 255; - } - } - - // update sub-rectangle of the current tile - subTile(x, y, w, h, color) { - const red = color[2]; - const green = color[1]; - const blue = color[0]; - const xend = x + w; - const yend = y + h; - - const data = this._tile.data; - const width = this._tile.width; - for (let j = y; j < yend; j++) { - for (let i = x; i < xend; i++) { - const p = (i + (j * width)) * 4; - data[p] = red; - data[p + 1] = green; - data[p + 2] = blue; - data[p + 3] = 255; - } - } - } - - // draw the current tile to the screen - finishTile() { - this._drawCtx.putImageData(this._tile, this._tile_x, this._tile_y); - this._damage(this._tile_x, this._tile_y, - this._tile.width, this._tile.height); - } - - blitImage(x, y, width, height, arr, offset, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - // NB(directxman12): it's technically more performant here to use preallocated arrays, - // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, - // this probably isn't getting called *nearly* as much - const new_arr = new Uint8Array(width * height * 4); - new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); - this._renderQ_push({ - 'type': 'blit', - 'data': new_arr, - 'x': x, - 'y': y, - 'width': width, - 'height': height, - }); - } else { - this._bgrxImageData(x, y, width, height, arr, offset); - } - } - - blitRgbImage(x, y, width, height, arr, offset, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - // NB(directxman12): it's technically more performant here to use preallocated arrays, - // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, - // this probably isn't getting called *nearly* as much - const new_arr = new Uint8Array(width * height * 3); - new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); - this._renderQ_push({ - 'type': 'blitRgb', - 'data': new_arr, - 'x': x, - 'y': y, - 'width': width, - 'height': height, - }); - } else { - this._rgbImageData(x, y, width, height, arr, offset); - } - } - - blitRgbxImage(x, y, width, height, arr, offset, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - // NB(directxman12): it's technically more performant here to use preallocated arrays, - // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, - // this probably isn't getting called *nearly* as much - const new_arr = new Uint8Array(width * height * 4); - new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); - this._renderQ_push({ - 'type': 'blitRgbx', - 'data': new_arr, - 'x': x, - 'y': y, - 'width': width, - 'height': height, - }); - } else { - this._rgbxImageData(x, y, width, height, arr, offset); - } - } - - drawImage(img, x, y, w, h) { - if (img.width != w || img.height != h) { - this._drawCtx.drawImage(img, x, y, w, h); - } else { - this._drawCtx.drawImage(img, x, y); - } - this._damage(x, y, w, h); - } - - autoscale(containerWidth, containerHeight) { - const vp = this._viewportLoc; - const targetAspectRatio = containerWidth / containerHeight; - const fbAspectRatio = vp.w / vp.h; - - let scaleRatio; - if (fbAspectRatio >= targetAspectRatio) { - scaleRatio = containerWidth / vp.w; - } else { - scaleRatio = containerHeight / vp.h; - } - - this._rescale(scaleRatio); - } - - // ===== PRIVATE METHODS ===== - - _rescale(factor) { - this._scale = factor; - const vp = this._viewportLoc; - - // NB(directxman12): If you set the width directly, or set the - // style width to a number, the canvas is cleared. - // However, if you set the style width to a string - // ('NNNpx'), the canvas is scaled without clearing. - const width = factor * vp.w + 'px'; - const height = factor * vp.h + 'px'; - - if ((this._target.style.width !== width) || - (this._target.style.height !== height)) { - this._target.style.width = width; - this._target.style.height = height; - } - } - - _setFillColor(color) { - const newStyle = 'rgb(' + color[2] + ',' + color[1] + ',' + color[0] + ')'; - if (newStyle !== this._prevDrawStyle) { - this._drawCtx.fillStyle = newStyle; - this._prevDrawStyle = newStyle; - } - } - - _rgbImageData(x, y, width, height, arr, offset) { - const img = this._drawCtx.createImageData(width, height); - const data = img.data; - for (let i = 0, j = offset; i < width * height * 4; i += 4, j += 3) { - data[i] = arr[j]; - data[i + 1] = arr[j + 1]; - data[i + 2] = arr[j + 2]; - data[i + 3] = 255; // Alpha - } - this._drawCtx.putImageData(img, x, y); - this._damage(x, y, img.width, img.height); - } - - _bgrxImageData(x, y, width, height, arr, offset) { - const img = this._drawCtx.createImageData(width, height); - const data = img.data; - for (let i = 0, j = offset; i < width * height * 4; i += 4, j += 4) { - data[i] = arr[j + 2]; - data[i + 1] = arr[j + 1]; - data[i + 2] = arr[j]; - data[i + 3] = 255; // Alpha - } - this._drawCtx.putImageData(img, x, y); - this._damage(x, y, img.width, img.height); - } - - _rgbxImageData(x, y, width, height, arr, offset) { - // NB(directxman12): arr must be an Type Array view - let img; - if (SUPPORTS_IMAGEDATA_CONSTRUCTOR) { - img = new ImageData(new Uint8ClampedArray(arr.buffer, arr.byteOffset, width * height * 4), width, height); - } else { - img = this._drawCtx.createImageData(width, height); - img.data.set(new Uint8ClampedArray(arr.buffer, arr.byteOffset, width * height * 4)); - } - this._drawCtx.putImageData(img, x, y); - this._damage(x, y, img.width, img.height); - } - - _renderQ_push(action) { - this._renderQ.push(action); - if (this._renderQ.length === 1) { - // If this can be rendered immediately it will be, otherwise - // the scanner will wait for the relevant event - this._scan_renderQ(); - } - } - - _resume_renderQ() { - // "this" is the object that is ready, not the - // display object - this.removeEventListener('load', this._noVNC_display._resume_renderQ); - this._noVNC_display._scan_renderQ(); - } - - _scan_renderQ() { - let ready = true; - while (ready && this._renderQ.length > 0) { - const a = this._renderQ[0]; - switch (a.type) { - case 'flip': - this.flip(true); - break; - case 'copy': - this.copyImage(a.old_x, a.old_y, a.x, a.y, a.width, a.height, true); - break; - case 'fill': - this.fillRect(a.x, a.y, a.width, a.height, a.color, true); - break; - case 'blit': - this.blitImage(a.x, a.y, a.width, a.height, a.data, 0, true); - break; - case 'blitRgb': - this.blitRgbImage(a.x, a.y, a.width, a.height, a.data, 0, true); - break; - case 'blitRgbx': - this.blitRgbxImage(a.x, a.y, a.width, a.height, a.data, 0, true); - break; - case 'img': - if (a.img.complete) { - this.drawImage(a.img, a.x, a.y, a.w, a.h); - } else { - a.img._noVNC_display = this; - a.img.addEventListener('load', this._resume_renderQ); - // We need to wait for this image to 'load' - // to keep things in-order - ready = false; - } - break; - } - - if (ready) { - this._renderQ.shift(); - } - } - - if (this._renderQ.length === 0 && this._flushing) { - this._flushing = false; - this.onflush(); - } - } -} diff --git a/kasmweb/core/encodings.js b/kasmweb/core/encodings.js deleted file mode 100644 index a05e032..0000000 --- a/kasmweb/core/encodings.js +++ /dev/null @@ -1,65 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -export const encodings = { - encodingRaw: 0, - encodingCopyRect: 1, - encodingRRE: 2, - encodingHextile: 5, - encodingTight: 7, - encodingTightPNG: -260, - - pseudoEncodingQualityLevel9: -23, - pseudoEncodingQualityLevel0: -32, - pseudoEncodingDesktopSize: -223, - pseudoEncodingLastRect: -224, - pseudoEncodingCursor: -239, - pseudoEncodingQEMUExtendedKeyEvent: -258, - pseudoEncodingExtendedDesktopSize: -308, - pseudoEncodingXvp: -309, - pseudoEncodingFence: -312, - pseudoEncodingContinuousUpdates: -313, - pseudoEncodingCompressLevel9: -247, - pseudoEncodingCompressLevel0: -256, - pseudoEncodingWEBP: -1024, - pseudoEncodingJpegVideoQualityLevel0: -1023, - pseudoEncodingJpegVideoQualityLevel9: -1014, - pseudoEncodingWebpVideoQualityLevel0: -1013, - pseudoEncodingWebpVideoQualityLevel9: -1004, - pseudoEncodingTreatLosslessLevel0: -1003, - pseudoEncodingTreatLosslessLevel10: -993, - pseudoEncodingPreferBandwidth: -992, - pseudoEncodingDynamicQualityMinLevel0: -991, - pseudoEncodingDynamicQualityMinLevel9: -982, - pseudoEncodingDynamicQualityMaxLevel0: -981, - pseudoEncodingDynamicQualityMaxLevel9: -972, - pseudoEncodingVideoAreaLevel1: -971, - pseudoEncodingVideoAreaLevel100: -871, - pseudoEncodingVideoTimeLevel0: -870, - pseudoEncodingVideoTimeLevel100: -770, - - pseudoEncodingFrameRateLevel10: -2048, - pseudoEncodingFrameRateLevel60: -1998, - pseudoEncodingMaxVideoResolution: -1997, - pseudoEncodingVideoScalingLevel0: -1996, - pseudoEncodingVideoScalingLevel9: -1987, - pseudoEncodingVideoOutTimeLevel1: -1986, - pseudoEncodingVideoOutTimeLevel100: -1887, -}; - -export function encodingName(num) { - switch (num) { - case encodings.encodingRaw: return "Raw"; - case encodings.encodingCopyRect: return "CopyRect"; - case encodings.encodingRRE: return "RRE"; - case encodings.encodingHextile: return "Hextile"; - case encodings.encodingTight: return "Tight"; - case encodings.encodingTightPNG: return "TightPNG"; - default: return "[unknown encoding " + num + "]"; - } -} diff --git a/kasmweb/core/inflator.js b/kasmweb/core/inflator.js deleted file mode 100644 index 0eab8fe..0000000 --- a/kasmweb/core/inflator.js +++ /dev/null @@ -1,38 +0,0 @@ -import { inflateInit, inflate, inflateReset } from "../vendor/pako/lib/zlib/inflate.js"; -import ZStream from "../vendor/pako/lib/zlib/zstream.js"; - -export default class Inflate { - constructor() { - this.strm = new ZStream(); - this.chunkSize = 1024 * 10 * 10; - this.strm.output = new Uint8Array(this.chunkSize); - this.windowBits = 5; - - inflateInit(this.strm, this.windowBits); - } - - inflate(data, flush, expected) { - this.strm.input = data; - this.strm.avail_in = this.strm.input.length; - this.strm.next_in = 0; - this.strm.next_out = 0; - - // resize our output buffer if it's too small - // (we could just use multiple chunks, but that would cause an extra - // allocation each time to flatten the chunks) - if (expected > this.chunkSize) { - this.chunkSize = expected; - this.strm.output = new Uint8Array(this.chunkSize); - } - - this.strm.avail_out = this.chunkSize; - - inflate(this.strm, flush); - - return new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); - } - - reset() { - inflateReset(this.strm); - } -} diff --git a/kasmweb/core/input/domkeytable.js b/kasmweb/core/input/domkeytable.js deleted file mode 100644 index 60ae3f9..0000000 --- a/kasmweb/core/input/domkeytable.js +++ /dev/null @@ -1,307 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -import KeyTable from "./keysym.js"; - -/* - * Mapping between HTML key values and VNC/X11 keysyms for "special" - * keys that cannot be handled via their Unicode codepoint. - * - * See https://www.w3.org/TR/uievents-key/ for possible values. - */ - -const DOMKeyTable = {}; - -function addStandard(key, standard) { - if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); - if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); - DOMKeyTable[key] = [standard, standard, standard, standard]; -} - -function addLeftRight(key, left, right) { - if (left === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); - if (right === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); - if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); - DOMKeyTable[key] = [left, left, right, left]; -} - -function addNumpad(key, standard, numpad) { - if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); - if (numpad === undefined) throw new Error("Undefined keysym for key \"" + key + "\""); - if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\""); - DOMKeyTable[key] = [standard, standard, standard, numpad]; -} - -// 2.2. Modifier Keys - -addLeftRight("Alt", KeyTable.XK_Alt_L, KeyTable.XK_Alt_R); -addStandard("AltGraph", KeyTable.XK_ISO_Level3_Shift); -addStandard("CapsLock", KeyTable.XK_Caps_Lock); -addLeftRight("Control", KeyTable.XK_Control_L, KeyTable.XK_Control_R); -// - Fn -// - FnLock -addLeftRight("Hyper", KeyTable.XK_Super_L, KeyTable.XK_Super_R); -addLeftRight("Meta", KeyTable.XK_Super_L, KeyTable.XK_Super_R); -addStandard("NumLock", KeyTable.XK_Num_Lock); -addStandard("ScrollLock", KeyTable.XK_Scroll_Lock); -addLeftRight("Shift", KeyTable.XK_Shift_L, KeyTable.XK_Shift_R); -addLeftRight("Super", KeyTable.XK_Super_L, KeyTable.XK_Super_R); -// - Symbol -// - SymbolLock - -// 2.3. Whitespace Keys - -addNumpad("Enter", KeyTable.XK_Return, KeyTable.XK_KP_Enter); -addStandard("Tab", KeyTable.XK_Tab); -addNumpad(" ", KeyTable.XK_space, KeyTable.XK_KP_Space); - -// 2.4. Navigation Keys - -addNumpad("ArrowDown", KeyTable.XK_Down, KeyTable.XK_KP_Down); -addNumpad("ArrowUp", KeyTable.XK_Up, KeyTable.XK_KP_Up); -addNumpad("ArrowLeft", KeyTable.XK_Left, KeyTable.XK_KP_Left); -addNumpad("ArrowRight", KeyTable.XK_Right, KeyTable.XK_KP_Right); -addNumpad("End", KeyTable.XK_End, KeyTable.XK_KP_End); -addNumpad("Home", KeyTable.XK_Home, KeyTable.XK_KP_Home); -addNumpad("PageDown", KeyTable.XK_Next, KeyTable.XK_KP_Next); -addNumpad("PageUp", KeyTable.XK_Prior, KeyTable.XK_KP_Prior); - -// 2.5. Editing Keys - -addStandard("Backspace", KeyTable.XK_BackSpace); -addNumpad("Clear", KeyTable.XK_Clear, KeyTable.XK_KP_Begin); -addStandard("Copy", KeyTable.XF86XK_Copy); -// - CrSel -addStandard("Cut", KeyTable.XF86XK_Cut); -addNumpad("Delete", KeyTable.XK_Delete, KeyTable.XK_KP_Delete); -// - EraseEof -// - ExSel -addNumpad("Insert", KeyTable.XK_Insert, KeyTable.XK_KP_Insert); -addStandard("Paste", KeyTable.XF86XK_Paste); -addStandard("Redo", KeyTable.XK_Redo); -addStandard("Undo", KeyTable.XK_Undo); - -// 2.6. UI Keys - -// - Accept -// - Again (could just be XK_Redo) -// - Attn -addStandard("Cancel", KeyTable.XK_Cancel); -addStandard("ContextMenu", KeyTable.XK_Menu); -addStandard("Escape", KeyTable.XK_Escape); -addStandard("Execute", KeyTable.XK_Execute); -addStandard("Find", KeyTable.XK_Find); -addStandard("Help", KeyTable.XK_Help); -addStandard("Pause", KeyTable.XK_Pause); -// - Play -// - Props -addStandard("Select", KeyTable.XK_Select); -addStandard("ZoomIn", KeyTable.XF86XK_ZoomIn); -addStandard("ZoomOut", KeyTable.XF86XK_ZoomOut); - -// 2.7. Device Keys - -addStandard("BrightnessDown", KeyTable.XF86XK_MonBrightnessDown); -addStandard("BrightnessUp", KeyTable.XF86XK_MonBrightnessUp); -addStandard("Eject", KeyTable.XF86XK_Eject); -addStandard("LogOff", KeyTable.XF86XK_LogOff); -addStandard("Power", KeyTable.XF86XK_PowerOff); -addStandard("PowerOff", KeyTable.XF86XK_PowerDown); -addStandard("PrintScreen", KeyTable.XK_Print); -addStandard("Hibernate", KeyTable.XF86XK_Hibernate); -addStandard("Standby", KeyTable.XF86XK_Standby); -addStandard("WakeUp", KeyTable.XF86XK_WakeUp); - -// 2.8. IME and Composition Keys - -addStandard("AllCandidates", KeyTable.XK_MultipleCandidate); -addStandard("Alphanumeric", KeyTable.XK_Eisu_Shift); // could also be _Eisu_Toggle -addStandard("CodeInput", KeyTable.XK_Codeinput); -addStandard("Compose", KeyTable.XK_Multi_key); -addStandard("Convert", KeyTable.XK_Henkan); -// - Dead -// - FinalMode -addStandard("GroupFirst", KeyTable.XK_ISO_First_Group); -addStandard("GroupLast", KeyTable.XK_ISO_Last_Group); -addStandard("GroupNext", KeyTable.XK_ISO_Next_Group); -addStandard("GroupPrevious", KeyTable.XK_ISO_Prev_Group); -// - ModeChange (XK_Mode_switch is often used for AltGr) -// - NextCandidate -addStandard("NonConvert", KeyTable.XK_Muhenkan); -addStandard("PreviousCandidate", KeyTable.XK_PreviousCandidate); -// - Process -addStandard("SingleCandidate", KeyTable.XK_SingleCandidate); -addStandard("HangulMode", KeyTable.XK_Hangul); -addStandard("HanjaMode", KeyTable.XK_Hangul_Hanja); -addStandard("JunjuaMode", KeyTable.XK_Hangul_Jeonja); -addStandard("Eisu", KeyTable.XK_Eisu_toggle); -addStandard("Hankaku", KeyTable.XK_Hankaku); -addStandard("Hiragana", KeyTable.XK_Hiragana); -addStandard("HiraganaKatakana", KeyTable.XK_Hiragana_Katakana); -addStandard("KanaMode", KeyTable.XK_Kana_Shift); // could also be _Kana_Lock -addStandard("KanjiMode", KeyTable.XK_Kanji); -addStandard("Katakana", KeyTable.XK_Katakana); -addStandard("Romaji", KeyTable.XK_Romaji); -addStandard("Zenkaku", KeyTable.XK_Zenkaku); -addStandard("ZenkakuHanaku", KeyTable.XK_Zenkaku_Hankaku); - -// 2.9. General-Purpose Function Keys - -addStandard("F1", KeyTable.XK_F1); -addStandard("F2", KeyTable.XK_F2); -addStandard("F3", KeyTable.XK_F3); -addStandard("F4", KeyTable.XK_F4); -addStandard("F5", KeyTable.XK_F5); -addStandard("F6", KeyTable.XK_F6); -addStandard("F7", KeyTable.XK_F7); -addStandard("F8", KeyTable.XK_F8); -addStandard("F9", KeyTable.XK_F9); -addStandard("F10", KeyTable.XK_F10); -addStandard("F11", KeyTable.XK_F11); -addStandard("F12", KeyTable.XK_F12); -addStandard("F13", KeyTable.XK_F13); -addStandard("F14", KeyTable.XK_F14); -addStandard("F15", KeyTable.XK_F15); -addStandard("F16", KeyTable.XK_F16); -addStandard("F17", KeyTable.XK_F17); -addStandard("F18", KeyTable.XK_F18); -addStandard("F19", KeyTable.XK_F19); -addStandard("F20", KeyTable.XK_F20); -addStandard("F21", KeyTable.XK_F21); -addStandard("F22", KeyTable.XK_F22); -addStandard("F23", KeyTable.XK_F23); -addStandard("F24", KeyTable.XK_F24); -addStandard("F25", KeyTable.XK_F25); -addStandard("F26", KeyTable.XK_F26); -addStandard("F27", KeyTable.XK_F27); -addStandard("F28", KeyTable.XK_F28); -addStandard("F29", KeyTable.XK_F29); -addStandard("F30", KeyTable.XK_F30); -addStandard("F31", KeyTable.XK_F31); -addStandard("F32", KeyTable.XK_F32); -addStandard("F33", KeyTable.XK_F33); -addStandard("F34", KeyTable.XK_F34); -addStandard("F35", KeyTable.XK_F35); -// - Soft1... - -// 2.10. Multimedia Keys - -// - ChannelDown -// - ChannelUp -addStandard("Close", KeyTable.XF86XK_Close); -addStandard("MailForward", KeyTable.XF86XK_MailForward); -addStandard("MailReply", KeyTable.XF86XK_Reply); -addStandard("MainSend", KeyTable.XF86XK_Send); -addStandard("MediaFastForward", KeyTable.XF86XK_AudioForward); -addStandard("MediaPause", KeyTable.XF86XK_AudioPause); -addStandard("MediaPlay", KeyTable.XF86XK_AudioPlay); -addStandard("MediaRecord", KeyTable.XF86XK_AudioRecord); -addStandard("MediaRewind", KeyTable.XF86XK_AudioRewind); -addStandard("MediaStop", KeyTable.XF86XK_AudioStop); -addStandard("MediaTrackNext", KeyTable.XF86XK_AudioNext); -addStandard("MediaTrackPrevious", KeyTable.XF86XK_AudioPrev); -addStandard("New", KeyTable.XF86XK_New); -addStandard("Open", KeyTable.XF86XK_Open); -addStandard("Print", KeyTable.XK_Print); -addStandard("Save", KeyTable.XF86XK_Save); -addStandard("SpellCheck", KeyTable.XF86XK_Spell); - -// 2.11. Multimedia Numpad Keys - -// - Key11 -// - Key12 - -// 2.12. Audio Keys - -// - AudioBalanceLeft -// - AudioBalanceRight -// - AudioBassDown -// - AudioBassBoostDown -// - AudioBassBoostToggle -// - AudioBassBoostUp -// - AudioBassUp -// - AudioFaderFront -// - AudioFaderRear -// - AudioSurroundModeNext -// - AudioTrebleDown -// - AudioTrebleUp -addStandard("AudioVolumeDown", KeyTable.XF86XK_AudioLowerVolume); -addStandard("AudioVolumeUp", KeyTable.XF86XK_AudioRaiseVolume); -addStandard("AudioVolumeMute", KeyTable.XF86XK_AudioMute); -// - MicrophoneToggle -// - MicrophoneVolumeDown -// - MicrophoneVolumeUp -addStandard("MicrophoneVolumeMute", KeyTable.XF86XK_AudioMicMute); - -// 2.13. Speech Keys - -// - SpeechCorrectionList -// - SpeechInputToggle - -// 2.14. Application Keys - -addStandard("LaunchCalculator", KeyTable.XF86XK_Calculator); -addStandard("LaunchCalendar", KeyTable.XF86XK_Calendar); -addStandard("LaunchMail", KeyTable.XF86XK_Mail); -addStandard("LaunchMediaPlayer", KeyTable.XF86XK_AudioMedia); -addStandard("LaunchMusicPlayer", KeyTable.XF86XK_Music); -addStandard("LaunchMyComputer", KeyTable.XF86XK_MyComputer); -addStandard("LaunchPhone", KeyTable.XF86XK_Phone); -addStandard("LaunchScreenSaver", KeyTable.XF86XK_ScreenSaver); -addStandard("LaunchSpreadsheet", KeyTable.XF86XK_Excel); -addStandard("LaunchWebBrowser", KeyTable.XF86XK_WWW); -addStandard("LaunchWebCam", KeyTable.XF86XK_WebCam); -addStandard("LaunchWordProcessor", KeyTable.XF86XK_Word); - -// 2.15. Browser Keys - -addStandard("BrowserBack", KeyTable.XF86XK_Back); -addStandard("BrowserFavorites", KeyTable.XF86XK_Favorites); -addStandard("BrowserForward", KeyTable.XF86XK_Forward); -addStandard("BrowserHome", KeyTable.XF86XK_HomePage); -addStandard("BrowserRefresh", KeyTable.XF86XK_Refresh); -addStandard("BrowserSearch", KeyTable.XF86XK_Search); -addStandard("BrowserStop", KeyTable.XF86XK_Stop); - -// 2.16. Mobile Phone Keys - -// - A whole bunch... - -// 2.17. TV Keys - -// - A whole bunch... - -// 2.18. Media Controller Keys - -// - A whole bunch... -addStandard("Dimmer", KeyTable.XF86XK_BrightnessAdjust); -addStandard("MediaAudioTrack", KeyTable.XF86XK_AudioCycleTrack); -addStandard("RandomToggle", KeyTable.XF86XK_AudioRandomPlay); -addStandard("SplitScreenToggle", KeyTable.XF86XK_SplitScreen); -addStandard("Subtitle", KeyTable.XF86XK_Subtitle); -addStandard("VideoModeNext", KeyTable.XF86XK_Next_VMode); - -// Extra: Numpad - -addNumpad("=", KeyTable.XK_equal, KeyTable.XK_KP_Equal); -addNumpad("+", KeyTable.XK_plus, KeyTable.XK_KP_Add); -addNumpad("-", KeyTable.XK_minus, KeyTable.XK_KP_Subtract); -addNumpad("*", KeyTable.XK_asterisk, KeyTable.XK_KP_Multiply); -addNumpad("/", KeyTable.XK_slash, KeyTable.XK_KP_Divide); -addNumpad(".", KeyTable.XK_period, KeyTable.XK_KP_Decimal); -addNumpad(",", KeyTable.XK_comma, KeyTable.XK_KP_Separator); -addNumpad("0", KeyTable.XK_0, KeyTable.XK_KP_0); -addNumpad("1", KeyTable.XK_1, KeyTable.XK_KP_1); -addNumpad("2", KeyTable.XK_2, KeyTable.XK_KP_2); -addNumpad("3", KeyTable.XK_3, KeyTable.XK_KP_3); -addNumpad("4", KeyTable.XK_4, KeyTable.XK_KP_4); -addNumpad("5", KeyTable.XK_5, KeyTable.XK_KP_5); -addNumpad("6", KeyTable.XK_6, KeyTable.XK_KP_6); -addNumpad("7", KeyTable.XK_7, KeyTable.XK_KP_7); -addNumpad("8", KeyTable.XK_8, KeyTable.XK_KP_8); -addNumpad("9", KeyTable.XK_9, KeyTable.XK_KP_9); - -export default DOMKeyTable; diff --git a/kasmweb/core/input/fixedkeys.js b/kasmweb/core/input/fixedkeys.js deleted file mode 100644 index 4d09f2f..0000000 --- a/kasmweb/core/input/fixedkeys.js +++ /dev/null @@ -1,129 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -/* - * Fallback mapping between HTML key codes (physical keys) and - * HTML key values. This only works for keys that don't vary - * between layouts. We also omit those who manage fine by mapping the - * Unicode representation. - * - * See https://www.w3.org/TR/uievents-code/ for possible codes. - * See https://www.w3.org/TR/uievents-key/ for possible values. - */ - -/* eslint-disable key-spacing */ - -export default { - -// 3.1.1.1. Writing System Keys - - 'Backspace': 'Backspace', - -// 3.1.1.2. Functional Keys - - 'AltLeft': 'Alt', - 'AltRight': 'Alt', // This could also be 'AltGraph' - 'CapsLock': 'CapsLock', - 'ContextMenu': 'ContextMenu', - 'ControlLeft': 'Control', - 'ControlRight': 'Control', - 'Enter': 'Enter', - 'MetaLeft': 'Meta', - 'MetaRight': 'Meta', - 'ShiftLeft': 'Shift', - 'ShiftRight': 'Shift', - 'Tab': 'Tab', - // FIXME: Japanese/Korean keys - -// 3.1.2. Control Pad Section - - 'Delete': 'Delete', - 'End': 'End', - 'Help': 'Help', - 'Home': 'Home', - 'Insert': 'Insert', - 'PageDown': 'PageDown', - 'PageUp': 'PageUp', - -// 3.1.3. Arrow Pad Section - - 'ArrowDown': 'ArrowDown', - 'ArrowLeft': 'ArrowLeft', - 'ArrowRight': 'ArrowRight', - 'ArrowUp': 'ArrowUp', - -// 3.1.4. Numpad Section - - 'NumLock': 'NumLock', - 'NumpadBackspace': 'Backspace', - 'NumpadClear': 'Clear', - -// 3.1.5. Function Section - - 'Escape': 'Escape', - 'F1': 'F1', - 'F2': 'F2', - 'F3': 'F3', - 'F4': 'F4', - 'F5': 'F5', - 'F6': 'F6', - 'F7': 'F7', - 'F8': 'F8', - 'F9': 'F9', - 'F10': 'F10', - 'F11': 'F11', - 'F12': 'F12', - 'F13': 'F13', - 'F14': 'F14', - 'F15': 'F15', - 'F16': 'F16', - 'F17': 'F17', - 'F18': 'F18', - 'F19': 'F19', - 'F20': 'F20', - 'F21': 'F21', - 'F22': 'F22', - 'F23': 'F23', - 'F24': 'F24', - 'F25': 'F25', - 'F26': 'F26', - 'F27': 'F27', - 'F28': 'F28', - 'F29': 'F29', - 'F30': 'F30', - 'F31': 'F31', - 'F32': 'F32', - 'F33': 'F33', - 'F34': 'F34', - 'F35': 'F35', - 'PrintScreen': 'PrintScreen', - 'ScrollLock': 'ScrollLock', - 'Pause': 'Pause', - -// 3.1.6. Media Keys - - 'BrowserBack': 'BrowserBack', - 'BrowserFavorites': 'BrowserFavorites', - 'BrowserForward': 'BrowserForward', - 'BrowserHome': 'BrowserHome', - 'BrowserRefresh': 'BrowserRefresh', - 'BrowserSearch': 'BrowserSearch', - 'BrowserStop': 'BrowserStop', - 'Eject': 'Eject', - 'LaunchApp1': 'LaunchMyComputer', - 'LaunchApp2': 'LaunchCalendar', - 'LaunchMail': 'LaunchMail', - 'MediaPlayPause': 'MediaPlay', - 'MediaStop': 'MediaStop', - 'MediaTrackNext': 'MediaTrackNext', - 'MediaTrackPrevious': 'MediaTrackPrevious', - 'Power': 'Power', - 'Sleep': 'Sleep', - 'AudioVolumeDown': 'AudioVolumeDown', - 'AudioVolumeMute': 'AudioVolumeMute', - 'AudioVolumeUp': 'AudioVolumeUp', - 'WakeUp': 'WakeUp', -}; diff --git a/kasmweb/core/input/keyboard.js b/kasmweb/core/input/keyboard.js deleted file mode 100644 index 9dbc8d6..0000000 --- a/kasmweb/core/input/keyboard.js +++ /dev/null @@ -1,370 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -import * as Log from '../util/logging.js'; -import { stopEvent } from '../util/events.js'; -import * as KeyboardUtil from "./util.js"; -import KeyTable from "./keysym.js"; -import * as browser from "../util/browser.js"; - -// -// Keyboard event handler -// - -export default class Keyboard { - constructor(target) { - this._target = target || null; - - this._keyDownList = {}; // List of depressed keys - // (even if they are happy) - this._pendingKey = null; // Key waiting for keypress - this._altGrArmed = false; // Windows AltGr detection - - // keep these here so we can refer to them later - this._eventHandlers = { - 'keyup': this._handleKeyUp.bind(this), - 'keydown': this._handleKeyDown.bind(this), - 'keypress': this._handleKeyPress.bind(this), - 'blur': this._allKeysUp.bind(this), - 'checkalt': this._checkAlt.bind(this), - }; - - // ===== EVENT HANDLERS ===== - - this.onkeyevent = () => {}; // Handler for key press/release - } - - // ===== PRIVATE METHODS ===== - - _sendKeyEvent(keysym, code, down) { - if (down) { - this._keyDownList[code] = keysym; - } else { - // Do we really think this key is down? - if (!(code in this._keyDownList)) { - return; - } - delete this._keyDownList[code]; - } - - Log.Debug("onkeyevent " + (down ? "down" : "up") + - ", keysym: " + keysym, ", code: " + code); - this.onkeyevent(keysym, code, down); - } - - _getKeyCode(e) { - const code = KeyboardUtil.getKeycode(e); - if (code !== 'Unidentified') { - return code; - } - - // Unstable, but we don't have anything else to go on - // (don't use it for 'keypress' events thought since - // WebKit sets it to the same as charCode) - if (e.keyCode && (e.type !== 'keypress')) { - // 229 is used for composition events - if (e.keyCode !== 229) { - return 'Platform' + e.keyCode; - } - } - - // A precursor to the final DOM3 standard. Unfortunately it - // is not layout independent, so it is as bad as using keyCode - if (e.keyIdentifier) { - // Non-character key? - if (e.keyIdentifier.substr(0, 2) !== 'U+') { - return e.keyIdentifier; - } - - const codepoint = parseInt(e.keyIdentifier.substr(2), 16); - const char = String.fromCharCode(codepoint).toUpperCase(); - - return 'Platform' + char.charCodeAt(); - } - - return 'Unidentified'; - } - - _handleKeyDown(e) { - const code = this._getKeyCode(e); - let keysym = KeyboardUtil.getKeysym(e); - - // Windows doesn't have a proper AltGr, but handles it using - // fake Ctrl+Alt. However the remote end might not be Windows, - // so we need to merge those in to a single AltGr event. We - // detect this case by seeing the two key events directly after - // each other with a very short time between them (<50ms). - if (this._altGrArmed) { - this._altGrArmed = false; - clearTimeout(this._altGrTimeout); - - if ((code === "AltRight") && - ((e.timeStamp - this._altGrCtrlTime) < 50)) { - // FIXME: We fail to detect this if either Ctrl key is - // first manually pressed as Windows then no - // longer sends the fake Ctrl down event. It - // does however happily send real Ctrl events - // even when AltGr is already down. Some - // browsers detect this for us though and set the - // key to "AltGraph". - keysym = KeyTable.XK_ISO_Level3_Shift; - } else { - this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); - } - } - - // We cannot handle keys we cannot track, but we also need - // to deal with virtual keyboards which omit key info - // (iOS omits tracking info on keyup events, which forces us to - // special treat that platform here) - if ((code === 'Unidentified') || browser.isIOS()) { - if (keysym) { - // If it's a virtual keyboard then it should be - // sufficient to just send press and release right - // after each other - this._sendKeyEvent(keysym, code, true); - this._sendKeyEvent(keysym, code, false); - } - - stopEvent(e); - return; - } - - // Alt behaves more like AltGraph on macOS, so shuffle the - // keys around a bit to make things more sane for the remote - // server. This method is used by RealVNC and TigerVNC (and - // possibly others). - if (browser.isMac()) { - switch (keysym) { - case KeyTable.XK_Super_L: - keysym = KeyTable.XK_Alt_L; - break; - case KeyTable.XK_Super_R: - keysym = KeyTable.XK_Super_L; - break; - case KeyTable.XK_Alt_L: - keysym = KeyTable.XK_Mode_switch; - break; - case KeyTable.XK_Alt_R: - keysym = KeyTable.XK_ISO_Level3_Shift; - break; - } - } - - // Is this key already pressed? If so, then we must use the - // same keysym or we'll confuse the server - if (code in this._keyDownList) { - keysym = this._keyDownList[code]; - } - - // macOS doesn't send proper key events for modifiers, only - // state change events. That gets extra confusing for CapsLock - // which toggles on each press, but not on release. So pretend - // it was a quick press and release of the button. - if (browser.isMac() && (code === 'CapsLock')) { - this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true); - this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false); - stopEvent(e); - return; - } - - // If this is a legacy browser then we'll need to wait for - // a keypress event as well - // (IE and Edge has a broken KeyboardEvent.key, so we can't - // just check for the presence of that field) - if (!keysym && (!e.key || browser.isIE() || browser.isEdge())) { - this._pendingKey = code; - // However we might not get a keypress event if the key - // is non-printable, which needs some special fallback - // handling - setTimeout(this._handleKeyPressTimeout.bind(this), 10, e); - return; - } - - this._pendingKey = null; - stopEvent(e); - - // Possible start of AltGr sequence? (see above) - if ((code === "ControlLeft") && browser.isWindows() && - !("ControlLeft" in this._keyDownList)) { - this._altGrArmed = true; - this._altGrTimeout = setTimeout(this._handleAltGrTimeout.bind(this), 100); - this._altGrCtrlTime = e.timeStamp; - return; - } - - this._sendKeyEvent(keysym, code, true); - } - - // Legacy event for browsers without code/key - _handleKeyPress(e) { - stopEvent(e); - - // Are we expecting a keypress? - if (this._pendingKey === null) { - return; - } - - let code = this._getKeyCode(e); - const keysym = KeyboardUtil.getKeysym(e); - - // The key we were waiting for? - if ((code !== 'Unidentified') && (code != this._pendingKey)) { - return; - } - - code = this._pendingKey; - this._pendingKey = null; - - if (!keysym) { - Log.Info('keypress with no keysym:', e); - return; - } - - this._sendKeyEvent(keysym, code, true); - } - - _handleKeyPressTimeout(e) { - // Did someone manage to sort out the key already? - if (this._pendingKey === null) { - return; - } - - let keysym; - - const code = this._pendingKey; - this._pendingKey = null; - - // We have no way of knowing the proper keysym with the - // information given, but the following are true for most - // layouts - if ((e.keyCode >= 0x30) && (e.keyCode <= 0x39)) { - // Digit - keysym = e.keyCode; - } else if ((e.keyCode >= 0x41) && (e.keyCode <= 0x5a)) { - // Character (A-Z) - let char = String.fromCharCode(e.keyCode); - // A feeble attempt at the correct case - if (e.shiftKey) { - char = char.toUpperCase(); - } else { - char = char.toLowerCase(); - } - keysym = char.charCodeAt(); - } else { - // Unknown, give up - keysym = 0; - } - - this._sendKeyEvent(keysym, code, true); - } - - _handleKeyUp(e) { - stopEvent(e); - - const code = this._getKeyCode(e); - - // We can't get a release in the middle of an AltGr sequence, so - // abort that detection - if (this._altGrArmed) { - this._altGrArmed = false; - clearTimeout(this._altGrTimeout); - this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); - } - - // See comment in _handleKeyDown() - if (browser.isMac() && (code === 'CapsLock')) { - this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true); - this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false); - return; - } - - this._sendKeyEvent(this._keyDownList[code], code, false); - } - - _handleAltGrTimeout() { - this._altGrArmed = false; - clearTimeout(this._altGrTimeout); - this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); - } - - _allKeysUp() { - Log.Debug(">> Keyboard.allKeysUp"); - for (let code in this._keyDownList) { - this._sendKeyEvent(this._keyDownList[code], code, false); - } - Log.Debug("<< Keyboard.allKeysUp"); - } - - // Firefox Alt workaround, see below - _checkAlt(e) { - if (e.altKey) { - return; - } - - const target = this._target; - const downList = this._keyDownList; - ['AltLeft', 'AltRight'].forEach((code) => { - if (!(code in downList)) { - return; - } - - const event = new KeyboardEvent('keyup', - { key: downList[code], - code: code }); - target.dispatchEvent(event); - }); - } - - // ===== PUBLIC METHODS ===== - - grab() { - //Log.Debug(">> Keyboard.grab"); - - this._target.addEventListener('keydown', this._eventHandlers.keydown); - this._target.addEventListener('keyup', this._eventHandlers.keyup); - this._target.addEventListener('keypress', this._eventHandlers.keypress); - - // Release (key up) if window loses focus - window.addEventListener('blur', this._eventHandlers.blur); - - // Firefox has broken handling of Alt, so we need to poll as - // best we can for releases (still doesn't prevent the menu - // from popping up though as we can't call preventDefault()) - if (browser.isWindows() && browser.isFirefox()) { - const handler = this._eventHandlers.checkalt; - ['mousedown', 'mouseup', 'mousemove', 'wheel', - 'touchstart', 'touchend', 'touchmove', - 'keydown', 'keyup'].forEach(type => - document.addEventListener(type, handler, - { capture: true, - passive: true })); - } - - //Log.Debug("<< Keyboard.grab"); - } - - ungrab() { - //Log.Debug(">> Keyboard.ungrab"); - - if (browser.isWindows() && browser.isFirefox()) { - const handler = this._eventHandlers.checkalt; - ['mousedown', 'mouseup', 'mousemove', 'wheel', - 'touchstart', 'touchend', 'touchmove', - 'keydown', 'keyup'].forEach(type => document.removeEventListener(type, handler)); - } - - this._target.removeEventListener('keydown', this._eventHandlers.keydown); - this._target.removeEventListener('keyup', this._eventHandlers.keyup); - this._target.removeEventListener('keypress', this._eventHandlers.keypress); - window.removeEventListener('blur', this._eventHandlers.blur); - - // Release (key up) all keys that are in a down state - this._allKeysUp(); - - //Log.Debug(">> Keyboard.ungrab"); - } -} diff --git a/kasmweb/core/input/keysym.js b/kasmweb/core/input/keysym.js deleted file mode 100644 index 22ba058..0000000 --- a/kasmweb/core/input/keysym.js +++ /dev/null @@ -1,616 +0,0 @@ -/* eslint-disable key-spacing */ - -export default { - XK_VoidSymbol: 0xffffff, /* Void symbol */ - - XK_BackSpace: 0xff08, /* Back space, back char */ - XK_Tab: 0xff09, - XK_Linefeed: 0xff0a, /* Linefeed, LF */ - XK_Clear: 0xff0b, - XK_Return: 0xff0d, /* Return, enter */ - XK_Pause: 0xff13, /* Pause, hold */ - XK_Scroll_Lock: 0xff14, - XK_Sys_Req: 0xff15, - XK_Escape: 0xff1b, - XK_Delete: 0xffff, /* Delete, rubout */ - - /* International & multi-key character composition */ - - XK_Multi_key: 0xff20, /* Multi-key character compose */ - XK_Codeinput: 0xff37, - XK_SingleCandidate: 0xff3c, - XK_MultipleCandidate: 0xff3d, - XK_PreviousCandidate: 0xff3e, - - /* Japanese keyboard support */ - - XK_Kanji: 0xff21, /* Kanji, Kanji convert */ - XK_Muhenkan: 0xff22, /* Cancel Conversion */ - XK_Henkan_Mode: 0xff23, /* Start/Stop Conversion */ - XK_Henkan: 0xff23, /* Alias for Henkan_Mode */ - XK_Romaji: 0xff24, /* to Romaji */ - XK_Hiragana: 0xff25, /* to Hiragana */ - XK_Katakana: 0xff26, /* to Katakana */ - XK_Hiragana_Katakana: 0xff27, /* Hiragana/Katakana toggle */ - XK_Zenkaku: 0xff28, /* to Zenkaku */ - XK_Hankaku: 0xff29, /* to Hankaku */ - XK_Zenkaku_Hankaku: 0xff2a, /* Zenkaku/Hankaku toggle */ - XK_Touroku: 0xff2b, /* Add to Dictionary */ - XK_Massyo: 0xff2c, /* Delete from Dictionary */ - XK_Kana_Lock: 0xff2d, /* Kana Lock */ - XK_Kana_Shift: 0xff2e, /* Kana Shift */ - XK_Eisu_Shift: 0xff2f, /* Alphanumeric Shift */ - XK_Eisu_toggle: 0xff30, /* Alphanumeric toggle */ - XK_Kanji_Bangou: 0xff37, /* Codeinput */ - XK_Zen_Koho: 0xff3d, /* Multiple/All Candidate(s) */ - XK_Mae_Koho: 0xff3e, /* Previous Candidate */ - - /* Cursor control & motion */ - - XK_Home: 0xff50, - XK_Left: 0xff51, /* Move left, left arrow */ - XK_Up: 0xff52, /* Move up, up arrow */ - XK_Right: 0xff53, /* Move right, right arrow */ - XK_Down: 0xff54, /* Move down, down arrow */ - XK_Prior: 0xff55, /* Prior, previous */ - XK_Page_Up: 0xff55, - XK_Next: 0xff56, /* Next */ - XK_Page_Down: 0xff56, - XK_End: 0xff57, /* EOL */ - XK_Begin: 0xff58, /* BOL */ - - - /* Misc functions */ - - XK_Select: 0xff60, /* Select, mark */ - XK_Print: 0xff61, - XK_Execute: 0xff62, /* Execute, run, do */ - XK_Insert: 0xff63, /* Insert, insert here */ - XK_Undo: 0xff65, - XK_Redo: 0xff66, /* Redo, again */ - XK_Menu: 0xff67, - XK_Find: 0xff68, /* Find, search */ - XK_Cancel: 0xff69, /* Cancel, stop, abort, exit */ - XK_Help: 0xff6a, /* Help */ - XK_Break: 0xff6b, - XK_Mode_switch: 0xff7e, /* Character set switch */ - XK_script_switch: 0xff7e, /* Alias for mode_switch */ - XK_Num_Lock: 0xff7f, - - /* Keypad functions, keypad numbers cleverly chosen to map to ASCII */ - - XK_KP_Space: 0xff80, /* Space */ - XK_KP_Tab: 0xff89, - XK_KP_Enter: 0xff8d, /* Enter */ - XK_KP_F1: 0xff91, /* PF1, KP_A, ... */ - XK_KP_F2: 0xff92, - XK_KP_F3: 0xff93, - XK_KP_F4: 0xff94, - XK_KP_Home: 0xff95, - XK_KP_Left: 0xff96, - XK_KP_Up: 0xff97, - XK_KP_Right: 0xff98, - XK_KP_Down: 0xff99, - XK_KP_Prior: 0xff9a, - XK_KP_Page_Up: 0xff9a, - XK_KP_Next: 0xff9b, - XK_KP_Page_Down: 0xff9b, - XK_KP_End: 0xff9c, - XK_KP_Begin: 0xff9d, - XK_KP_Insert: 0xff9e, - XK_KP_Delete: 0xff9f, - XK_KP_Equal: 0xffbd, /* Equals */ - XK_KP_Multiply: 0xffaa, - XK_KP_Add: 0xffab, - XK_KP_Separator: 0xffac, /* Separator, often comma */ - XK_KP_Subtract: 0xffad, - XK_KP_Decimal: 0xffae, - XK_KP_Divide: 0xffaf, - - XK_KP_0: 0xffb0, - XK_KP_1: 0xffb1, - XK_KP_2: 0xffb2, - XK_KP_3: 0xffb3, - XK_KP_4: 0xffb4, - XK_KP_5: 0xffb5, - XK_KP_6: 0xffb6, - XK_KP_7: 0xffb7, - XK_KP_8: 0xffb8, - XK_KP_9: 0xffb9, - - /* - * Auxiliary functions; note the duplicate definitions for left and right - * function keys; Sun keyboards and a few other manufacturers have such - * function key groups on the left and/or right sides of the keyboard. - * We've not found a keyboard with more than 35 function keys total. - */ - - XK_F1: 0xffbe, - XK_F2: 0xffbf, - XK_F3: 0xffc0, - XK_F4: 0xffc1, - XK_F5: 0xffc2, - XK_F6: 0xffc3, - XK_F7: 0xffc4, - XK_F8: 0xffc5, - XK_F9: 0xffc6, - XK_F10: 0xffc7, - XK_F11: 0xffc8, - XK_L1: 0xffc8, - XK_F12: 0xffc9, - XK_L2: 0xffc9, - XK_F13: 0xffca, - XK_L3: 0xffca, - XK_F14: 0xffcb, - XK_L4: 0xffcb, - XK_F15: 0xffcc, - XK_L5: 0xffcc, - XK_F16: 0xffcd, - XK_L6: 0xffcd, - XK_F17: 0xffce, - XK_L7: 0xffce, - XK_F18: 0xffcf, - XK_L8: 0xffcf, - XK_F19: 0xffd0, - XK_L9: 0xffd0, - XK_F20: 0xffd1, - XK_L10: 0xffd1, - XK_F21: 0xffd2, - XK_R1: 0xffd2, - XK_F22: 0xffd3, - XK_R2: 0xffd3, - XK_F23: 0xffd4, - XK_R3: 0xffd4, - XK_F24: 0xffd5, - XK_R4: 0xffd5, - XK_F25: 0xffd6, - XK_R5: 0xffd6, - XK_F26: 0xffd7, - XK_R6: 0xffd7, - XK_F27: 0xffd8, - XK_R7: 0xffd8, - XK_F28: 0xffd9, - XK_R8: 0xffd9, - XK_F29: 0xffda, - XK_R9: 0xffda, - XK_F30: 0xffdb, - XK_R10: 0xffdb, - XK_F31: 0xffdc, - XK_R11: 0xffdc, - XK_F32: 0xffdd, - XK_R12: 0xffdd, - XK_F33: 0xffde, - XK_R13: 0xffde, - XK_F34: 0xffdf, - XK_R14: 0xffdf, - XK_F35: 0xffe0, - XK_R15: 0xffe0, - - /* Modifiers */ - - XK_Shift_L: 0xffe1, /* Left shift */ - XK_Shift_R: 0xffe2, /* Right shift */ - XK_Control_L: 0xffe3, /* Left control */ - XK_Control_R: 0xffe4, /* Right control */ - XK_Caps_Lock: 0xffe5, /* Caps lock */ - XK_Shift_Lock: 0xffe6, /* Shift lock */ - - XK_Meta_L: 0xffe7, /* Left meta */ - XK_Meta_R: 0xffe8, /* Right meta */ - XK_Alt_L: 0xffe9, /* Left alt */ - XK_Alt_R: 0xffea, /* Right alt */ - XK_Super_L: 0xffeb, /* Left super */ - XK_Super_R: 0xffec, /* Right super */ - XK_Hyper_L: 0xffed, /* Left hyper */ - XK_Hyper_R: 0xffee, /* Right hyper */ - - /* - * Keyboard (XKB) Extension function and modifier keys - * (from Appendix C of "The X Keyboard Extension: Protocol Specification") - * Byte 3 = 0xfe - */ - - XK_ISO_Level3_Shift: 0xfe03, /* AltGr */ - XK_ISO_Next_Group: 0xfe08, - XK_ISO_Prev_Group: 0xfe0a, - XK_ISO_First_Group: 0xfe0c, - XK_ISO_Last_Group: 0xfe0e, - - /* - * Latin 1 - * (ISO/IEC 8859-1: Unicode U+0020..U+00FF) - * Byte 3: 0 - */ - - XK_space: 0x0020, /* U+0020 SPACE */ - XK_exclam: 0x0021, /* U+0021 EXCLAMATION MARK */ - XK_quotedbl: 0x0022, /* U+0022 QUOTATION MARK */ - XK_numbersign: 0x0023, /* U+0023 NUMBER SIGN */ - XK_dollar: 0x0024, /* U+0024 DOLLAR SIGN */ - XK_percent: 0x0025, /* U+0025 PERCENT SIGN */ - XK_ampersand: 0x0026, /* U+0026 AMPERSAND */ - XK_apostrophe: 0x0027, /* U+0027 APOSTROPHE */ - XK_quoteright: 0x0027, /* deprecated */ - XK_parenleft: 0x0028, /* U+0028 LEFT PARENTHESIS */ - XK_parenright: 0x0029, /* U+0029 RIGHT PARENTHESIS */ - XK_asterisk: 0x002a, /* U+002A ASTERISK */ - XK_plus: 0x002b, /* U+002B PLUS SIGN */ - XK_comma: 0x002c, /* U+002C COMMA */ - XK_minus: 0x002d, /* U+002D HYPHEN-MINUS */ - XK_period: 0x002e, /* U+002E FULL STOP */ - XK_slash: 0x002f, /* U+002F SOLIDUS */ - XK_0: 0x0030, /* U+0030 DIGIT ZERO */ - XK_1: 0x0031, /* U+0031 DIGIT ONE */ - XK_2: 0x0032, /* U+0032 DIGIT TWO */ - XK_3: 0x0033, /* U+0033 DIGIT THREE */ - XK_4: 0x0034, /* U+0034 DIGIT FOUR */ - XK_5: 0x0035, /* U+0035 DIGIT FIVE */ - XK_6: 0x0036, /* U+0036 DIGIT SIX */ - XK_7: 0x0037, /* U+0037 DIGIT SEVEN */ - XK_8: 0x0038, /* U+0038 DIGIT EIGHT */ - XK_9: 0x0039, /* U+0039 DIGIT NINE */ - XK_colon: 0x003a, /* U+003A COLON */ - XK_semicolon: 0x003b, /* U+003B SEMICOLON */ - XK_less: 0x003c, /* U+003C LESS-THAN SIGN */ - XK_equal: 0x003d, /* U+003D EQUALS SIGN */ - XK_greater: 0x003e, /* U+003E GREATER-THAN SIGN */ - XK_question: 0x003f, /* U+003F QUESTION MARK */ - XK_at: 0x0040, /* U+0040 COMMERCIAL AT */ - XK_A: 0x0041, /* U+0041 LATIN CAPITAL LETTER A */ - XK_B: 0x0042, /* U+0042 LATIN CAPITAL LETTER B */ - XK_C: 0x0043, /* U+0043 LATIN CAPITAL LETTER C */ - XK_D: 0x0044, /* U+0044 LATIN CAPITAL LETTER D */ - XK_E: 0x0045, /* U+0045 LATIN CAPITAL LETTER E */ - XK_F: 0x0046, /* U+0046 LATIN CAPITAL LETTER F */ - XK_G: 0x0047, /* U+0047 LATIN CAPITAL LETTER G */ - XK_H: 0x0048, /* U+0048 LATIN CAPITAL LETTER H */ - XK_I: 0x0049, /* U+0049 LATIN CAPITAL LETTER I */ - XK_J: 0x004a, /* U+004A LATIN CAPITAL LETTER J */ - XK_K: 0x004b, /* U+004B LATIN CAPITAL LETTER K */ - XK_L: 0x004c, /* U+004C LATIN CAPITAL LETTER L */ - XK_M: 0x004d, /* U+004D LATIN CAPITAL LETTER M */ - XK_N: 0x004e, /* U+004E LATIN CAPITAL LETTER N */ - XK_O: 0x004f, /* U+004F LATIN CAPITAL LETTER O */ - XK_P: 0x0050, /* U+0050 LATIN CAPITAL LETTER P */ - XK_Q: 0x0051, /* U+0051 LATIN CAPITAL LETTER Q */ - XK_R: 0x0052, /* U+0052 LATIN CAPITAL LETTER R */ - XK_S: 0x0053, /* U+0053 LATIN CAPITAL LETTER S */ - XK_T: 0x0054, /* U+0054 LATIN CAPITAL LETTER T */ - XK_U: 0x0055, /* U+0055 LATIN CAPITAL LETTER U */ - XK_V: 0x0056, /* U+0056 LATIN CAPITAL LETTER V */ - XK_W: 0x0057, /* U+0057 LATIN CAPITAL LETTER W */ - XK_X: 0x0058, /* U+0058 LATIN CAPITAL LETTER X */ - XK_Y: 0x0059, /* U+0059 LATIN CAPITAL LETTER Y */ - XK_Z: 0x005a, /* U+005A LATIN CAPITAL LETTER Z */ - XK_bracketleft: 0x005b, /* U+005B LEFT SQUARE BRACKET */ - XK_backslash: 0x005c, /* U+005C REVERSE SOLIDUS */ - XK_bracketright: 0x005d, /* U+005D RIGHT SQUARE BRACKET */ - XK_asciicircum: 0x005e, /* U+005E CIRCUMFLEX ACCENT */ - XK_underscore: 0x005f, /* U+005F LOW LINE */ - XK_grave: 0x0060, /* U+0060 GRAVE ACCENT */ - XK_quoteleft: 0x0060, /* deprecated */ - XK_a: 0x0061, /* U+0061 LATIN SMALL LETTER A */ - XK_b: 0x0062, /* U+0062 LATIN SMALL LETTER B */ - XK_c: 0x0063, /* U+0063 LATIN SMALL LETTER C */ - XK_d: 0x0064, /* U+0064 LATIN SMALL LETTER D */ - XK_e: 0x0065, /* U+0065 LATIN SMALL LETTER E */ - XK_f: 0x0066, /* U+0066 LATIN SMALL LETTER F */ - XK_g: 0x0067, /* U+0067 LATIN SMALL LETTER G */ - XK_h: 0x0068, /* U+0068 LATIN SMALL LETTER H */ - XK_i: 0x0069, /* U+0069 LATIN SMALL LETTER I */ - XK_j: 0x006a, /* U+006A LATIN SMALL LETTER J */ - XK_k: 0x006b, /* U+006B LATIN SMALL LETTER K */ - XK_l: 0x006c, /* U+006C LATIN SMALL LETTER L */ - XK_m: 0x006d, /* U+006D LATIN SMALL LETTER M */ - XK_n: 0x006e, /* U+006E LATIN SMALL LETTER N */ - XK_o: 0x006f, /* U+006F LATIN SMALL LETTER O */ - XK_p: 0x0070, /* U+0070 LATIN SMALL LETTER P */ - XK_q: 0x0071, /* U+0071 LATIN SMALL LETTER Q */ - XK_r: 0x0072, /* U+0072 LATIN SMALL LETTER R */ - XK_s: 0x0073, /* U+0073 LATIN SMALL LETTER S */ - XK_t: 0x0074, /* U+0074 LATIN SMALL LETTER T */ - XK_u: 0x0075, /* U+0075 LATIN SMALL LETTER U */ - XK_v: 0x0076, /* U+0076 LATIN SMALL LETTER V */ - XK_w: 0x0077, /* U+0077 LATIN SMALL LETTER W */ - XK_x: 0x0078, /* U+0078 LATIN SMALL LETTER X */ - XK_y: 0x0079, /* U+0079 LATIN SMALL LETTER Y */ - XK_z: 0x007a, /* U+007A LATIN SMALL LETTER Z */ - XK_braceleft: 0x007b, /* U+007B LEFT CURLY BRACKET */ - XK_bar: 0x007c, /* U+007C VERTICAL LINE */ - XK_braceright: 0x007d, /* U+007D RIGHT CURLY BRACKET */ - XK_asciitilde: 0x007e, /* U+007E TILDE */ - - XK_nobreakspace: 0x00a0, /* U+00A0 NO-BREAK SPACE */ - XK_exclamdown: 0x00a1, /* U+00A1 INVERTED EXCLAMATION MARK */ - XK_cent: 0x00a2, /* U+00A2 CENT SIGN */ - XK_sterling: 0x00a3, /* U+00A3 POUND SIGN */ - XK_currency: 0x00a4, /* U+00A4 CURRENCY SIGN */ - XK_yen: 0x00a5, /* U+00A5 YEN SIGN */ - XK_brokenbar: 0x00a6, /* U+00A6 BROKEN BAR */ - XK_section: 0x00a7, /* U+00A7 SECTION SIGN */ - XK_diaeresis: 0x00a8, /* U+00A8 DIAERESIS */ - XK_copyright: 0x00a9, /* U+00A9 COPYRIGHT SIGN */ - XK_ordfeminine: 0x00aa, /* U+00AA FEMININE ORDINAL INDICATOR */ - XK_guillemotleft: 0x00ab, /* U+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */ - XK_notsign: 0x00ac, /* U+00AC NOT SIGN */ - XK_hyphen: 0x00ad, /* U+00AD SOFT HYPHEN */ - XK_registered: 0x00ae, /* U+00AE REGISTERED SIGN */ - XK_macron: 0x00af, /* U+00AF MACRON */ - XK_degree: 0x00b0, /* U+00B0 DEGREE SIGN */ - XK_plusminus: 0x00b1, /* U+00B1 PLUS-MINUS SIGN */ - XK_twosuperior: 0x00b2, /* U+00B2 SUPERSCRIPT TWO */ - XK_threesuperior: 0x00b3, /* U+00B3 SUPERSCRIPT THREE */ - XK_acute: 0x00b4, /* U+00B4 ACUTE ACCENT */ - XK_mu: 0x00b5, /* U+00B5 MICRO SIGN */ - XK_paragraph: 0x00b6, /* U+00B6 PILCROW SIGN */ - XK_periodcentered: 0x00b7, /* U+00B7 MIDDLE DOT */ - XK_cedilla: 0x00b8, /* U+00B8 CEDILLA */ - XK_onesuperior: 0x00b9, /* U+00B9 SUPERSCRIPT ONE */ - XK_masculine: 0x00ba, /* U+00BA MASCULINE ORDINAL INDICATOR */ - XK_guillemotright: 0x00bb, /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */ - XK_onequarter: 0x00bc, /* U+00BC VULGAR FRACTION ONE QUARTER */ - XK_onehalf: 0x00bd, /* U+00BD VULGAR FRACTION ONE HALF */ - XK_threequarters: 0x00be, /* U+00BE VULGAR FRACTION THREE QUARTERS */ - XK_questiondown: 0x00bf, /* U+00BF INVERTED QUESTION MARK */ - XK_Agrave: 0x00c0, /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */ - XK_Aacute: 0x00c1, /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */ - XK_Acircumflex: 0x00c2, /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */ - XK_Atilde: 0x00c3, /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */ - XK_Adiaeresis: 0x00c4, /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS */ - XK_Aring: 0x00c5, /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */ - XK_AE: 0x00c6, /* U+00C6 LATIN CAPITAL LETTER AE */ - XK_Ccedilla: 0x00c7, /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */ - XK_Egrave: 0x00c8, /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */ - XK_Eacute: 0x00c9, /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */ - XK_Ecircumflex: 0x00ca, /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */ - XK_Ediaeresis: 0x00cb, /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS */ - XK_Igrave: 0x00cc, /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */ - XK_Iacute: 0x00cd, /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */ - XK_Icircumflex: 0x00ce, /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */ - XK_Idiaeresis: 0x00cf, /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS */ - XK_ETH: 0x00d0, /* U+00D0 LATIN CAPITAL LETTER ETH */ - XK_Eth: 0x00d0, /* deprecated */ - XK_Ntilde: 0x00d1, /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */ - XK_Ograve: 0x00d2, /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */ - XK_Oacute: 0x00d3, /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */ - XK_Ocircumflex: 0x00d4, /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */ - XK_Otilde: 0x00d5, /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */ - XK_Odiaeresis: 0x00d6, /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS */ - XK_multiply: 0x00d7, /* U+00D7 MULTIPLICATION SIGN */ - XK_Oslash: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ - XK_Ooblique: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ - XK_Ugrave: 0x00d9, /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */ - XK_Uacute: 0x00da, /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */ - XK_Ucircumflex: 0x00db, /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */ - XK_Udiaeresis: 0x00dc, /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS */ - XK_Yacute: 0x00dd, /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */ - XK_THORN: 0x00de, /* U+00DE LATIN CAPITAL LETTER THORN */ - XK_Thorn: 0x00de, /* deprecated */ - XK_ssharp: 0x00df, /* U+00DF LATIN SMALL LETTER SHARP S */ - XK_agrave: 0x00e0, /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */ - XK_aacute: 0x00e1, /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */ - XK_acircumflex: 0x00e2, /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX */ - XK_atilde: 0x00e3, /* U+00E3 LATIN SMALL LETTER A WITH TILDE */ - XK_adiaeresis: 0x00e4, /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */ - XK_aring: 0x00e5, /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */ - XK_ae: 0x00e6, /* U+00E6 LATIN SMALL LETTER AE */ - XK_ccedilla: 0x00e7, /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */ - XK_egrave: 0x00e8, /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */ - XK_eacute: 0x00e9, /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */ - XK_ecircumflex: 0x00ea, /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX */ - XK_ediaeresis: 0x00eb, /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */ - XK_igrave: 0x00ec, /* U+00EC LATIN SMALL LETTER I WITH GRAVE */ - XK_iacute: 0x00ed, /* U+00ED LATIN SMALL LETTER I WITH ACUTE */ - XK_icircumflex: 0x00ee, /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX */ - XK_idiaeresis: 0x00ef, /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */ - XK_eth: 0x00f0, /* U+00F0 LATIN SMALL LETTER ETH */ - XK_ntilde: 0x00f1, /* U+00F1 LATIN SMALL LETTER N WITH TILDE */ - XK_ograve: 0x00f2, /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */ - XK_oacute: 0x00f3, /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */ - XK_ocircumflex: 0x00f4, /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX */ - XK_otilde: 0x00f5, /* U+00F5 LATIN SMALL LETTER O WITH TILDE */ - XK_odiaeresis: 0x00f6, /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */ - XK_division: 0x00f7, /* U+00F7 DIVISION SIGN */ - XK_oslash: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ - XK_ooblique: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ - XK_ugrave: 0x00f9, /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */ - XK_uacute: 0x00fa, /* U+00FA LATIN SMALL LETTER U WITH ACUTE */ - XK_ucircumflex: 0x00fb, /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX */ - XK_udiaeresis: 0x00fc, /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */ - XK_yacute: 0x00fd, /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */ - XK_thorn: 0x00fe, /* U+00FE LATIN SMALL LETTER THORN */ - XK_ydiaeresis: 0x00ff, /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */ - - /* - * Korean - * Byte 3 = 0x0e - */ - - XK_Hangul: 0xff31, /* Hangul start/stop(toggle) */ - XK_Hangul_Hanja: 0xff34, /* Start Hangul->Hanja Conversion */ - XK_Hangul_Jeonja: 0xff38, /* Jeonja mode */ - - /* - * XFree86 vendor specific keysyms. - * - * The XFree86 keysym range is 0x10080001 - 0x1008FFFF. - */ - - XF86XK_ModeLock: 0x1008FF01, - XF86XK_MonBrightnessUp: 0x1008FF02, - XF86XK_MonBrightnessDown: 0x1008FF03, - XF86XK_KbdLightOnOff: 0x1008FF04, - XF86XK_KbdBrightnessUp: 0x1008FF05, - XF86XK_KbdBrightnessDown: 0x1008FF06, - XF86XK_Standby: 0x1008FF10, - XF86XK_AudioLowerVolume: 0x1008FF11, - XF86XK_AudioMute: 0x1008FF12, - XF86XK_AudioRaiseVolume: 0x1008FF13, - XF86XK_AudioPlay: 0x1008FF14, - XF86XK_AudioStop: 0x1008FF15, - XF86XK_AudioPrev: 0x1008FF16, - XF86XK_AudioNext: 0x1008FF17, - XF86XK_HomePage: 0x1008FF18, - XF86XK_Mail: 0x1008FF19, - XF86XK_Start: 0x1008FF1A, - XF86XK_Search: 0x1008FF1B, - XF86XK_AudioRecord: 0x1008FF1C, - XF86XK_Calculator: 0x1008FF1D, - XF86XK_Memo: 0x1008FF1E, - XF86XK_ToDoList: 0x1008FF1F, - XF86XK_Calendar: 0x1008FF20, - XF86XK_PowerDown: 0x1008FF21, - XF86XK_ContrastAdjust: 0x1008FF22, - XF86XK_RockerUp: 0x1008FF23, - XF86XK_RockerDown: 0x1008FF24, - XF86XK_RockerEnter: 0x1008FF25, - XF86XK_Back: 0x1008FF26, - XF86XK_Forward: 0x1008FF27, - XF86XK_Stop: 0x1008FF28, - XF86XK_Refresh: 0x1008FF29, - XF86XK_PowerOff: 0x1008FF2A, - XF86XK_WakeUp: 0x1008FF2B, - XF86XK_Eject: 0x1008FF2C, - XF86XK_ScreenSaver: 0x1008FF2D, - XF86XK_WWW: 0x1008FF2E, - XF86XK_Sleep: 0x1008FF2F, - XF86XK_Favorites: 0x1008FF30, - XF86XK_AudioPause: 0x1008FF31, - XF86XK_AudioMedia: 0x1008FF32, - XF86XK_MyComputer: 0x1008FF33, - XF86XK_VendorHome: 0x1008FF34, - XF86XK_LightBulb: 0x1008FF35, - XF86XK_Shop: 0x1008FF36, - XF86XK_History: 0x1008FF37, - XF86XK_OpenURL: 0x1008FF38, - XF86XK_AddFavorite: 0x1008FF39, - XF86XK_HotLinks: 0x1008FF3A, - XF86XK_BrightnessAdjust: 0x1008FF3B, - XF86XK_Finance: 0x1008FF3C, - XF86XK_Community: 0x1008FF3D, - XF86XK_AudioRewind: 0x1008FF3E, - XF86XK_BackForward: 0x1008FF3F, - XF86XK_Launch0: 0x1008FF40, - XF86XK_Launch1: 0x1008FF41, - XF86XK_Launch2: 0x1008FF42, - XF86XK_Launch3: 0x1008FF43, - XF86XK_Launch4: 0x1008FF44, - XF86XK_Launch5: 0x1008FF45, - XF86XK_Launch6: 0x1008FF46, - XF86XK_Launch7: 0x1008FF47, - XF86XK_Launch8: 0x1008FF48, - XF86XK_Launch9: 0x1008FF49, - XF86XK_LaunchA: 0x1008FF4A, - XF86XK_LaunchB: 0x1008FF4B, - XF86XK_LaunchC: 0x1008FF4C, - XF86XK_LaunchD: 0x1008FF4D, - XF86XK_LaunchE: 0x1008FF4E, - XF86XK_LaunchF: 0x1008FF4F, - XF86XK_ApplicationLeft: 0x1008FF50, - XF86XK_ApplicationRight: 0x1008FF51, - XF86XK_Book: 0x1008FF52, - XF86XK_CD: 0x1008FF53, - XF86XK_Calculater: 0x1008FF54, - XF86XK_Clear: 0x1008FF55, - XF86XK_Close: 0x1008FF56, - XF86XK_Copy: 0x1008FF57, - XF86XK_Cut: 0x1008FF58, - XF86XK_Display: 0x1008FF59, - XF86XK_DOS: 0x1008FF5A, - XF86XK_Documents: 0x1008FF5B, - XF86XK_Excel: 0x1008FF5C, - XF86XK_Explorer: 0x1008FF5D, - XF86XK_Game: 0x1008FF5E, - XF86XK_Go: 0x1008FF5F, - XF86XK_iTouch: 0x1008FF60, - XF86XK_LogOff: 0x1008FF61, - XF86XK_Market: 0x1008FF62, - XF86XK_Meeting: 0x1008FF63, - XF86XK_MenuKB: 0x1008FF65, - XF86XK_MenuPB: 0x1008FF66, - XF86XK_MySites: 0x1008FF67, - XF86XK_New: 0x1008FF68, - XF86XK_News: 0x1008FF69, - XF86XK_OfficeHome: 0x1008FF6A, - XF86XK_Open: 0x1008FF6B, - XF86XK_Option: 0x1008FF6C, - XF86XK_Paste: 0x1008FF6D, - XF86XK_Phone: 0x1008FF6E, - XF86XK_Q: 0x1008FF70, - XF86XK_Reply: 0x1008FF72, - XF86XK_Reload: 0x1008FF73, - XF86XK_RotateWindows: 0x1008FF74, - XF86XK_RotationPB: 0x1008FF75, - XF86XK_RotationKB: 0x1008FF76, - XF86XK_Save: 0x1008FF77, - XF86XK_ScrollUp: 0x1008FF78, - XF86XK_ScrollDown: 0x1008FF79, - XF86XK_ScrollClick: 0x1008FF7A, - XF86XK_Send: 0x1008FF7B, - XF86XK_Spell: 0x1008FF7C, - XF86XK_SplitScreen: 0x1008FF7D, - XF86XK_Support: 0x1008FF7E, - XF86XK_TaskPane: 0x1008FF7F, - XF86XK_Terminal: 0x1008FF80, - XF86XK_Tools: 0x1008FF81, - XF86XK_Travel: 0x1008FF82, - XF86XK_UserPB: 0x1008FF84, - XF86XK_User1KB: 0x1008FF85, - XF86XK_User2KB: 0x1008FF86, - XF86XK_Video: 0x1008FF87, - XF86XK_WheelButton: 0x1008FF88, - XF86XK_Word: 0x1008FF89, - XF86XK_Xfer: 0x1008FF8A, - XF86XK_ZoomIn: 0x1008FF8B, - XF86XK_ZoomOut: 0x1008FF8C, - XF86XK_Away: 0x1008FF8D, - XF86XK_Messenger: 0x1008FF8E, - XF86XK_WebCam: 0x1008FF8F, - XF86XK_MailForward: 0x1008FF90, - XF86XK_Pictures: 0x1008FF91, - XF86XK_Music: 0x1008FF92, - XF86XK_Battery: 0x1008FF93, - XF86XK_Bluetooth: 0x1008FF94, - XF86XK_WLAN: 0x1008FF95, - XF86XK_UWB: 0x1008FF96, - XF86XK_AudioForward: 0x1008FF97, - XF86XK_AudioRepeat: 0x1008FF98, - XF86XK_AudioRandomPlay: 0x1008FF99, - XF86XK_Subtitle: 0x1008FF9A, - XF86XK_AudioCycleTrack: 0x1008FF9B, - XF86XK_CycleAngle: 0x1008FF9C, - XF86XK_FrameBack: 0x1008FF9D, - XF86XK_FrameForward: 0x1008FF9E, - XF86XK_Time: 0x1008FF9F, - XF86XK_Select: 0x1008FFA0, - XF86XK_View: 0x1008FFA1, - XF86XK_TopMenu: 0x1008FFA2, - XF86XK_Red: 0x1008FFA3, - XF86XK_Green: 0x1008FFA4, - XF86XK_Yellow: 0x1008FFA5, - XF86XK_Blue: 0x1008FFA6, - XF86XK_Suspend: 0x1008FFA7, - XF86XK_Hibernate: 0x1008FFA8, - XF86XK_TouchpadToggle: 0x1008FFA9, - XF86XK_TouchpadOn: 0x1008FFB0, - XF86XK_TouchpadOff: 0x1008FFB1, - XF86XK_AudioMicMute: 0x1008FFB2, - XF86XK_Switch_VT_1: 0x1008FE01, - XF86XK_Switch_VT_2: 0x1008FE02, - XF86XK_Switch_VT_3: 0x1008FE03, - XF86XK_Switch_VT_4: 0x1008FE04, - XF86XK_Switch_VT_5: 0x1008FE05, - XF86XK_Switch_VT_6: 0x1008FE06, - XF86XK_Switch_VT_7: 0x1008FE07, - XF86XK_Switch_VT_8: 0x1008FE08, - XF86XK_Switch_VT_9: 0x1008FE09, - XF86XK_Switch_VT_10: 0x1008FE0A, - XF86XK_Switch_VT_11: 0x1008FE0B, - XF86XK_Switch_VT_12: 0x1008FE0C, - XF86XK_Ungrab: 0x1008FE20, - XF86XK_ClearGrab: 0x1008FE21, - XF86XK_Next_VMode: 0x1008FE22, - XF86XK_Prev_VMode: 0x1008FE23, - XF86XK_LogWindowTree: 0x1008FE24, - XF86XK_LogGrabInfo: 0x1008FE25, -}; diff --git a/kasmweb/core/input/keysymdef.js b/kasmweb/core/input/keysymdef.js deleted file mode 100644 index 951caca..0000000 --- a/kasmweb/core/input/keysymdef.js +++ /dev/null @@ -1,688 +0,0 @@ -/* - * Mapping from Unicode codepoints to X11/RFB keysyms - * - * This file was automatically generated from keysymdef.h - * DO NOT EDIT! - */ - -/* Functions at the bottom */ - -const codepoints = { - 0x0100: 0x03c0, // XK_Amacron - 0x0101: 0x03e0, // XK_amacron - 0x0102: 0x01c3, // XK_Abreve - 0x0103: 0x01e3, // XK_abreve - 0x0104: 0x01a1, // XK_Aogonek - 0x0105: 0x01b1, // XK_aogonek - 0x0106: 0x01c6, // XK_Cacute - 0x0107: 0x01e6, // XK_cacute - 0x0108: 0x02c6, // XK_Ccircumflex - 0x0109: 0x02e6, // XK_ccircumflex - 0x010a: 0x02c5, // XK_Cabovedot - 0x010b: 0x02e5, // XK_cabovedot - 0x010c: 0x01c8, // XK_Ccaron - 0x010d: 0x01e8, // XK_ccaron - 0x010e: 0x01cf, // XK_Dcaron - 0x010f: 0x01ef, // XK_dcaron - 0x0110: 0x01d0, // XK_Dstroke - 0x0111: 0x01f0, // XK_dstroke - 0x0112: 0x03aa, // XK_Emacron - 0x0113: 0x03ba, // XK_emacron - 0x0116: 0x03cc, // XK_Eabovedot - 0x0117: 0x03ec, // XK_eabovedot - 0x0118: 0x01ca, // XK_Eogonek - 0x0119: 0x01ea, // XK_eogonek - 0x011a: 0x01cc, // XK_Ecaron - 0x011b: 0x01ec, // XK_ecaron - 0x011c: 0x02d8, // XK_Gcircumflex - 0x011d: 0x02f8, // XK_gcircumflex - 0x011e: 0x02ab, // XK_Gbreve - 0x011f: 0x02bb, // XK_gbreve - 0x0120: 0x02d5, // XK_Gabovedot - 0x0121: 0x02f5, // XK_gabovedot - 0x0122: 0x03ab, // XK_Gcedilla - 0x0123: 0x03bb, // XK_gcedilla - 0x0124: 0x02a6, // XK_Hcircumflex - 0x0125: 0x02b6, // XK_hcircumflex - 0x0126: 0x02a1, // XK_Hstroke - 0x0127: 0x02b1, // XK_hstroke - 0x0128: 0x03a5, // XK_Itilde - 0x0129: 0x03b5, // XK_itilde - 0x012a: 0x03cf, // XK_Imacron - 0x012b: 0x03ef, // XK_imacron - 0x012e: 0x03c7, // XK_Iogonek - 0x012f: 0x03e7, // XK_iogonek - 0x0130: 0x02a9, // XK_Iabovedot - 0x0131: 0x02b9, // XK_idotless - 0x0134: 0x02ac, // XK_Jcircumflex - 0x0135: 0x02bc, // XK_jcircumflex - 0x0136: 0x03d3, // XK_Kcedilla - 0x0137: 0x03f3, // XK_kcedilla - 0x0138: 0x03a2, // XK_kra - 0x0139: 0x01c5, // XK_Lacute - 0x013a: 0x01e5, // XK_lacute - 0x013b: 0x03a6, // XK_Lcedilla - 0x013c: 0x03b6, // XK_lcedilla - 0x013d: 0x01a5, // XK_Lcaron - 0x013e: 0x01b5, // XK_lcaron - 0x0141: 0x01a3, // XK_Lstroke - 0x0142: 0x01b3, // XK_lstroke - 0x0143: 0x01d1, // XK_Nacute - 0x0144: 0x01f1, // XK_nacute - 0x0145: 0x03d1, // XK_Ncedilla - 0x0146: 0x03f1, // XK_ncedilla - 0x0147: 0x01d2, // XK_Ncaron - 0x0148: 0x01f2, // XK_ncaron - 0x014a: 0x03bd, // XK_ENG - 0x014b: 0x03bf, // XK_eng - 0x014c: 0x03d2, // XK_Omacron - 0x014d: 0x03f2, // XK_omacron - 0x0150: 0x01d5, // XK_Odoubleacute - 0x0151: 0x01f5, // XK_odoubleacute - 0x0152: 0x13bc, // XK_OE - 0x0153: 0x13bd, // XK_oe - 0x0154: 0x01c0, // XK_Racute - 0x0155: 0x01e0, // XK_racute - 0x0156: 0x03a3, // XK_Rcedilla - 0x0157: 0x03b3, // XK_rcedilla - 0x0158: 0x01d8, // XK_Rcaron - 0x0159: 0x01f8, // XK_rcaron - 0x015a: 0x01a6, // XK_Sacute - 0x015b: 0x01b6, // XK_sacute - 0x015c: 0x02de, // XK_Scircumflex - 0x015d: 0x02fe, // XK_scircumflex - 0x015e: 0x01aa, // XK_Scedilla - 0x015f: 0x01ba, // XK_scedilla - 0x0160: 0x01a9, // XK_Scaron - 0x0161: 0x01b9, // XK_scaron - 0x0162: 0x01de, // XK_Tcedilla - 0x0163: 0x01fe, // XK_tcedilla - 0x0164: 0x01ab, // XK_Tcaron - 0x0165: 0x01bb, // XK_tcaron - 0x0166: 0x03ac, // XK_Tslash - 0x0167: 0x03bc, // XK_tslash - 0x0168: 0x03dd, // XK_Utilde - 0x0169: 0x03fd, // XK_utilde - 0x016a: 0x03de, // XK_Umacron - 0x016b: 0x03fe, // XK_umacron - 0x016c: 0x02dd, // XK_Ubreve - 0x016d: 0x02fd, // XK_ubreve - 0x016e: 0x01d9, // XK_Uring - 0x016f: 0x01f9, // XK_uring - 0x0170: 0x01db, // XK_Udoubleacute - 0x0171: 0x01fb, // XK_udoubleacute - 0x0172: 0x03d9, // XK_Uogonek - 0x0173: 0x03f9, // XK_uogonek - 0x0178: 0x13be, // XK_Ydiaeresis - 0x0179: 0x01ac, // XK_Zacute - 0x017a: 0x01bc, // XK_zacute - 0x017b: 0x01af, // XK_Zabovedot - 0x017c: 0x01bf, // XK_zabovedot - 0x017d: 0x01ae, // XK_Zcaron - 0x017e: 0x01be, // XK_zcaron - 0x0192: 0x08f6, // XK_function - 0x01d2: 0x10001d1, // XK_Ocaron - 0x02c7: 0x01b7, // XK_caron - 0x02d8: 0x01a2, // XK_breve - 0x02d9: 0x01ff, // XK_abovedot - 0x02db: 0x01b2, // XK_ogonek - 0x02dd: 0x01bd, // XK_doubleacute - 0x0385: 0x07ae, // XK_Greek_accentdieresis - 0x0386: 0x07a1, // XK_Greek_ALPHAaccent - 0x0388: 0x07a2, // XK_Greek_EPSILONaccent - 0x0389: 0x07a3, // XK_Greek_ETAaccent - 0x038a: 0x07a4, // XK_Greek_IOTAaccent - 0x038c: 0x07a7, // XK_Greek_OMICRONaccent - 0x038e: 0x07a8, // XK_Greek_UPSILONaccent - 0x038f: 0x07ab, // XK_Greek_OMEGAaccent - 0x0390: 0x07b6, // XK_Greek_iotaaccentdieresis - 0x0391: 0x07c1, // XK_Greek_ALPHA - 0x0392: 0x07c2, // XK_Greek_BETA - 0x0393: 0x07c3, // XK_Greek_GAMMA - 0x0394: 0x07c4, // XK_Greek_DELTA - 0x0395: 0x07c5, // XK_Greek_EPSILON - 0x0396: 0x07c6, // XK_Greek_ZETA - 0x0397: 0x07c7, // XK_Greek_ETA - 0x0398: 0x07c8, // XK_Greek_THETA - 0x0399: 0x07c9, // XK_Greek_IOTA - 0x039a: 0x07ca, // XK_Greek_KAPPA - 0x039b: 0x07cb, // XK_Greek_LAMDA - 0x039c: 0x07cc, // XK_Greek_MU - 0x039d: 0x07cd, // XK_Greek_NU - 0x039e: 0x07ce, // XK_Greek_XI - 0x039f: 0x07cf, // XK_Greek_OMICRON - 0x03a0: 0x07d0, // XK_Greek_PI - 0x03a1: 0x07d1, // XK_Greek_RHO - 0x03a3: 0x07d2, // XK_Greek_SIGMA - 0x03a4: 0x07d4, // XK_Greek_TAU - 0x03a5: 0x07d5, // XK_Greek_UPSILON - 0x03a6: 0x07d6, // XK_Greek_PHI - 0x03a7: 0x07d7, // XK_Greek_CHI - 0x03a8: 0x07d8, // XK_Greek_PSI - 0x03a9: 0x07d9, // XK_Greek_OMEGA - 0x03aa: 0x07a5, // XK_Greek_IOTAdieresis - 0x03ab: 0x07a9, // XK_Greek_UPSILONdieresis - 0x03ac: 0x07b1, // XK_Greek_alphaaccent - 0x03ad: 0x07b2, // XK_Greek_epsilonaccent - 0x03ae: 0x07b3, // XK_Greek_etaaccent - 0x03af: 0x07b4, // XK_Greek_iotaaccent - 0x03b0: 0x07ba, // XK_Greek_upsilonaccentdieresis - 0x03b1: 0x07e1, // XK_Greek_alpha - 0x03b2: 0x07e2, // XK_Greek_beta - 0x03b3: 0x07e3, // XK_Greek_gamma - 0x03b4: 0x07e4, // XK_Greek_delta - 0x03b5: 0x07e5, // XK_Greek_epsilon - 0x03b6: 0x07e6, // XK_Greek_zeta - 0x03b7: 0x07e7, // XK_Greek_eta - 0x03b8: 0x07e8, // XK_Greek_theta - 0x03b9: 0x07e9, // XK_Greek_iota - 0x03ba: 0x07ea, // XK_Greek_kappa - 0x03bb: 0x07eb, // XK_Greek_lamda - 0x03bc: 0x07ec, // XK_Greek_mu - 0x03bd: 0x07ed, // XK_Greek_nu - 0x03be: 0x07ee, // XK_Greek_xi - 0x03bf: 0x07ef, // XK_Greek_omicron - 0x03c0: 0x07f0, // XK_Greek_pi - 0x03c1: 0x07f1, // XK_Greek_rho - 0x03c2: 0x07f3, // XK_Greek_finalsmallsigma - 0x03c3: 0x07f2, // XK_Greek_sigma - 0x03c4: 0x07f4, // XK_Greek_tau - 0x03c5: 0x07f5, // XK_Greek_upsilon - 0x03c6: 0x07f6, // XK_Greek_phi - 0x03c7: 0x07f7, // XK_Greek_chi - 0x03c8: 0x07f8, // XK_Greek_psi - 0x03c9: 0x07f9, // XK_Greek_omega - 0x03ca: 0x07b5, // XK_Greek_iotadieresis - 0x03cb: 0x07b9, // XK_Greek_upsilondieresis - 0x03cc: 0x07b7, // XK_Greek_omicronaccent - 0x03cd: 0x07b8, // XK_Greek_upsilonaccent - 0x03ce: 0x07bb, // XK_Greek_omegaaccent - 0x0401: 0x06b3, // XK_Cyrillic_IO - 0x0402: 0x06b1, // XK_Serbian_DJE - 0x0403: 0x06b2, // XK_Macedonia_GJE - 0x0404: 0x06b4, // XK_Ukrainian_IE - 0x0405: 0x06b5, // XK_Macedonia_DSE - 0x0406: 0x06b6, // XK_Ukrainian_I - 0x0407: 0x06b7, // XK_Ukrainian_YI - 0x0408: 0x06b8, // XK_Cyrillic_JE - 0x0409: 0x06b9, // XK_Cyrillic_LJE - 0x040a: 0x06ba, // XK_Cyrillic_NJE - 0x040b: 0x06bb, // XK_Serbian_TSHE - 0x040c: 0x06bc, // XK_Macedonia_KJE - 0x040e: 0x06be, // XK_Byelorussian_SHORTU - 0x040f: 0x06bf, // XK_Cyrillic_DZHE - 0x0410: 0x06e1, // XK_Cyrillic_A - 0x0411: 0x06e2, // XK_Cyrillic_BE - 0x0412: 0x06f7, // XK_Cyrillic_VE - 0x0413: 0x06e7, // XK_Cyrillic_GHE - 0x0414: 0x06e4, // XK_Cyrillic_DE - 0x0415: 0x06e5, // XK_Cyrillic_IE - 0x0416: 0x06f6, // XK_Cyrillic_ZHE - 0x0417: 0x06fa, // XK_Cyrillic_ZE - 0x0418: 0x06e9, // XK_Cyrillic_I - 0x0419: 0x06ea, // XK_Cyrillic_SHORTI - 0x041a: 0x06eb, // XK_Cyrillic_KA - 0x041b: 0x06ec, // XK_Cyrillic_EL - 0x041c: 0x06ed, // XK_Cyrillic_EM - 0x041d: 0x06ee, // XK_Cyrillic_EN - 0x041e: 0x06ef, // XK_Cyrillic_O - 0x041f: 0x06f0, // XK_Cyrillic_PE - 0x0420: 0x06f2, // XK_Cyrillic_ER - 0x0421: 0x06f3, // XK_Cyrillic_ES - 0x0422: 0x06f4, // XK_Cyrillic_TE - 0x0423: 0x06f5, // XK_Cyrillic_U - 0x0424: 0x06e6, // XK_Cyrillic_EF - 0x0425: 0x06e8, // XK_Cyrillic_HA - 0x0426: 0x06e3, // XK_Cyrillic_TSE - 0x0427: 0x06fe, // XK_Cyrillic_CHE - 0x0428: 0x06fb, // XK_Cyrillic_SHA - 0x0429: 0x06fd, // XK_Cyrillic_SHCHA - 0x042a: 0x06ff, // XK_Cyrillic_HARDSIGN - 0x042b: 0x06f9, // XK_Cyrillic_YERU - 0x042c: 0x06f8, // XK_Cyrillic_SOFTSIGN - 0x042d: 0x06fc, // XK_Cyrillic_E - 0x042e: 0x06e0, // XK_Cyrillic_YU - 0x042f: 0x06f1, // XK_Cyrillic_YA - 0x0430: 0x06c1, // XK_Cyrillic_a - 0x0431: 0x06c2, // XK_Cyrillic_be - 0x0432: 0x06d7, // XK_Cyrillic_ve - 0x0433: 0x06c7, // XK_Cyrillic_ghe - 0x0434: 0x06c4, // XK_Cyrillic_de - 0x0435: 0x06c5, // XK_Cyrillic_ie - 0x0436: 0x06d6, // XK_Cyrillic_zhe - 0x0437: 0x06da, // XK_Cyrillic_ze - 0x0438: 0x06c9, // XK_Cyrillic_i - 0x0439: 0x06ca, // XK_Cyrillic_shorti - 0x043a: 0x06cb, // XK_Cyrillic_ka - 0x043b: 0x06cc, // XK_Cyrillic_el - 0x043c: 0x06cd, // XK_Cyrillic_em - 0x043d: 0x06ce, // XK_Cyrillic_en - 0x043e: 0x06cf, // XK_Cyrillic_o - 0x043f: 0x06d0, // XK_Cyrillic_pe - 0x0440: 0x06d2, // XK_Cyrillic_er - 0x0441: 0x06d3, // XK_Cyrillic_es - 0x0442: 0x06d4, // XK_Cyrillic_te - 0x0443: 0x06d5, // XK_Cyrillic_u - 0x0444: 0x06c6, // XK_Cyrillic_ef - 0x0445: 0x06c8, // XK_Cyrillic_ha - 0x0446: 0x06c3, // XK_Cyrillic_tse - 0x0447: 0x06de, // XK_Cyrillic_che - 0x0448: 0x06db, // XK_Cyrillic_sha - 0x0449: 0x06dd, // XK_Cyrillic_shcha - 0x044a: 0x06df, // XK_Cyrillic_hardsign - 0x044b: 0x06d9, // XK_Cyrillic_yeru - 0x044c: 0x06d8, // XK_Cyrillic_softsign - 0x044d: 0x06dc, // XK_Cyrillic_e - 0x044e: 0x06c0, // XK_Cyrillic_yu - 0x044f: 0x06d1, // XK_Cyrillic_ya - 0x0451: 0x06a3, // XK_Cyrillic_io - 0x0452: 0x06a1, // XK_Serbian_dje - 0x0453: 0x06a2, // XK_Macedonia_gje - 0x0454: 0x06a4, // XK_Ukrainian_ie - 0x0455: 0x06a5, // XK_Macedonia_dse - 0x0456: 0x06a6, // XK_Ukrainian_i - 0x0457: 0x06a7, // XK_Ukrainian_yi - 0x0458: 0x06a8, // XK_Cyrillic_je - 0x0459: 0x06a9, // XK_Cyrillic_lje - 0x045a: 0x06aa, // XK_Cyrillic_nje - 0x045b: 0x06ab, // XK_Serbian_tshe - 0x045c: 0x06ac, // XK_Macedonia_kje - 0x045e: 0x06ae, // XK_Byelorussian_shortu - 0x045f: 0x06af, // XK_Cyrillic_dzhe - 0x0490: 0x06bd, // XK_Ukrainian_GHE_WITH_UPTURN - 0x0491: 0x06ad, // XK_Ukrainian_ghe_with_upturn - 0x05d0: 0x0ce0, // XK_hebrew_aleph - 0x05d1: 0x0ce1, // XK_hebrew_bet - 0x05d2: 0x0ce2, // XK_hebrew_gimel - 0x05d3: 0x0ce3, // XK_hebrew_dalet - 0x05d4: 0x0ce4, // XK_hebrew_he - 0x05d5: 0x0ce5, // XK_hebrew_waw - 0x05d6: 0x0ce6, // XK_hebrew_zain - 0x05d7: 0x0ce7, // XK_hebrew_chet - 0x05d8: 0x0ce8, // XK_hebrew_tet - 0x05d9: 0x0ce9, // XK_hebrew_yod - 0x05da: 0x0cea, // XK_hebrew_finalkaph - 0x05db: 0x0ceb, // XK_hebrew_kaph - 0x05dc: 0x0cec, // XK_hebrew_lamed - 0x05dd: 0x0ced, // XK_hebrew_finalmem - 0x05de: 0x0cee, // XK_hebrew_mem - 0x05df: 0x0cef, // XK_hebrew_finalnun - 0x05e0: 0x0cf0, // XK_hebrew_nun - 0x05e1: 0x0cf1, // XK_hebrew_samech - 0x05e2: 0x0cf2, // XK_hebrew_ayin - 0x05e3: 0x0cf3, // XK_hebrew_finalpe - 0x05e4: 0x0cf4, // XK_hebrew_pe - 0x05e5: 0x0cf5, // XK_hebrew_finalzade - 0x05e6: 0x0cf6, // XK_hebrew_zade - 0x05e7: 0x0cf7, // XK_hebrew_qoph - 0x05e8: 0x0cf8, // XK_hebrew_resh - 0x05e9: 0x0cf9, // XK_hebrew_shin - 0x05ea: 0x0cfa, // XK_hebrew_taw - 0x060c: 0x05ac, // XK_Arabic_comma - 0x061b: 0x05bb, // XK_Arabic_semicolon - 0x061f: 0x05bf, // XK_Arabic_question_mark - 0x0621: 0x05c1, // XK_Arabic_hamza - 0x0622: 0x05c2, // XK_Arabic_maddaonalef - 0x0623: 0x05c3, // XK_Arabic_hamzaonalef - 0x0624: 0x05c4, // XK_Arabic_hamzaonwaw - 0x0625: 0x05c5, // XK_Arabic_hamzaunderalef - 0x0626: 0x05c6, // XK_Arabic_hamzaonyeh - 0x0627: 0x05c7, // XK_Arabic_alef - 0x0628: 0x05c8, // XK_Arabic_beh - 0x0629: 0x05c9, // XK_Arabic_tehmarbuta - 0x062a: 0x05ca, // XK_Arabic_teh - 0x062b: 0x05cb, // XK_Arabic_theh - 0x062c: 0x05cc, // XK_Arabic_jeem - 0x062d: 0x05cd, // XK_Arabic_hah - 0x062e: 0x05ce, // XK_Arabic_khah - 0x062f: 0x05cf, // XK_Arabic_dal - 0x0630: 0x05d0, // XK_Arabic_thal - 0x0631: 0x05d1, // XK_Arabic_ra - 0x0632: 0x05d2, // XK_Arabic_zain - 0x0633: 0x05d3, // XK_Arabic_seen - 0x0634: 0x05d4, // XK_Arabic_sheen - 0x0635: 0x05d5, // XK_Arabic_sad - 0x0636: 0x05d6, // XK_Arabic_dad - 0x0637: 0x05d7, // XK_Arabic_tah - 0x0638: 0x05d8, // XK_Arabic_zah - 0x0639: 0x05d9, // XK_Arabic_ain - 0x063a: 0x05da, // XK_Arabic_ghain - 0x0640: 0x05e0, // XK_Arabic_tatweel - 0x0641: 0x05e1, // XK_Arabic_feh - 0x0642: 0x05e2, // XK_Arabic_qaf - 0x0643: 0x05e3, // XK_Arabic_kaf - 0x0644: 0x05e4, // XK_Arabic_lam - 0x0645: 0x05e5, // XK_Arabic_meem - 0x0646: 0x05e6, // XK_Arabic_noon - 0x0647: 0x05e7, // XK_Arabic_ha - 0x0648: 0x05e8, // XK_Arabic_waw - 0x0649: 0x05e9, // XK_Arabic_alefmaksura - 0x064a: 0x05ea, // XK_Arabic_yeh - 0x064b: 0x05eb, // XK_Arabic_fathatan - 0x064c: 0x05ec, // XK_Arabic_dammatan - 0x064d: 0x05ed, // XK_Arabic_kasratan - 0x064e: 0x05ee, // XK_Arabic_fatha - 0x064f: 0x05ef, // XK_Arabic_damma - 0x0650: 0x05f0, // XK_Arabic_kasra - 0x0651: 0x05f1, // XK_Arabic_shadda - 0x0652: 0x05f2, // XK_Arabic_sukun - 0x0e01: 0x0da1, // XK_Thai_kokai - 0x0e02: 0x0da2, // XK_Thai_khokhai - 0x0e03: 0x0da3, // XK_Thai_khokhuat - 0x0e04: 0x0da4, // XK_Thai_khokhwai - 0x0e05: 0x0da5, // XK_Thai_khokhon - 0x0e06: 0x0da6, // XK_Thai_khorakhang - 0x0e07: 0x0da7, // XK_Thai_ngongu - 0x0e08: 0x0da8, // XK_Thai_chochan - 0x0e09: 0x0da9, // XK_Thai_choching - 0x0e0a: 0x0daa, // XK_Thai_chochang - 0x0e0b: 0x0dab, // XK_Thai_soso - 0x0e0c: 0x0dac, // XK_Thai_chochoe - 0x0e0d: 0x0dad, // XK_Thai_yoying - 0x0e0e: 0x0dae, // XK_Thai_dochada - 0x0e0f: 0x0daf, // XK_Thai_topatak - 0x0e10: 0x0db0, // XK_Thai_thothan - 0x0e11: 0x0db1, // XK_Thai_thonangmontho - 0x0e12: 0x0db2, // XK_Thai_thophuthao - 0x0e13: 0x0db3, // XK_Thai_nonen - 0x0e14: 0x0db4, // XK_Thai_dodek - 0x0e15: 0x0db5, // XK_Thai_totao - 0x0e16: 0x0db6, // XK_Thai_thothung - 0x0e17: 0x0db7, // XK_Thai_thothahan - 0x0e18: 0x0db8, // XK_Thai_thothong - 0x0e19: 0x0db9, // XK_Thai_nonu - 0x0e1a: 0x0dba, // XK_Thai_bobaimai - 0x0e1b: 0x0dbb, // XK_Thai_popla - 0x0e1c: 0x0dbc, // XK_Thai_phophung - 0x0e1d: 0x0dbd, // XK_Thai_fofa - 0x0e1e: 0x0dbe, // XK_Thai_phophan - 0x0e1f: 0x0dbf, // XK_Thai_fofan - 0x0e20: 0x0dc0, // XK_Thai_phosamphao - 0x0e21: 0x0dc1, // XK_Thai_moma - 0x0e22: 0x0dc2, // XK_Thai_yoyak - 0x0e23: 0x0dc3, // XK_Thai_rorua - 0x0e24: 0x0dc4, // XK_Thai_ru - 0x0e25: 0x0dc5, // XK_Thai_loling - 0x0e26: 0x0dc6, // XK_Thai_lu - 0x0e27: 0x0dc7, // XK_Thai_wowaen - 0x0e28: 0x0dc8, // XK_Thai_sosala - 0x0e29: 0x0dc9, // XK_Thai_sorusi - 0x0e2a: 0x0dca, // XK_Thai_sosua - 0x0e2b: 0x0dcb, // XK_Thai_hohip - 0x0e2c: 0x0dcc, // XK_Thai_lochula - 0x0e2d: 0x0dcd, // XK_Thai_oang - 0x0e2e: 0x0dce, // XK_Thai_honokhuk - 0x0e2f: 0x0dcf, // XK_Thai_paiyannoi - 0x0e30: 0x0dd0, // XK_Thai_saraa - 0x0e31: 0x0dd1, // XK_Thai_maihanakat - 0x0e32: 0x0dd2, // XK_Thai_saraaa - 0x0e33: 0x0dd3, // XK_Thai_saraam - 0x0e34: 0x0dd4, // XK_Thai_sarai - 0x0e35: 0x0dd5, // XK_Thai_saraii - 0x0e36: 0x0dd6, // XK_Thai_saraue - 0x0e37: 0x0dd7, // XK_Thai_sarauee - 0x0e38: 0x0dd8, // XK_Thai_sarau - 0x0e39: 0x0dd9, // XK_Thai_sarauu - 0x0e3a: 0x0dda, // XK_Thai_phinthu - 0x0e3f: 0x0ddf, // XK_Thai_baht - 0x0e40: 0x0de0, // XK_Thai_sarae - 0x0e41: 0x0de1, // XK_Thai_saraae - 0x0e42: 0x0de2, // XK_Thai_sarao - 0x0e43: 0x0de3, // XK_Thai_saraaimaimuan - 0x0e44: 0x0de4, // XK_Thai_saraaimaimalai - 0x0e45: 0x0de5, // XK_Thai_lakkhangyao - 0x0e46: 0x0de6, // XK_Thai_maiyamok - 0x0e47: 0x0de7, // XK_Thai_maitaikhu - 0x0e48: 0x0de8, // XK_Thai_maiek - 0x0e49: 0x0de9, // XK_Thai_maitho - 0x0e4a: 0x0dea, // XK_Thai_maitri - 0x0e4b: 0x0deb, // XK_Thai_maichattawa - 0x0e4c: 0x0dec, // XK_Thai_thanthakhat - 0x0e4d: 0x0ded, // XK_Thai_nikhahit - 0x0e50: 0x0df0, // XK_Thai_leksun - 0x0e51: 0x0df1, // XK_Thai_leknung - 0x0e52: 0x0df2, // XK_Thai_leksong - 0x0e53: 0x0df3, // XK_Thai_leksam - 0x0e54: 0x0df4, // XK_Thai_leksi - 0x0e55: 0x0df5, // XK_Thai_lekha - 0x0e56: 0x0df6, // XK_Thai_lekhok - 0x0e57: 0x0df7, // XK_Thai_lekchet - 0x0e58: 0x0df8, // XK_Thai_lekpaet - 0x0e59: 0x0df9, // XK_Thai_lekkao - 0x2002: 0x0aa2, // XK_enspace - 0x2003: 0x0aa1, // XK_emspace - 0x2004: 0x0aa3, // XK_em3space - 0x2005: 0x0aa4, // XK_em4space - 0x2007: 0x0aa5, // XK_digitspace - 0x2008: 0x0aa6, // XK_punctspace - 0x2009: 0x0aa7, // XK_thinspace - 0x200a: 0x0aa8, // XK_hairspace - 0x2012: 0x0abb, // XK_figdash - 0x2013: 0x0aaa, // XK_endash - 0x2014: 0x0aa9, // XK_emdash - 0x2015: 0x07af, // XK_Greek_horizbar - 0x2017: 0x0cdf, // XK_hebrew_doublelowline - 0x2018: 0x0ad0, // XK_leftsinglequotemark - 0x2019: 0x0ad1, // XK_rightsinglequotemark - 0x201a: 0x0afd, // XK_singlelowquotemark - 0x201c: 0x0ad2, // XK_leftdoublequotemark - 0x201d: 0x0ad3, // XK_rightdoublequotemark - 0x201e: 0x0afe, // XK_doublelowquotemark - 0x2020: 0x0af1, // XK_dagger - 0x2021: 0x0af2, // XK_doubledagger - 0x2022: 0x0ae6, // XK_enfilledcircbullet - 0x2025: 0x0aaf, // XK_doubbaselinedot - 0x2026: 0x0aae, // XK_ellipsis - 0x2030: 0x0ad5, // XK_permille - 0x2032: 0x0ad6, // XK_minutes - 0x2033: 0x0ad7, // XK_seconds - 0x2038: 0x0afc, // XK_caret - 0x203e: 0x047e, // XK_overline - 0x20a9: 0x0eff, // XK_Korean_Won - 0x20ac: 0x20ac, // XK_EuroSign - 0x2105: 0x0ab8, // XK_careof - 0x2116: 0x06b0, // XK_numerosign - 0x2117: 0x0afb, // XK_phonographcopyright - 0x211e: 0x0ad4, // XK_prescription - 0x2122: 0x0ac9, // XK_trademark - 0x2153: 0x0ab0, // XK_onethird - 0x2154: 0x0ab1, // XK_twothirds - 0x2155: 0x0ab2, // XK_onefifth - 0x2156: 0x0ab3, // XK_twofifths - 0x2157: 0x0ab4, // XK_threefifths - 0x2158: 0x0ab5, // XK_fourfifths - 0x2159: 0x0ab6, // XK_onesixth - 0x215a: 0x0ab7, // XK_fivesixths - 0x215b: 0x0ac3, // XK_oneeighth - 0x215c: 0x0ac4, // XK_threeeighths - 0x215d: 0x0ac5, // XK_fiveeighths - 0x215e: 0x0ac6, // XK_seveneighths - 0x2190: 0x08fb, // XK_leftarrow - 0x2191: 0x08fc, // XK_uparrow - 0x2192: 0x08fd, // XK_rightarrow - 0x2193: 0x08fe, // XK_downarrow - 0x21d2: 0x08ce, // XK_implies - 0x21d4: 0x08cd, // XK_ifonlyif - 0x2202: 0x08ef, // XK_partialderivative - 0x2207: 0x08c5, // XK_nabla - 0x2218: 0x0bca, // XK_jot - 0x221a: 0x08d6, // XK_radical - 0x221d: 0x08c1, // XK_variation - 0x221e: 0x08c2, // XK_infinity - 0x2227: 0x08de, // XK_logicaland - 0x2228: 0x08df, // XK_logicalor - 0x2229: 0x08dc, // XK_intersection - 0x222a: 0x08dd, // XK_union - 0x222b: 0x08bf, // XK_integral - 0x2234: 0x08c0, // XK_therefore - 0x223c: 0x08c8, // XK_approximate - 0x2243: 0x08c9, // XK_similarequal - 0x2245: 0x1002248, // XK_approxeq - 0x2260: 0x08bd, // XK_notequal - 0x2261: 0x08cf, // XK_identical - 0x2264: 0x08bc, // XK_lessthanequal - 0x2265: 0x08be, // XK_greaterthanequal - 0x2282: 0x08da, // XK_includedin - 0x2283: 0x08db, // XK_includes - 0x22a2: 0x0bfc, // XK_righttack - 0x22a3: 0x0bdc, // XK_lefttack - 0x22a4: 0x0bc2, // XK_downtack - 0x22a5: 0x0bce, // XK_uptack - 0x2308: 0x0bd3, // XK_upstile - 0x230a: 0x0bc4, // XK_downstile - 0x2315: 0x0afa, // XK_telephonerecorder - 0x2320: 0x08a4, // XK_topintegral - 0x2321: 0x08a5, // XK_botintegral - 0x2395: 0x0bcc, // XK_quad - 0x239b: 0x08ab, // XK_topleftparens - 0x239d: 0x08ac, // XK_botleftparens - 0x239e: 0x08ad, // XK_toprightparens - 0x23a0: 0x08ae, // XK_botrightparens - 0x23a1: 0x08a7, // XK_topleftsqbracket - 0x23a3: 0x08a8, // XK_botleftsqbracket - 0x23a4: 0x08a9, // XK_toprightsqbracket - 0x23a6: 0x08aa, // XK_botrightsqbracket - 0x23a8: 0x08af, // XK_leftmiddlecurlybrace - 0x23ac: 0x08b0, // XK_rightmiddlecurlybrace - 0x23b7: 0x08a1, // XK_leftradical - 0x23ba: 0x09ef, // XK_horizlinescan1 - 0x23bb: 0x09f0, // XK_horizlinescan3 - 0x23bc: 0x09f2, // XK_horizlinescan7 - 0x23bd: 0x09f3, // XK_horizlinescan9 - 0x2409: 0x09e2, // XK_ht - 0x240a: 0x09e5, // XK_lf - 0x240b: 0x09e9, // XK_vt - 0x240c: 0x09e3, // XK_ff - 0x240d: 0x09e4, // XK_cr - 0x2423: 0x0aac, // XK_signifblank - 0x2424: 0x09e8, // XK_nl - 0x2500: 0x08a3, // XK_horizconnector - 0x2502: 0x08a6, // XK_vertconnector - 0x250c: 0x08a2, // XK_topleftradical - 0x2510: 0x09eb, // XK_uprightcorner - 0x2514: 0x09ed, // XK_lowleftcorner - 0x2518: 0x09ea, // XK_lowrightcorner - 0x251c: 0x09f4, // XK_leftt - 0x2524: 0x09f5, // XK_rightt - 0x252c: 0x09f7, // XK_topt - 0x2534: 0x09f6, // XK_bott - 0x253c: 0x09ee, // XK_crossinglines - 0x2592: 0x09e1, // XK_checkerboard - 0x25aa: 0x0ae7, // XK_enfilledsqbullet - 0x25ab: 0x0ae1, // XK_enopensquarebullet - 0x25ac: 0x0adb, // XK_filledrectbullet - 0x25ad: 0x0ae2, // XK_openrectbullet - 0x25ae: 0x0adf, // XK_emfilledrect - 0x25af: 0x0acf, // XK_emopenrectangle - 0x25b2: 0x0ae8, // XK_filledtribulletup - 0x25b3: 0x0ae3, // XK_opentribulletup - 0x25b6: 0x0add, // XK_filledrighttribullet - 0x25b7: 0x0acd, // XK_rightopentriangle - 0x25bc: 0x0ae9, // XK_filledtribulletdown - 0x25bd: 0x0ae4, // XK_opentribulletdown - 0x25c0: 0x0adc, // XK_filledlefttribullet - 0x25c1: 0x0acc, // XK_leftopentriangle - 0x25c6: 0x09e0, // XK_soliddiamond - 0x25cb: 0x0ace, // XK_emopencircle - 0x25cf: 0x0ade, // XK_emfilledcircle - 0x25e6: 0x0ae0, // XK_enopencircbullet - 0x2606: 0x0ae5, // XK_openstar - 0x260e: 0x0af9, // XK_telephone - 0x2613: 0x0aca, // XK_signaturemark - 0x261c: 0x0aea, // XK_leftpointer - 0x261e: 0x0aeb, // XK_rightpointer - 0x2640: 0x0af8, // XK_femalesymbol - 0x2642: 0x0af7, // XK_malesymbol - 0x2663: 0x0aec, // XK_club - 0x2665: 0x0aee, // XK_heart - 0x2666: 0x0aed, // XK_diamond - 0x266d: 0x0af6, // XK_musicalflat - 0x266f: 0x0af5, // XK_musicalsharp - 0x2713: 0x0af3, // XK_checkmark - 0x2717: 0x0af4, // XK_ballotcross - 0x271d: 0x0ad9, // XK_latincross - 0x2720: 0x0af0, // XK_maltesecross - 0x27e8: 0x0abc, // XK_leftanglebracket - 0x27e9: 0x0abe, // XK_rightanglebracket - 0x3001: 0x04a4, // XK_kana_comma - 0x3002: 0x04a1, // XK_kana_fullstop - 0x300c: 0x04a2, // XK_kana_openingbracket - 0x300d: 0x04a3, // XK_kana_closingbracket - 0x309b: 0x04de, // XK_voicedsound - 0x309c: 0x04df, // XK_semivoicedsound - 0x30a1: 0x04a7, // XK_kana_a - 0x30a2: 0x04b1, // XK_kana_A - 0x30a3: 0x04a8, // XK_kana_i - 0x30a4: 0x04b2, // XK_kana_I - 0x30a5: 0x04a9, // XK_kana_u - 0x30a6: 0x04b3, // XK_kana_U - 0x30a7: 0x04aa, // XK_kana_e - 0x30a8: 0x04b4, // XK_kana_E - 0x30a9: 0x04ab, // XK_kana_o - 0x30aa: 0x04b5, // XK_kana_O - 0x30ab: 0x04b6, // XK_kana_KA - 0x30ad: 0x04b7, // XK_kana_KI - 0x30af: 0x04b8, // XK_kana_KU - 0x30b1: 0x04b9, // XK_kana_KE - 0x30b3: 0x04ba, // XK_kana_KO - 0x30b5: 0x04bb, // XK_kana_SA - 0x30b7: 0x04bc, // XK_kana_SHI - 0x30b9: 0x04bd, // XK_kana_SU - 0x30bb: 0x04be, // XK_kana_SE - 0x30bd: 0x04bf, // XK_kana_SO - 0x30bf: 0x04c0, // XK_kana_TA - 0x30c1: 0x04c1, // XK_kana_CHI - 0x30c3: 0x04af, // XK_kana_tsu - 0x30c4: 0x04c2, // XK_kana_TSU - 0x30c6: 0x04c3, // XK_kana_TE - 0x30c8: 0x04c4, // XK_kana_TO - 0x30ca: 0x04c5, // XK_kana_NA - 0x30cb: 0x04c6, // XK_kana_NI - 0x30cc: 0x04c7, // XK_kana_NU - 0x30cd: 0x04c8, // XK_kana_NE - 0x30ce: 0x04c9, // XK_kana_NO - 0x30cf: 0x04ca, // XK_kana_HA - 0x30d2: 0x04cb, // XK_kana_HI - 0x30d5: 0x04cc, // XK_kana_FU - 0x30d8: 0x04cd, // XK_kana_HE - 0x30db: 0x04ce, // XK_kana_HO - 0x30de: 0x04cf, // XK_kana_MA - 0x30df: 0x04d0, // XK_kana_MI - 0x30e0: 0x04d1, // XK_kana_MU - 0x30e1: 0x04d2, // XK_kana_ME - 0x30e2: 0x04d3, // XK_kana_MO - 0x30e3: 0x04ac, // XK_kana_ya - 0x30e4: 0x04d4, // XK_kana_YA - 0x30e5: 0x04ad, // XK_kana_yu - 0x30e6: 0x04d5, // XK_kana_YU - 0x30e7: 0x04ae, // XK_kana_yo - 0x30e8: 0x04d6, // XK_kana_YO - 0x30e9: 0x04d7, // XK_kana_RA - 0x30ea: 0x04d8, // XK_kana_RI - 0x30eb: 0x04d9, // XK_kana_RU - 0x30ec: 0x04da, // XK_kana_RE - 0x30ed: 0x04db, // XK_kana_RO - 0x30ef: 0x04dc, // XK_kana_WA - 0x30f2: 0x04a6, // XK_kana_WO - 0x30f3: 0x04dd, // XK_kana_N - 0x30fb: 0x04a5, // XK_kana_conjunctive - 0x30fc: 0x04b0, // XK_prolongedsound -}; - -export default { - lookup(u) { - // Latin-1 is one-to-one mapping - if ((u >= 0x20) && (u <= 0xff)) { - return u; - } - - // Lookup table (fairly random) - const keysym = codepoints[u]; - if (keysym !== undefined) { - return keysym; - } - - // General mapping as final fallback - return 0x01000000 | u; - }, -}; diff --git a/kasmweb/core/input/mouse.js b/kasmweb/core/input/mouse.js deleted file mode 100644 index c78f2ab..0000000 --- a/kasmweb/core/input/mouse.js +++ /dev/null @@ -1,280 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -import * as Log from '../util/logging.js'; -import { isTouchDevice } from '../util/browser.js'; -import { setCapture, stopEvent, getPointerEvent } from '../util/events.js'; - -const WHEEL_STEP = 10; // Delta threshold for a mouse wheel step -const WHEEL_STEP_TIMEOUT = 50; // ms -const WHEEL_LINE_HEIGHT = 19; - -export default class Mouse { - constructor(target) { - this._target = target || document; - - this._doubleClickTimer = null; - this._lastTouchPos = null; - - this._pos = null; - this._wheelStepXTimer = null; - this._wheelStepYTimer = null; - this._accumulatedWheelDeltaX = 0; - this._accumulatedWheelDeltaY = 0; - - this._eventHandlers = { - 'mousedown': this._handleMouseDown.bind(this), - 'mouseup': this._handleMouseUp.bind(this), - 'mousemove': this._handleMouseMove.bind(this), - 'mousewheel': this._handleMouseWheel.bind(this), - 'mousedisable': this._handleMouseDisable.bind(this) - }; - - // ===== PROPERTIES ===== - - this.touchButton = 1; // Button mask (1, 2, 4) for touch devices (0 means ignore clicks) - - // ===== EVENT HANDLERS ===== - - this.onmousebutton = () => {}; // Handler for mouse button click/release - this.onmousemove = () => {}; // Handler for mouse movement - } - - // ===== PRIVATE METHODS ===== - - _resetDoubleClickTimer() { - this._doubleClickTimer = null; - } - - _handleMouseButton(e, down) { - this._updateMousePosition(e); - let pos = this._pos; - - let bmask; - if (e.touches || e.changedTouches) { - // Touch device - - // When two touches occur within 500 ms of each other and are - // close enough together a double click is triggered. - if (down == 1) { - if (this._doubleClickTimer === null) { - this._lastTouchPos = pos; - } else { - clearTimeout(this._doubleClickTimer); - - // When the distance between the two touches is small enough - // force the position of the latter touch to the position of - // the first. - - const xs = this._lastTouchPos.x - pos.x; - const ys = this._lastTouchPos.y - pos.y; - const d = Math.sqrt((xs * xs) + (ys * ys)); - - // The goal is to trigger on a certain physical width, the - // devicePixelRatio brings us a bit closer but is not optimal. - const threshold = 20 * (window.devicePixelRatio || 1); - if (d < threshold) { - pos = this._lastTouchPos; - } - } - this._doubleClickTimer = setTimeout(this._resetDoubleClickTimer.bind(this), 500); - } - bmask = this.touchButton; - // If bmask is set - } else if (e.which) { - /* everything except IE */ - bmask = 1 << e.button; - } else { - /* IE including 9 */ - bmask = (e.button & 0x1) + // Left - (e.button & 0x2) * 2 + // Right - (e.button & 0x4) / 2; // Middle - } - - Log.Debug("onmousebutton " + (down ? "down" : "up") + - ", x: " + pos.x + ", y: " + pos.y + ", bmask: " + bmask); - this.onmousebutton(pos.x, pos.y, down, bmask); - - stopEvent(e); - } - - _handleMouseDown(e) { - // Touch events have implicit capture - if (e.type === "mousedown") { - setCapture(this._target); - } - - this._handleMouseButton(e, 1); - } - - _handleMouseUp(e) { - this._handleMouseButton(e, 0); - } - - // Mouse wheel events are sent in steps over VNC. This means that the VNC - // protocol can't handle a wheel event with specific distance or speed. - // Therefor, if we get a lot of small mouse wheel events we combine them. - _generateWheelStepX() { - - if (this._accumulatedWheelDeltaX < 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 5); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 5); - } else if (this._accumulatedWheelDeltaX > 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 6); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 6); - } - - this._accumulatedWheelDeltaX = 0; - } - - _generateWheelStepY() { - - if (this._accumulatedWheelDeltaY < 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 3); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 3); - } else if (this._accumulatedWheelDeltaY > 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 4); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 4); - } - - this._accumulatedWheelDeltaY = 0; - } - - _resetWheelStepTimers() { - window.clearTimeout(this._wheelStepXTimer); - window.clearTimeout(this._wheelStepYTimer); - this._wheelStepXTimer = null; - this._wheelStepYTimer = null; - } - - _handleMouseWheel(e) { - this._resetWheelStepTimers(); - - this._updateMousePosition(e); - - let dX = e.deltaX; - let dY = e.deltaY; - - // Pixel units unless it's non-zero. - // Note that if deltamode is line or page won't matter since we aren't - // sending the mouse wheel delta to the server anyway. - // The difference between pixel and line can be important however since - // we have a threshold that can be smaller than the line height. - if (e.deltaMode !== 0) { - dX *= WHEEL_LINE_HEIGHT; - dY *= WHEEL_LINE_HEIGHT; - } - - this._accumulatedWheelDeltaX += dX; - this._accumulatedWheelDeltaY += dY; - - // Generate a mouse wheel step event when the accumulated delta - // for one of the axes is large enough. - // Small delta events that do not pass the threshold get sent - // after a timeout. - if (Math.abs(this._accumulatedWheelDeltaX) > WHEEL_STEP) { - this._generateWheelStepX(); - } else { - this._wheelStepXTimer = - window.setTimeout(this._generateWheelStepX.bind(this), - WHEEL_STEP_TIMEOUT); - } - if (Math.abs(this._accumulatedWheelDeltaY) > WHEEL_STEP) { - this._generateWheelStepY(); - } else { - this._wheelStepYTimer = - window.setTimeout(this._generateWheelStepY.bind(this), - WHEEL_STEP_TIMEOUT); - } - - stopEvent(e); - } - - _handleMouseMove(e) { - this._updateMousePosition(e); - this.onmousemove(this._pos.x, this._pos.y); - stopEvent(e); - } - - _handleMouseDisable(e) { - /* - * Stop propagation if inside canvas area - * Note: This is only needed for the 'click' event as it fails - * to fire properly for the target element so we have - * to listen on the document element instead. - */ - if (e.target == this._target) { - stopEvent(e); - } - } - - // Update coordinates relative to target - _updateMousePosition(e) { - e = getPointerEvent(e); - const bounds = this._target.getBoundingClientRect(); - let x; - let y; - // Clip to target bounds - if (e.clientX < bounds.left) { - x = 0; - } else if (e.clientX >= bounds.right) { - x = bounds.width - 1; - } else { - x = e.clientX - bounds.left; - } - if (e.clientY < bounds.top) { - y = 0; - } else if (e.clientY >= bounds.bottom) { - y = bounds.height - 1; - } else { - y = e.clientY - bounds.top; - } - this._pos = {x: x, y: y}; - } - - // ===== PUBLIC METHODS ===== - - grab() { - const c = this._target; - - if (isTouchDevice) { - c.addEventListener('touchstart', this._eventHandlers.mousedown); - c.addEventListener('touchend', this._eventHandlers.mouseup); - c.addEventListener('touchmove', this._eventHandlers.mousemove); - } - c.addEventListener('mousedown', this._eventHandlers.mousedown); - c.addEventListener('mouseup', this._eventHandlers.mouseup); - c.addEventListener('mousemove', this._eventHandlers.mousemove); - c.addEventListener('wheel', this._eventHandlers.mousewheel); - - /* Prevent middle-click pasting (see above for why we bind to document) */ - document.addEventListener('click', this._eventHandlers.mousedisable); - - /* preventDefault() on mousedown doesn't stop this event for some - reason so we have to explicitly block it */ - c.addEventListener('contextmenu', this._eventHandlers.mousedisable); - } - - ungrab() { - const c = this._target; - - this._resetWheelStepTimers(); - - if (isTouchDevice) { - c.removeEventListener('touchstart', this._eventHandlers.mousedown); - c.removeEventListener('touchend', this._eventHandlers.mouseup); - c.removeEventListener('touchmove', this._eventHandlers.mousemove); - } - c.removeEventListener('mousedown', this._eventHandlers.mousedown); - c.removeEventListener('mouseup', this._eventHandlers.mouseup); - c.removeEventListener('mousemove', this._eventHandlers.mousemove); - c.removeEventListener('wheel', this._eventHandlers.mousewheel); - - document.removeEventListener('click', this._eventHandlers.mousedisable); - - c.removeEventListener('contextmenu', this._eventHandlers.mousedisable); - } -} diff --git a/kasmweb/core/input/util.js b/kasmweb/core/input/util.js deleted file mode 100644 index f177ef5..0000000 --- a/kasmweb/core/input/util.js +++ /dev/null @@ -1,164 +0,0 @@ -import keysyms from "./keysymdef.js"; -import vkeys from "./vkeys.js"; -import fixedkeys from "./fixedkeys.js"; -import DOMKeyTable from "./domkeytable.js"; -import * as browser from "../util/browser.js"; - -// Get 'KeyboardEvent.code', handling legacy browsers -export function getKeycode(evt) { - // Are we getting proper key identifiers? - // (unfortunately Firefox and Chrome are crappy here and gives - // us an empty string on some platforms, rather than leaving it - // undefined) - if (evt.code) { - // Mozilla isn't fully in sync with the spec yet - switch (evt.code) { - case 'OSLeft': return 'MetaLeft'; - case 'OSRight': return 'MetaRight'; - } - - return evt.code; - } - - // The de-facto standard is to use Windows Virtual-Key codes - // in the 'keyCode' field for non-printable characters. However - // Webkit sets it to the same as charCode in 'keypress' events. - if ((evt.type !== 'keypress') && (evt.keyCode in vkeys)) { - let code = vkeys[evt.keyCode]; - - // macOS has messed up this code for some reason - if (browser.isMac() && (code === 'ContextMenu')) { - code = 'MetaRight'; - } - - // The keyCode doesn't distinguish between left and right - // for the standard modifiers - if (evt.location === 2) { - switch (code) { - case 'ShiftLeft': return 'ShiftRight'; - case 'ControlLeft': return 'ControlRight'; - case 'AltLeft': return 'AltRight'; - } - } - - // Nor a bunch of the numpad keys - if (evt.location === 3) { - switch (code) { - case 'Delete': return 'NumpadDecimal'; - case 'Insert': return 'Numpad0'; - case 'End': return 'Numpad1'; - case 'ArrowDown': return 'Numpad2'; - case 'PageDown': return 'Numpad3'; - case 'ArrowLeft': return 'Numpad4'; - case 'ArrowRight': return 'Numpad6'; - case 'Home': return 'Numpad7'; - case 'ArrowUp': return 'Numpad8'; - case 'PageUp': return 'Numpad9'; - case 'Enter': return 'NumpadEnter'; - } - } - - return code; - } - - return 'Unidentified'; -} - -// Get 'KeyboardEvent.key', handling legacy browsers -export function getKey(evt) { - // Are we getting a proper key value? - if (evt.key !== undefined) { - // IE and Edge use some ancient version of the spec - // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ - switch (evt.key) { - case 'Spacebar': return ' '; - case 'Esc': return 'Escape'; - case 'Scroll': return 'ScrollLock'; - case 'Win': return 'Meta'; - case 'Apps': return 'ContextMenu'; - case 'Up': return 'ArrowUp'; - case 'Left': return 'ArrowLeft'; - case 'Right': return 'ArrowRight'; - case 'Down': return 'ArrowDown'; - case 'Del': return 'Delete'; - case 'Divide': return '/'; - case 'Multiply': return '*'; - case 'Subtract': return '-'; - case 'Add': return '+'; - case 'Decimal': return evt.char; - } - - // Mozilla isn't fully in sync with the spec yet - switch (evt.key) { - case 'OS': return 'Meta'; - } - - // iOS leaks some OS names - switch (evt.key) { - case 'UIKeyInputUpArrow': return 'ArrowUp'; - case 'UIKeyInputDownArrow': return 'ArrowDown'; - case 'UIKeyInputLeftArrow': return 'ArrowLeft'; - case 'UIKeyInputRightArrow': return 'ArrowRight'; - case 'UIKeyInputEscape': return 'Escape'; - } - - // IE and Edge have broken handling of AltGraph so we cannot - // trust them for printable characters - if ((evt.key.length !== 1) || (!browser.isIE() && !browser.isEdge())) { - return evt.key; - } - } - - // Try to deduce it based on the physical key - const code = getKeycode(evt); - if (code in fixedkeys) { - return fixedkeys[code]; - } - - // If that failed, then see if we have a printable character - if (evt.charCode) { - return String.fromCharCode(evt.charCode); - } - - // At this point we have nothing left to go on - return 'Unidentified'; -} - -// Get the most reliable keysym value we can get from a key event -export function getKeysym(evt) { - const key = getKey(evt); - - if (key === 'Unidentified') { - return null; - } - - // First look up special keys - if (key in DOMKeyTable) { - let location = evt.location; - - // Safari screws up location for the right cmd key - if ((key === 'Meta') && (location === 0)) { - location = 2; - } - - if ((location === undefined) || (location > 3)) { - location = 0; - } - - return DOMKeyTable[key][location]; - } - - // Now we need to look at the Unicode symbol instead - - // Special key? (FIXME: Should have been caught earlier) - if (key.length !== 1) { - return null; - } - - const codepoint = key.charCodeAt(); - if (codepoint) { - return keysyms.lookup(codepoint); - } - - return null; -} diff --git a/kasmweb/core/input/vkeys.js b/kasmweb/core/input/vkeys.js deleted file mode 100644 index f84109b..0000000 --- a/kasmweb/core/input/vkeys.js +++ /dev/null @@ -1,117 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -/* - * Mapping between Microsoft® Windows® Virtual-Key codes and - * HTML key codes. - */ - -export default { - 0x08: 'Backspace', - 0x09: 'Tab', - 0x0a: 'NumpadClear', - 0x0c: 'Numpad5', // IE11 sends evt.keyCode: 12 when numlock is off - 0x0d: 'Enter', - 0x10: 'ShiftLeft', - 0x11: 'ControlLeft', - 0x12: 'AltLeft', - 0x13: 'Pause', - 0x14: 'CapsLock', - 0x15: 'Lang1', - 0x19: 'Lang2', - 0x1b: 'Escape', - 0x1c: 'Convert', - 0x1d: 'NonConvert', - 0x20: 'Space', - 0x21: 'PageUp', - 0x22: 'PageDown', - 0x23: 'End', - 0x24: 'Home', - 0x25: 'ArrowLeft', - 0x26: 'ArrowUp', - 0x27: 'ArrowRight', - 0x28: 'ArrowDown', - 0x29: 'Select', - 0x2c: 'PrintScreen', - 0x2d: 'Insert', - 0x2e: 'Delete', - 0x2f: 'Help', - 0x30: 'Digit0', - 0x31: 'Digit1', - 0x32: 'Digit2', - 0x33: 'Digit3', - 0x34: 'Digit4', - 0x35: 'Digit5', - 0x36: 'Digit6', - 0x37: 'Digit7', - 0x38: 'Digit8', - 0x39: 'Digit9', - 0x5b: 'MetaLeft', - 0x5c: 'MetaRight', - 0x5d: 'ContextMenu', - 0x5f: 'Sleep', - 0x60: 'Numpad0', - 0x61: 'Numpad1', - 0x62: 'Numpad2', - 0x63: 'Numpad3', - 0x64: 'Numpad4', - 0x65: 'Numpad5', - 0x66: 'Numpad6', - 0x67: 'Numpad7', - 0x68: 'Numpad8', - 0x69: 'Numpad9', - 0x6a: 'NumpadMultiply', - 0x6b: 'NumpadAdd', - 0x6c: 'NumpadDecimal', - 0x6d: 'NumpadSubtract', - 0x6e: 'NumpadDecimal', // Duplicate, because buggy on Windows - 0x6f: 'NumpadDivide', - 0x70: 'F1', - 0x71: 'F2', - 0x72: 'F3', - 0x73: 'F4', - 0x74: 'F5', - 0x75: 'F6', - 0x76: 'F7', - 0x77: 'F8', - 0x78: 'F9', - 0x79: 'F10', - 0x7a: 'F11', - 0x7b: 'F12', - 0x7c: 'F13', - 0x7d: 'F14', - 0x7e: 'F15', - 0x7f: 'F16', - 0x80: 'F17', - 0x81: 'F18', - 0x82: 'F19', - 0x83: 'F20', - 0x84: 'F21', - 0x85: 'F22', - 0x86: 'F23', - 0x87: 'F24', - 0x90: 'NumLock', - 0x91: 'ScrollLock', - 0xa6: 'BrowserBack', - 0xa7: 'BrowserForward', - 0xa8: 'BrowserRefresh', - 0xa9: 'BrowserStop', - 0xaa: 'BrowserSearch', - 0xab: 'BrowserFavorites', - 0xac: 'BrowserHome', - 0xad: 'AudioVolumeMute', - 0xae: 'AudioVolumeDown', - 0xaf: 'AudioVolumeUp', - 0xb0: 'MediaTrackNext', - 0xb1: 'MediaTrackPrevious', - 0xb2: 'MediaStop', - 0xb3: 'MediaPlayPause', - 0xb4: 'LaunchMail', - 0xb5: 'MediaSelect', - 0xb6: 'LaunchApp1', - 0xb7: 'LaunchApp2', - 0xe1: 'AltRight', // Only when it is AltGraph -}; diff --git a/kasmweb/core/input/xtscancodes.js b/kasmweb/core/input/xtscancodes.js deleted file mode 100644 index 514809c..0000000 --- a/kasmweb/core/input/xtscancodes.js +++ /dev/null @@ -1,171 +0,0 @@ -/* - * This file is auto-generated from keymaps.csv on 2017-05-31 16:20 - * Database checksum sha256(92fd165507f2a3b8c5b3fa56e425d45788dbcb98cf067a307527d91ce22cab94) - * To re-generate, run: - * keymap-gen --lang=js code-map keymaps.csv html atset1 -*/ -export default { - "Again": 0xe005, /* html:Again (Again) -> linux:129 (KEY_AGAIN) -> atset1:57349 */ - "AltLeft": 0x38, /* html:AltLeft (AltLeft) -> linux:56 (KEY_LEFTALT) -> atset1:56 */ - "AltRight": 0xe038, /* html:AltRight (AltRight) -> linux:100 (KEY_RIGHTALT) -> atset1:57400 */ - "ArrowDown": 0xe050, /* html:ArrowDown (ArrowDown) -> linux:108 (KEY_DOWN) -> atset1:57424 */ - "ArrowLeft": 0xe04b, /* html:ArrowLeft (ArrowLeft) -> linux:105 (KEY_LEFT) -> atset1:57419 */ - "ArrowRight": 0xe04d, /* html:ArrowRight (ArrowRight) -> linux:106 (KEY_RIGHT) -> atset1:57421 */ - "ArrowUp": 0xe048, /* html:ArrowUp (ArrowUp) -> linux:103 (KEY_UP) -> atset1:57416 */ - "AudioVolumeDown": 0xe02e, /* html:AudioVolumeDown (AudioVolumeDown) -> linux:114 (KEY_VOLUMEDOWN) -> atset1:57390 */ - "AudioVolumeMute": 0xe020, /* html:AudioVolumeMute (AudioVolumeMute) -> linux:113 (KEY_MUTE) -> atset1:57376 */ - "AudioVolumeUp": 0xe030, /* html:AudioVolumeUp (AudioVolumeUp) -> linux:115 (KEY_VOLUMEUP) -> atset1:57392 */ - "Backquote": 0x29, /* html:Backquote (Backquote) -> linux:41 (KEY_GRAVE) -> atset1:41 */ - "Backslash": 0x2b, /* html:Backslash (Backslash) -> linux:43 (KEY_BACKSLASH) -> atset1:43 */ - "Backspace": 0xe, /* html:Backspace (Backspace) -> linux:14 (KEY_BACKSPACE) -> atset1:14 */ - "BracketLeft": 0x1a, /* html:BracketLeft (BracketLeft) -> linux:26 (KEY_LEFTBRACE) -> atset1:26 */ - "BracketRight": 0x1b, /* html:BracketRight (BracketRight) -> linux:27 (KEY_RIGHTBRACE) -> atset1:27 */ - "BrowserBack": 0xe06a, /* html:BrowserBack (BrowserBack) -> linux:158 (KEY_BACK) -> atset1:57450 */ - "BrowserFavorites": 0xe066, /* html:BrowserFavorites (BrowserFavorites) -> linux:156 (KEY_BOOKMARKS) -> atset1:57446 */ - "BrowserForward": 0xe069, /* html:BrowserForward (BrowserForward) -> linux:159 (KEY_FORWARD) -> atset1:57449 */ - "BrowserHome": 0xe032, /* html:BrowserHome (BrowserHome) -> linux:172 (KEY_HOMEPAGE) -> atset1:57394 */ - "BrowserRefresh": 0xe067, /* html:BrowserRefresh (BrowserRefresh) -> linux:173 (KEY_REFRESH) -> atset1:57447 */ - "BrowserSearch": 0xe065, /* html:BrowserSearch (BrowserSearch) -> linux:217 (KEY_SEARCH) -> atset1:57445 */ - "BrowserStop": 0xe068, /* html:BrowserStop (BrowserStop) -> linux:128 (KEY_STOP) -> atset1:57448 */ - "CapsLock": 0x3a, /* html:CapsLock (CapsLock) -> linux:58 (KEY_CAPSLOCK) -> atset1:58 */ - "Comma": 0x33, /* html:Comma (Comma) -> linux:51 (KEY_COMMA) -> atset1:51 */ - "ContextMenu": 0xe05d, /* html:ContextMenu (ContextMenu) -> linux:127 (KEY_COMPOSE) -> atset1:57437 */ - "ControlLeft": 0x1d, /* html:ControlLeft (ControlLeft) -> linux:29 (KEY_LEFTCTRL) -> atset1:29 */ - "ControlRight": 0xe01d, /* html:ControlRight (ControlRight) -> linux:97 (KEY_RIGHTCTRL) -> atset1:57373 */ - "Convert": 0x79, /* html:Convert (Convert) -> linux:92 (KEY_HENKAN) -> atset1:121 */ - "Copy": 0xe078, /* html:Copy (Copy) -> linux:133 (KEY_COPY) -> atset1:57464 */ - "Cut": 0xe03c, /* html:Cut (Cut) -> linux:137 (KEY_CUT) -> atset1:57404 */ - "Delete": 0xe053, /* html:Delete (Delete) -> linux:111 (KEY_DELETE) -> atset1:57427 */ - "Digit0": 0xb, /* html:Digit0 (Digit0) -> linux:11 (KEY_0) -> atset1:11 */ - "Digit1": 0x2, /* html:Digit1 (Digit1) -> linux:2 (KEY_1) -> atset1:2 */ - "Digit2": 0x3, /* html:Digit2 (Digit2) -> linux:3 (KEY_2) -> atset1:3 */ - "Digit3": 0x4, /* html:Digit3 (Digit3) -> linux:4 (KEY_3) -> atset1:4 */ - "Digit4": 0x5, /* html:Digit4 (Digit4) -> linux:5 (KEY_4) -> atset1:5 */ - "Digit5": 0x6, /* html:Digit5 (Digit5) -> linux:6 (KEY_5) -> atset1:6 */ - "Digit6": 0x7, /* html:Digit6 (Digit6) -> linux:7 (KEY_6) -> atset1:7 */ - "Digit7": 0x8, /* html:Digit7 (Digit7) -> linux:8 (KEY_7) -> atset1:8 */ - "Digit8": 0x9, /* html:Digit8 (Digit8) -> linux:9 (KEY_8) -> atset1:9 */ - "Digit9": 0xa, /* html:Digit9 (Digit9) -> linux:10 (KEY_9) -> atset1:10 */ - "Eject": 0xe07d, /* html:Eject (Eject) -> linux:162 (KEY_EJECTCLOSECD) -> atset1:57469 */ - "End": 0xe04f, /* html:End (End) -> linux:107 (KEY_END) -> atset1:57423 */ - "Enter": 0x1c, /* html:Enter (Enter) -> linux:28 (KEY_ENTER) -> atset1:28 */ - "Equal": 0xd, /* html:Equal (Equal) -> linux:13 (KEY_EQUAL) -> atset1:13 */ - "Escape": 0x1, /* html:Escape (Escape) -> linux:1 (KEY_ESC) -> atset1:1 */ - "F1": 0x3b, /* html:F1 (F1) -> linux:59 (KEY_F1) -> atset1:59 */ - "F10": 0x44, /* html:F10 (F10) -> linux:68 (KEY_F10) -> atset1:68 */ - "F11": 0x57, /* html:F11 (F11) -> linux:87 (KEY_F11) -> atset1:87 */ - "F12": 0x58, /* html:F12 (F12) -> linux:88 (KEY_F12) -> atset1:88 */ - "F13": 0x5d, /* html:F13 (F13) -> linux:183 (KEY_F13) -> atset1:93 */ - "F14": 0x5e, /* html:F14 (F14) -> linux:184 (KEY_F14) -> atset1:94 */ - "F15": 0x5f, /* html:F15 (F15) -> linux:185 (KEY_F15) -> atset1:95 */ - "F16": 0x55, /* html:F16 (F16) -> linux:186 (KEY_F16) -> atset1:85 */ - "F17": 0xe003, /* html:F17 (F17) -> linux:187 (KEY_F17) -> atset1:57347 */ - "F18": 0xe077, /* html:F18 (F18) -> linux:188 (KEY_F18) -> atset1:57463 */ - "F19": 0xe004, /* html:F19 (F19) -> linux:189 (KEY_F19) -> atset1:57348 */ - "F2": 0x3c, /* html:F2 (F2) -> linux:60 (KEY_F2) -> atset1:60 */ - "F20": 0x5a, /* html:F20 (F20) -> linux:190 (KEY_F20) -> atset1:90 */ - "F21": 0x74, /* html:F21 (F21) -> linux:191 (KEY_F21) -> atset1:116 */ - "F22": 0xe079, /* html:F22 (F22) -> linux:192 (KEY_F22) -> atset1:57465 */ - "F23": 0x6d, /* html:F23 (F23) -> linux:193 (KEY_F23) -> atset1:109 */ - "F24": 0x6f, /* html:F24 (F24) -> linux:194 (KEY_F24) -> atset1:111 */ - "F3": 0x3d, /* html:F3 (F3) -> linux:61 (KEY_F3) -> atset1:61 */ - "F4": 0x3e, /* html:F4 (F4) -> linux:62 (KEY_F4) -> atset1:62 */ - "F5": 0x3f, /* html:F5 (F5) -> linux:63 (KEY_F5) -> atset1:63 */ - "F6": 0x40, /* html:F6 (F6) -> linux:64 (KEY_F6) -> atset1:64 */ - "F7": 0x41, /* html:F7 (F7) -> linux:65 (KEY_F7) -> atset1:65 */ - "F8": 0x42, /* html:F8 (F8) -> linux:66 (KEY_F8) -> atset1:66 */ - "F9": 0x43, /* html:F9 (F9) -> linux:67 (KEY_F9) -> atset1:67 */ - "Find": 0xe041, /* html:Find (Find) -> linux:136 (KEY_FIND) -> atset1:57409 */ - "Help": 0xe075, /* html:Help (Help) -> linux:138 (KEY_HELP) -> atset1:57461 */ - "Hiragana": 0x77, /* html:Hiragana (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */ - "Home": 0xe047, /* html:Home (Home) -> linux:102 (KEY_HOME) -> atset1:57415 */ - "Insert": 0xe052, /* html:Insert (Insert) -> linux:110 (KEY_INSERT) -> atset1:57426 */ - "IntlBackslash": 0x56, /* html:IntlBackslash (IntlBackslash) -> linux:86 (KEY_102ND) -> atset1:86 */ - "IntlRo": 0x73, /* html:IntlRo (IntlRo) -> linux:89 (KEY_RO) -> atset1:115 */ - "IntlYen": 0x7d, /* html:IntlYen (IntlYen) -> linux:124 (KEY_YEN) -> atset1:125 */ - "KanaMode": 0x70, /* html:KanaMode (KanaMode) -> linux:93 (KEY_KATAKANAHIRAGANA) -> atset1:112 */ - "Katakana": 0x78, /* html:Katakana (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */ - "KeyA": 0x1e, /* html:KeyA (KeyA) -> linux:30 (KEY_A) -> atset1:30 */ - "KeyB": 0x30, /* html:KeyB (KeyB) -> linux:48 (KEY_B) -> atset1:48 */ - "KeyC": 0x2e, /* html:KeyC (KeyC) -> linux:46 (KEY_C) -> atset1:46 */ - "KeyD": 0x20, /* html:KeyD (KeyD) -> linux:32 (KEY_D) -> atset1:32 */ - "KeyE": 0x12, /* html:KeyE (KeyE) -> linux:18 (KEY_E) -> atset1:18 */ - "KeyF": 0x21, /* html:KeyF (KeyF) -> linux:33 (KEY_F) -> atset1:33 */ - "KeyG": 0x22, /* html:KeyG (KeyG) -> linux:34 (KEY_G) -> atset1:34 */ - "KeyH": 0x23, /* html:KeyH (KeyH) -> linux:35 (KEY_H) -> atset1:35 */ - "KeyI": 0x17, /* html:KeyI (KeyI) -> linux:23 (KEY_I) -> atset1:23 */ - "KeyJ": 0x24, /* html:KeyJ (KeyJ) -> linux:36 (KEY_J) -> atset1:36 */ - "KeyK": 0x25, /* html:KeyK (KeyK) -> linux:37 (KEY_K) -> atset1:37 */ - "KeyL": 0x26, /* html:KeyL (KeyL) -> linux:38 (KEY_L) -> atset1:38 */ - "KeyM": 0x32, /* html:KeyM (KeyM) -> linux:50 (KEY_M) -> atset1:50 */ - "KeyN": 0x31, /* html:KeyN (KeyN) -> linux:49 (KEY_N) -> atset1:49 */ - "KeyO": 0x18, /* html:KeyO (KeyO) -> linux:24 (KEY_O) -> atset1:24 */ - "KeyP": 0x19, /* html:KeyP (KeyP) -> linux:25 (KEY_P) -> atset1:25 */ - "KeyQ": 0x10, /* html:KeyQ (KeyQ) -> linux:16 (KEY_Q) -> atset1:16 */ - "KeyR": 0x13, /* html:KeyR (KeyR) -> linux:19 (KEY_R) -> atset1:19 */ - "KeyS": 0x1f, /* html:KeyS (KeyS) -> linux:31 (KEY_S) -> atset1:31 */ - "KeyT": 0x14, /* html:KeyT (KeyT) -> linux:20 (KEY_T) -> atset1:20 */ - "KeyU": 0x16, /* html:KeyU (KeyU) -> linux:22 (KEY_U) -> atset1:22 */ - "KeyV": 0x2f, /* html:KeyV (KeyV) -> linux:47 (KEY_V) -> atset1:47 */ - "KeyW": 0x11, /* html:KeyW (KeyW) -> linux:17 (KEY_W) -> atset1:17 */ - "KeyX": 0x2d, /* html:KeyX (KeyX) -> linux:45 (KEY_X) -> atset1:45 */ - "KeyY": 0x15, /* html:KeyY (KeyY) -> linux:21 (KEY_Y) -> atset1:21 */ - "KeyZ": 0x2c, /* html:KeyZ (KeyZ) -> linux:44 (KEY_Z) -> atset1:44 */ - "Lang3": 0x78, /* html:Lang3 (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */ - "Lang4": 0x77, /* html:Lang4 (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */ - "Lang5": 0x76, /* html:Lang5 (Lang5) -> linux:85 (KEY_ZENKAKUHANKAKU) -> atset1:118 */ - "LaunchApp1": 0xe06b, /* html:LaunchApp1 (LaunchApp1) -> linux:157 (KEY_COMPUTER) -> atset1:57451 */ - "LaunchApp2": 0xe021, /* html:LaunchApp2 (LaunchApp2) -> linux:140 (KEY_CALC) -> atset1:57377 */ - "LaunchMail": 0xe06c, /* html:LaunchMail (LaunchMail) -> linux:155 (KEY_MAIL) -> atset1:57452 */ - "MediaPlayPause": 0xe022, /* html:MediaPlayPause (MediaPlayPause) -> linux:164 (KEY_PLAYPAUSE) -> atset1:57378 */ - "MediaSelect": 0xe06d, /* html:MediaSelect (MediaSelect) -> linux:226 (KEY_MEDIA) -> atset1:57453 */ - "MediaStop": 0xe024, /* html:MediaStop (MediaStop) -> linux:166 (KEY_STOPCD) -> atset1:57380 */ - "MediaTrackNext": 0xe019, /* html:MediaTrackNext (MediaTrackNext) -> linux:163 (KEY_NEXTSONG) -> atset1:57369 */ - "MediaTrackPrevious": 0xe010, /* html:MediaTrackPrevious (MediaTrackPrevious) -> linux:165 (KEY_PREVIOUSSONG) -> atset1:57360 */ - "MetaLeft": 0xe05b, /* html:MetaLeft (MetaLeft) -> linux:125 (KEY_LEFTMETA) -> atset1:57435 */ - "MetaRight": 0xe05c, /* html:MetaRight (MetaRight) -> linux:126 (KEY_RIGHTMETA) -> atset1:57436 */ - "Minus": 0xc, /* html:Minus (Minus) -> linux:12 (KEY_MINUS) -> atset1:12 */ - "NonConvert": 0x7b, /* html:NonConvert (NonConvert) -> linux:94 (KEY_MUHENKAN) -> atset1:123 */ - "NumLock": 0x45, /* html:NumLock (NumLock) -> linux:69 (KEY_NUMLOCK) -> atset1:69 */ - "Numpad0": 0x52, /* html:Numpad0 (Numpad0) -> linux:82 (KEY_KP0) -> atset1:82 */ - "Numpad1": 0x4f, /* html:Numpad1 (Numpad1) -> linux:79 (KEY_KP1) -> atset1:79 */ - "Numpad2": 0x50, /* html:Numpad2 (Numpad2) -> linux:80 (KEY_KP2) -> atset1:80 */ - "Numpad3": 0x51, /* html:Numpad3 (Numpad3) -> linux:81 (KEY_KP3) -> atset1:81 */ - "Numpad4": 0x4b, /* html:Numpad4 (Numpad4) -> linux:75 (KEY_KP4) -> atset1:75 */ - "Numpad5": 0x4c, /* html:Numpad5 (Numpad5) -> linux:76 (KEY_KP5) -> atset1:76 */ - "Numpad6": 0x4d, /* html:Numpad6 (Numpad6) -> linux:77 (KEY_KP6) -> atset1:77 */ - "Numpad7": 0x47, /* html:Numpad7 (Numpad7) -> linux:71 (KEY_KP7) -> atset1:71 */ - "Numpad8": 0x48, /* html:Numpad8 (Numpad8) -> linux:72 (KEY_KP8) -> atset1:72 */ - "Numpad9": 0x49, /* html:Numpad9 (Numpad9) -> linux:73 (KEY_KP9) -> atset1:73 */ - "NumpadAdd": 0x4e, /* html:NumpadAdd (NumpadAdd) -> linux:78 (KEY_KPPLUS) -> atset1:78 */ - "NumpadComma": 0x7e, /* html:NumpadComma (NumpadComma) -> linux:121 (KEY_KPCOMMA) -> atset1:126 */ - "NumpadDecimal": 0x53, /* html:NumpadDecimal (NumpadDecimal) -> linux:83 (KEY_KPDOT) -> atset1:83 */ - "NumpadDivide": 0xe035, /* html:NumpadDivide (NumpadDivide) -> linux:98 (KEY_KPSLASH) -> atset1:57397 */ - "NumpadEnter": 0xe01c, /* html:NumpadEnter (NumpadEnter) -> linux:96 (KEY_KPENTER) -> atset1:57372 */ - "NumpadEqual": 0x59, /* html:NumpadEqual (NumpadEqual) -> linux:117 (KEY_KPEQUAL) -> atset1:89 */ - "NumpadMultiply": 0x37, /* html:NumpadMultiply (NumpadMultiply) -> linux:55 (KEY_KPASTERISK) -> atset1:55 */ - "NumpadParenLeft": 0xe076, /* html:NumpadParenLeft (NumpadParenLeft) -> linux:179 (KEY_KPLEFTPAREN) -> atset1:57462 */ - "NumpadParenRight": 0xe07b, /* html:NumpadParenRight (NumpadParenRight) -> linux:180 (KEY_KPRIGHTPAREN) -> atset1:57467 */ - "NumpadSubtract": 0x4a, /* html:NumpadSubtract (NumpadSubtract) -> linux:74 (KEY_KPMINUS) -> atset1:74 */ - "Open": 0x64, /* html:Open (Open) -> linux:134 (KEY_OPEN) -> atset1:100 */ - "PageDown": 0xe051, /* html:PageDown (PageDown) -> linux:109 (KEY_PAGEDOWN) -> atset1:57425 */ - "PageUp": 0xe049, /* html:PageUp (PageUp) -> linux:104 (KEY_PAGEUP) -> atset1:57417 */ - "Paste": 0x65, /* html:Paste (Paste) -> linux:135 (KEY_PASTE) -> atset1:101 */ - "Pause": 0xe046, /* html:Pause (Pause) -> linux:119 (KEY_PAUSE) -> atset1:57414 */ - "Period": 0x34, /* html:Period (Period) -> linux:52 (KEY_DOT) -> atset1:52 */ - "Power": 0xe05e, /* html:Power (Power) -> linux:116 (KEY_POWER) -> atset1:57438 */ - "PrintScreen": 0x54, /* html:PrintScreen (PrintScreen) -> linux:99 (KEY_SYSRQ) -> atset1:84 */ - "Props": 0xe006, /* html:Props (Props) -> linux:130 (KEY_PROPS) -> atset1:57350 */ - "Quote": 0x28, /* html:Quote (Quote) -> linux:40 (KEY_APOSTROPHE) -> atset1:40 */ - "ScrollLock": 0x46, /* html:ScrollLock (ScrollLock) -> linux:70 (KEY_SCROLLLOCK) -> atset1:70 */ - "Semicolon": 0x27, /* html:Semicolon (Semicolon) -> linux:39 (KEY_SEMICOLON) -> atset1:39 */ - "ShiftLeft": 0x2a, /* html:ShiftLeft (ShiftLeft) -> linux:42 (KEY_LEFTSHIFT) -> atset1:42 */ - "ShiftRight": 0x36, /* html:ShiftRight (ShiftRight) -> linux:54 (KEY_RIGHTSHIFT) -> atset1:54 */ - "Slash": 0x35, /* html:Slash (Slash) -> linux:53 (KEY_SLASH) -> atset1:53 */ - "Sleep": 0xe05f, /* html:Sleep (Sleep) -> linux:142 (KEY_SLEEP) -> atset1:57439 */ - "Space": 0x39, /* html:Space (Space) -> linux:57 (KEY_SPACE) -> atset1:57 */ - "Suspend": 0xe025, /* html:Suspend (Suspend) -> linux:205 (KEY_SUSPEND) -> atset1:57381 */ - "Tab": 0xf, /* html:Tab (Tab) -> linux:15 (KEY_TAB) -> atset1:15 */ - "Undo": 0xe007, /* html:Undo (Undo) -> linux:131 (KEY_UNDO) -> atset1:57351 */ - "WakeUp": 0xe063, /* html:WakeUp (WakeUp) -> linux:143 (KEY_WAKEUP) -> atset1:57443 */ -}; diff --git a/kasmweb/core/rfb.js b/kasmweb/core/rfb.js deleted file mode 100644 index 91c11b0..0000000 --- a/kasmweb/core/rfb.js +++ /dev/null @@ -1,2293 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - * - */ - -import * as Log from './util/logging.js'; -import { decodeUTF8 } from './util/strings.js'; -import { supportsCursorURIs, isTouchDevice } from './util/browser.js'; -import { dragThreshold } from './util/browser.js'; -import EventTargetMixin from './util/eventtarget.js'; -import Display from "./display.js"; -import Keyboard from "./input/keyboard.js"; -import Mouse from "./input/mouse.js"; -import Cursor from "./util/cursor.js"; -import Websock from "./websock.js"; -import DES from "./des.js"; -import KeyTable from "./input/keysym.js"; -import XtScancode from "./input/xtscancodes.js"; -import { encodings } from "./encodings.js"; -import "./util/polyfill.js"; - -import RawDecoder from "./decoders/raw.js"; -import CopyRectDecoder from "./decoders/copyrect.js"; -import RREDecoder from "./decoders/rre.js"; -import HextileDecoder from "./decoders/hextile.js"; -import TightDecoder from "./decoders/tight.js"; -import TightPNGDecoder from "./decoders/tightpng.js"; - -// How many seconds to wait for a disconnect to finish -const DISCONNECT_TIMEOUT = 3; -const DEFAULT_BACKGROUND = 'rgb(40, 40, 40)'; - -var _videoQuality = 2; -var _enableWebP = false; - -export default class RFB extends EventTargetMixin { - constructor(target, url, options) { - if (!target) { - throw new Error("Must specify target"); - } - if (!url) { - throw new Error("Must specify URL"); - } - - super(); - - this._target = target; - this._url = url; - - // Connection details - options = options || {}; - this._rfb_credentials = options.credentials || {}; - this._shared = 'shared' in options ? !!options.shared : true; - this._repeaterID = options.repeaterID || ''; - this._showDotCursor = options.showDotCursor || false; - - // Internal state - this._rfb_connection_state = ''; - this._rfb_init_state = ''; - this._rfb_auth_scheme = ''; - this._rfb_clean_disconnect = true; - - // Server capabilities - this._rfb_version = 0; - this._rfb_max_version = 3.8; - this._rfb_tightvnc = false; - this._rfb_xvp_ver = 0; - - this._fb_width = 0; - this._fb_height = 0; - - this._fb_name = ""; - - this._capabilities = { power: false }; - - this._supportsFence = false; - - this._supportsContinuousUpdates = false; - this._enabledContinuousUpdates = false; - - this._supportsSetDesktopSize = false; - this._screen_id = 0; - this._screen_flags = 0; - - this._qemuExtKeyEventSupported = false; - - // kasm defaults - this._jpegVideoQuality = 5; - this._webpVideoQuality = 5; - this._treatLossless = 7; - this._preferBandwidth = true; - this._dynamicQualityMin = 3; - this._dynamicQualityMax = 9; - this._videoArea = 65; - this._videoTime = 5; - this._videoOutTime = 3; - this._videoScaling = 2; - this._frameRate = 30; - this._maxVideoResolutionX = 960; - this._maxVideoResolutionY = 540; - - // Internal objects - this._sock = null; // Websock object - this._display = null; // Display object - this._flushing = false; // Display flushing state - this._keyboard = null; // Keyboard input handler object - this._mouse = null; // Mouse input handler object - - // Timers - this._disconnTimer = null; // disconnection timer - this._resizeTimeout = null; // resize rate limiting - - // Decoder states - this._decoders = {}; - - this._FBU = { - rects: 0, - x: 0, - y: 0, - width: 0, - height: 0, - encoding: null, - }; - - // Mouse state - this._mouse_buttonMask = 0; - this._mouse_arr = []; - this._viewportDragging = false; - this._viewportDragPos = {}; - this._viewportHasMoved = false; - - // Bound event handlers - this._eventHandlers = { - focusCanvas: this._focusCanvas.bind(this), - windowResize: this._windowResize.bind(this), - firstClick: this._firstClick.bind(this), - firstTouch: this._firstTouch.bind(this) - }; - - // main setup - Log.Debug(">> RFB.constructor"); - - // Create DOM elements - this._screen = document.createElement('div'); - this._screen.style.display = 'flex'; - this._screen.style.width = '100%'; - this._screen.style.height = '100%'; - this._screen.style.overflow = 'auto'; - this._screen.style.background = DEFAULT_BACKGROUND; - this._canvas = document.createElement('canvas'); - this._canvas.style.margin = 'auto'; - // Some browsers add an outline on focus - this._canvas.style.outline = 'none'; - // IE miscalculates width without this :( - this._canvas.style.flexShrink = '0'; - this._canvas.width = 0; - this._canvas.height = 0; - this._canvas.tabIndex = -1; - this._screen.appendChild(this._canvas); - - // Cursor - this._cursor = new Cursor(); - - // XXX: TightVNC 2.8.11 sends no cursor at all until Windows changes - // it. Result: no cursor at all until a window border or an edit field - // is hit blindly. But there are also VNC servers that draw the cursor - // in the framebuffer and don't send the empty local cursor. There is - // no way to satisfy both sides. - // - // The spec is unclear on this "initial cursor" issue. Many other - // viewers (TigerVNC, RealVNC, Remmina) display an arrow as the - // initial cursor instead. - this._cursorImage = RFB.cursors.none; - - // populate decoder array with objects - this._decoders[encodings.encodingRaw] = new RawDecoder(); - this._decoders[encodings.encodingCopyRect] = new CopyRectDecoder(); - this._decoders[encodings.encodingRRE] = new RREDecoder(); - this._decoders[encodings.encodingHextile] = new HextileDecoder(); - this._decoders[encodings.encodingTight] = new TightDecoder(); - this._decoders[encodings.encodingTightPNG] = new TightPNGDecoder(); - - // NB: nothing that needs explicit teardown should be done - // before this point, since this can throw an exception - try { - this._display = new Display(this._canvas); - } catch (exc) { - Log.Error("Display exception: " + exc); - throw exc; - } - this._display.onflush = this._onFlush.bind(this); - this._display.clear(); - - this._keyboard = new Keyboard(this._canvas); - this._keyboard.onkeyevent = this._handleKeyEvent.bind(this); - - this._mouse = new Mouse(this._canvas); - this._mouse.onmousebutton = this._handleMouseButton.bind(this); - this._mouse.onmousemove = this._handleMouseMove.bind(this); - - this._sock = new Websock(); - this._sock.on('message', this._handle_message.bind(this)); - this._sock.on('open', () => { - if ((this._rfb_connection_state === 'connecting') && - (this._rfb_init_state === '')) { - this._rfb_init_state = 'ProtocolVersion'; - Log.Debug("Starting VNC handshake"); - } else { - this._fail("Unexpected server connection while " + - this._rfb_connection_state); - } - }); - this._sock.on('close', (e) => { - Log.Debug("WebSocket on-close event"); - let msg = ""; - if (e.code) { - msg = "(code: " + e.code; - if (e.reason) { - msg += ", reason: " + e.reason; - } - msg += ")"; - } - switch (this._rfb_connection_state) { - case 'connecting': - this._fail("Connection closed " + msg); - break; - case 'connected': - // Handle disconnects that were initiated server-side - this._updateConnectionState('disconnecting'); - this._updateConnectionState('disconnected'); - break; - case 'disconnecting': - // Normal disconnection path - this._updateConnectionState('disconnected'); - break; - case 'disconnected': - this._fail("Unexpected server disconnect " + - "when already disconnected " + msg); - break; - default: - this._fail("Unexpected server disconnect before connecting " + - msg); - break; - } - this._sock.off('close'); - }); - this._sock.on('error', e => Log.Warn("WebSocket on-error event")); - - // Slight delay of the actual connection so that the caller has - // time to set up callbacks - setTimeout(this._updateConnectionState.bind(this, 'connecting')); - - Log.Debug("<< RFB.constructor"); - - // ===== PROPERTIES ===== - - this.dragViewport = false; - this.focusOnClick = true; - this.sentEventsCounter = 0; //tracks the number of events sent to the server - - this._viewOnly = false; - this._clipViewport = false; - this._scaleViewport = false; - this._resizeSession = false; - } - - // ===== PROPERTIES ===== - - get videoQuality() { return this._videoQuality; } - set videoQuality(quality) { this._videoQuality = quality; } - - get enableWebP() { return this._enableWebP; } - set enableWebP(enabled) { this._enableWebP = enabled; } - - get jpegVideoQuality() { return this._jpegVideoQuality; } - set jpegVideoQuality(val) { this._jpegVideoQuality = val; } - - get webpVideoQuality() { return this._webpVideoQuality; } - set webpVideoQuality(val) { this._webpVideoQuality = val; } - - get treatLossless() { return this._treatLossless; } - set treatLossless(val) { this._treatLossless = val; } - - get preferBandwidth() { return this._preferBandwidth; } - set preferBandwidth(val) { this._preferBandwidth = val; } - - get dynamicQualityMin() { return this._dynamicQualityMin; } - set dynamicQualityMin(val) { this._dynamicQualityMin = val; } - - get dynamicQualityMax() { return this._dynamicQualityMax; } - set dynamicQualityMax(val) { this._dynamicQualityMax = val; } - - get videoArea() { return this._videoArea; } - set videoArea(val) { this._videoArea = val; } - - get videoTime() { return this._videoTime; } - set videoTime(val) { this._videoTime = val; } - - get videoOutTime() { return this._videoOutTime; } - set videoOutTime(val) { this._videoOutTime = val; } - - get videoScaling() { return this._videoScaling; } - set videoScaling(val) { this._videoScaling = val; } - - get frameRate() { return this._frameRate; } - set frameRate(val) { this._frameRate = val; } - - get maxVideoResolutionX() { return this._maxVideoResolutionX; } - set maxVideoResolutionX(val) { this._maxVideoResolutionX = val; } - - get maxVideoResolutionY() { return this._maxVideoResolutionY; } - set maxVideoResolutionY(val) { this._maxVideoResolutionY = val; } - - get viewOnly() { return this._viewOnly; } - set viewOnly(viewOnly) { - this._viewOnly = viewOnly; - - if (this._rfb_connection_state === "connecting" || - this._rfb_connection_state === "connected") { - if (viewOnly) { - this._keyboard.ungrab(); - this._mouse.ungrab(); - } else { - this._keyboard.grab(); - this._mouse.grab(); - } - } - } - - get capabilities() { return this._capabilities; } - - get touchButton() { return this._mouse.touchButton; } - set touchButton(button) { this._mouse.touchButton = button; } - - get clipViewport() { return this._clipViewport; } - set clipViewport(viewport) { - this._clipViewport = viewport; - this._updateClip(); - } - - get scaleViewport() { return this._scaleViewport; } - set scaleViewport(scale) { - this._scaleViewport = scale; - // Scaling trumps clipping, so we may need to adjust - // clipping when enabling or disabling scaling - if (scale && this._clipViewport) { - this._updateClip(); - } - this._updateScale(); - if (!scale && this._clipViewport) { - this._updateClip(); - } - } - - get resizeSession() { return this._resizeSession; } - set resizeSession(resize) { - this._resizeSession = resize; - if (resize) { - this._requestRemoteResize(); - this.scaleViewport = true; - } - } - - get showDotCursor() { return this._showDotCursor; } - set showDotCursor(show) { - this._showDotCursor = show; - this._refreshCursor(); - } - - get background() { return this._screen.style.background; } - set background(cssValue) { this._screen.style.background = cssValue; } - - // ===== PUBLIC METHODS ===== - - disconnect() { - this._updateConnectionState('disconnecting'); - this._sock.off('error'); - this._sock.off('message'); - this._sock.off('open'); - } - - sendCredentials(creds) { - this._rfb_credentials = creds; - setTimeout(this._init_msg.bind(this), 0); - } - - sendCtrlAltDel() { - if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; } - Log.Info("Sending Ctrl-Alt-Del"); - - this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); - this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true); - this.sendKey(KeyTable.XK_Delete, "Delete", true); - this.sendKey(KeyTable.XK_Delete, "Delete", false); - this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); - this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); - } - - machineShutdown() { - this._xvpOp(1, 2); - } - - machineReboot() { - this._xvpOp(1, 3); - } - - machineReset() { - this._xvpOp(1, 4); - } - - // Send a key press. If 'down' is not specified then send a down key - // followed by an up key. - sendKey(keysym, code, down) { - if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; } - - this.sentEventsCounter+=1; - - if (down === undefined) { - this.sendKey(keysym, code, true); - this.sendKey(keysym, code, false); - return; - } - - const scancode = XtScancode[code]; - - if (this._qemuExtKeyEventSupported && scancode) { - // 0 is NoSymbol - keysym = keysym || 0; - - Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode); - - RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode); - } else { - if (!keysym) { - return; - } - Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym); - RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0); - } - } - - focus() { - this._canvas.focus(); - } - - blur() { - this._canvas.blur(); - } - - clipboardPasteFrom(text) { - if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; } - this.sentEventsCounter+=1; - RFB.messages.clientCutText(this._sock, text); - } - - requestBottleneckStats() { - RFB.messages.requestStats(this._sock); - } - - // ===== PRIVATE METHODS ===== - - _connect() { - Log.Debug(">> RFB.connect"); - - Log.Info("connecting to " + this._url); - - try { - // WebSocket.onopen transitions to the RFB init states - this._sock.open(this._url, ['binary']); - this.sentEventsCounter+=1; - } catch (e) { - if (e.name === 'SyntaxError') { - this._fail("Invalid host or port (" + e + ")"); - } else { - this._fail("Error when opening socket (" + e + ")"); - } - } - - // Make our elements part of the page - this._target.appendChild(this._screen); - - this._cursor.attach(this._canvas); - this._refreshCursor(); - - // Monitor size changes of the screen - // FIXME: Use ResizeObserver, or hidden overflow - window.addEventListener('resize', this._eventHandlers.windowResize); - - // Always grab focus on some kind of click event - this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas); - this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas); - this._canvas.addEventListener("mousedown", this._eventHandlers.firstClick); - this._canvas.addEventListener("touchstart", this._eventHandlers.firstTouch); - - Log.Debug("<< RFB.connect"); - } - - _disconnect() { - Log.Debug(">> RFB.disconnect"); - this._cursor.detach(); - this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas); - this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas); - window.removeEventListener('resize', this._eventHandlers.windowResize); - this._keyboard.ungrab(); - this._mouse.ungrab(); - this._sock.close(); - try { - this._target.removeChild(this._screen); - } catch (e) { - if (e.name === 'NotFoundError') { - // Some cases where the initial connection fails - // can disconnect before the _screen is created - } else { - throw e; - } - } - clearTimeout(this._resizeTimeout); - Log.Debug("<< RFB.disconnect"); - } - - _focusCanvas(event) { - // Respect earlier handlers' request to not do side-effects - if (event.defaultPrevented) { - return; - } - - if (!this.focusOnClick) { - return; - } - - this.focus(); - } - - _windowResize(event) { - // If the window resized then our screen element might have - // as well. Update the viewport dimensions. - window.requestAnimationFrame(() => { - this._updateClip(); - this._updateScale(); - }); - - if (this._resizeSession) { - // Request changing the resolution of the remote display to - // the size of the local browser viewport. - - // In order to not send multiple requests before the browser-resize - // is finished we wait 0.5 seconds before sending the request. - clearTimeout(this._resizeTimeout); - this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this), 500); - } - } - - _firstClick(event) { - parent.postMessage({ action: 'firstClick', value: null}, '*' ); - this._canvas.removeEventListener("mousedown", this._eventHandlers.firstClick); - } - - _firstTouch(event) { - parent.postMessage({ action: 'firstTouch', value: null}, '*' ); - this._canvas.removeEventListener("touchstart", this._eventHandlers.firstTouch); - } - - // Update state of clipping in Display object, and make sure the - // configured viewport matches the current screen size - _updateClip() { - const cur_clip = this._display.clipViewport; - let new_clip = this._clipViewport; - - if (this._scaleViewport) { - // Disable viewport clipping if we are scaling - new_clip = false; - } - - if (cur_clip !== new_clip) { - this._display.clipViewport = new_clip; - } - - if (new_clip) { - // When clipping is enabled, the screen is limited to - // the size of the container. - const size = this._screenSize(); - this._display.viewportChangeSize(size.w, size.h); - this._fixScrollbars(); - } - } - - _updateScale() { - if (!this._scaleViewport) { - this._display.scale = 1.0; - } else { - const size = this._screenSize(false); - this._display.autoscale(size.w, size.h); - } - this._fixScrollbars(); - } - - // Requests a change of remote desktop size. This message is an extension - // and may only be sent if we have received an ExtendedDesktopSize message - _requestRemoteResize() { - clearTimeout(this._resizeTimeout); - this._resizeTimeout = null; - - if (!this._resizeSession || this._viewOnly || - !this._supportsSetDesktopSize) { - return; - } - - const size = this._screenSize(); - RFB.messages.setDesktopSize(this._sock, - Math.floor(size.w), Math.floor(size.h), - this._screen_id, this._screen_flags); - - this.sentEventsCounter+=1; - - Log.Debug('Requested new desktop size: ' + - size.w + 'x' + size.h); - } - - // Gets the the size of the available screen - _screenSize (limited) { - if (limited === undefined) { - limited = true; - } - var x = this._screen.offsetWidth; - var y = this._screen.offsetHeight; - try { - if (x > 1280 && limited && this.videoQuality == 1) { - var ratio = y / x; - console.log(ratio); - x = 1280; - y = x * ratio; - } - else if (limited && this.videoQuality == 0){ - x = 1280; - y = 720; - } - } catch (err) { - console.log(err); - } - - return { w: x, - h: y }; - } - - _fixScrollbars() { - // This is a hack because Chrome screws up the calculation - // for when scrollbars are needed. So to fix it we temporarily - // toggle them off and on. - const orig = this._screen.style.overflow; - this._screen.style.overflow = 'hidden'; - // Force Chrome to recalculate the layout by asking for - // an element's dimensions - this._screen.getBoundingClientRect(); - this._screen.style.overflow = orig; - } - - /* - * Connection states: - * connecting - * connected - * disconnecting - * disconnected - permanent state - */ - _updateConnectionState(state) { - const oldstate = this._rfb_connection_state; - - if (state === oldstate) { - Log.Debug("Already in state '" + state + "', ignoring"); - return; - } - - // The 'disconnected' state is permanent for each RFB object - if (oldstate === 'disconnected') { - Log.Error("Tried changing state of a disconnected RFB object"); - return; - } - - // Ensure proper transitions before doing anything - switch (state) { - case 'connected': - if (oldstate !== 'connecting') { - Log.Error("Bad transition to connected state, " + - "previous connection state: " + oldstate); - return; - } - break; - - case 'disconnected': - if (oldstate !== 'disconnecting') { - Log.Error("Bad transition to disconnected state, " + - "previous connection state: " + oldstate); - return; - } - break; - - case 'connecting': - if (oldstate !== '') { - Log.Error("Bad transition to connecting state, " + - "previous connection state: " + oldstate); - return; - } - break; - - case 'disconnecting': - if (oldstate !== 'connected' && oldstate !== 'connecting') { - Log.Error("Bad transition to disconnecting state, " + - "previous connection state: " + oldstate); - return; - } - break; - - default: - Log.Error("Unknown connection state: " + state); - return; - } - - // State change actions - - this._rfb_connection_state = state; - - Log.Debug("New state '" + state + "', was '" + oldstate + "'."); - - if (this._disconnTimer && state !== 'disconnecting') { - Log.Debug("Clearing disconnect timer"); - clearTimeout(this._disconnTimer); - this._disconnTimer = null; - - // make sure we don't get a double event - this._sock.off('close'); - } - - switch (state) { - case 'connecting': - this._connect(); - break; - - case 'connected': - this.dispatchEvent(new CustomEvent("connect", { detail: {} })); - break; - - case 'disconnecting': - this._disconnect(); - - this._disconnTimer = setTimeout(() => { - Log.Error("Disconnection timed out."); - this._updateConnectionState('disconnected'); - }, DISCONNECT_TIMEOUT * 1000); - break; - - case 'disconnected': - this.dispatchEvent(new CustomEvent( - "disconnect", { detail: - { clean: this._rfb_clean_disconnect } })); - break; - } - } - - /* Print errors and disconnect - * - * The parameter 'details' is used for information that - * should be logged but not sent to the user interface. - */ - _fail(details) { - switch (this._rfb_connection_state) { - case 'disconnecting': - Log.Error("Failed when disconnecting: " + details); - break; - case 'connected': - Log.Error("Failed while connected: " + details); - break; - case 'connecting': - Log.Error("Failed when connecting: " + details); - break; - default: - Log.Error("RFB failure: " + details); - break; - } - this._rfb_clean_disconnect = false; //This is sent to the UI - - // Transition to disconnected without waiting for socket to close - this._updateConnectionState('disconnecting'); - this._updateConnectionState('disconnected'); - - return false; - } - - _setCapability(cap, val) { - this._capabilities[cap] = val; - this.dispatchEvent(new CustomEvent("capabilities", - { detail: { capabilities: this._capabilities } })); - } - - _handle_message() { - if (this._sock.rQlen === 0) { - Log.Warn("handle_message called on an empty receive queue"); - return; - } - - switch (this._rfb_connection_state) { - case 'disconnected': - Log.Error("Got data while disconnected"); - break; - case 'connected': - while (true) { - if (this._flushing) { - break; - } - if (!this._normal_msg()) { - break; - } - if (this._sock.rQlen === 0) { - break; - } - } - break; - default: - this._init_msg(); - break; - } - } - - _handleKeyEvent(keysym, code, down) { - this.sendKey(keysym, code, down); - } - - _handleMouseButton(x, y, down, bmask) { - if (down) { - this._mouse_buttonMask |= bmask; - } else { - this._mouse_buttonMask &= ~bmask; - } - - if (this.dragViewport) { - if (down && !this._viewportDragging) { - this._viewportDragging = true; - this._viewportDragPos = {'x': x, 'y': y}; - this._viewportHasMoved = false; - - // Skip sending mouse events - return; - } else { - this._viewportDragging = false; - - // If we actually performed a drag then we are done - // here and should not send any mouse events - if (this._viewportHasMoved) { - return; - } - - // Otherwise we treat this as a mouse click event. - // Send the button down event here, as the button up - // event is sent at the end of this function. - this.sentEventsCounter+=1; - RFB.messages.pointerEvent(this._sock, - this._display.absX(x), - this._display.absY(y), - bmask); - } - } - - if (this._viewOnly) { return; } // View only, skip mouse events - - if (this._rfb_connection_state !== 'connected') { return; } - this.sentEventsCounter+=1; - RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask); - } - - _handleMouseMove(x, y) { - if (this._viewportDragging) { - const deltaX = this._viewportDragPos.x - x; - const deltaY = this._viewportDragPos.y - y; - - if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold || - Math.abs(deltaY) > dragThreshold)) { - this._viewportHasMoved = true; - - this._viewportDragPos = {'x': x, 'y': y}; - this._display.viewportChangePos(deltaX, deltaY); - } - - // Skip sending mouse events - return; - } - - if (this._viewOnly) { return; } // View only, skip mouse events - - if (this._rfb_connection_state !== 'connected') { return; } - RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask); - } - - // Message Handlers - - _negotiate_protocol_version() { - if (this._sock.rQlen < 12) { - return this._fail("Received incomplete protocol version."); - } - - const sversion = this._sock.rQshiftStr(12).substr(4, 7); - Log.Info("Server ProtocolVersion: " + sversion); - let is_repeater = 0; - switch (sversion) { - case "000.000": // UltraVNC repeater - is_repeater = 1; - break; - case "003.003": - case "003.006": // UltraVNC - case "003.889": // Apple Remote Desktop - this._rfb_version = 3.3; - break; - case "003.007": - this._rfb_version = 3.7; - break; - case "003.008": - case "004.000": // Intel AMT KVM - case "004.001": // RealVNC 4.6 - case "005.000": // RealVNC 5.3 - this._rfb_version = 3.8; - break; - default: - return this._fail("Invalid server version " + sversion); - } - - if (is_repeater) { - let repeaterID = "ID:" + this._repeaterID; - while (repeaterID.length < 250) { - repeaterID += "\0"; - } - this._sock.send_string(repeaterID); - return true; - } - - if (this._rfb_version > this._rfb_max_version) { - this._rfb_version = this._rfb_max_version; - } - - const cversion = "00" + parseInt(this._rfb_version, 10) + - ".00" + ((this._rfb_version * 10) % 10); - this._sock.send_string("RFB " + cversion + "\n"); - Log.Debug('Sent ProtocolVersion: ' + cversion); - - this._rfb_init_state = 'Security'; - } - - _negotiate_security() { - // Polyfill since IE and PhantomJS doesn't have - // TypedArray.includes() - function includes(item, array) { - for (let i = 0; i < array.length; i++) { - if (array[i] === item) { - return true; - } - } - return false; - } - - if (this._rfb_version >= 3.7) { - // Server sends supported list, client decides - const num_types = this._sock.rQshift8(); - if (this._sock.rQwait("security type", num_types, 1)) { return false; } - - if (num_types === 0) { - return this._handle_security_failure("no security types"); - } - - const types = this._sock.rQshiftBytes(num_types); - Log.Debug("Server security types: " + types); - - // Look for each auth in preferred order - this._rfb_auth_scheme = 0; - if (includes(1, types)) { - this._rfb_auth_scheme = 1; // None - } else if (includes(22, types)) { - this._rfb_auth_scheme = 22; // XVP - } else if (includes(16, types)) { - this._rfb_auth_scheme = 16; // Tight - } else if (includes(2, types)) { - this._rfb_auth_scheme = 2; // VNC Auth - } else { - return this._fail("Unsupported security types (types: " + types + ")"); - } - - this._sock.send([this._rfb_auth_scheme]); - } else { - // Server decides - if (this._sock.rQwait("security scheme", 4)) { return false; } - this._rfb_auth_scheme = this._sock.rQshift32(); - } - - this._rfb_init_state = 'Authentication'; - Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme); - - return this._init_msg(); // jump to authentication - } - - /* - * Get the security failure reason if sent from the server and - * send the 'securityfailure' event. - * - * - The optional parameter context can be used to add some extra - * context to the log output. - * - * - The optional parameter security_result_status can be used to - * add a custom status code to the event. - */ - _handle_security_failure(context, security_result_status) { - - if (typeof context === 'undefined') { - context = ""; - } else { - context = " on " + context; - } - - if (typeof security_result_status === 'undefined') { - security_result_status = 1; // fail - } - - if (this._sock.rQwait("reason length", 4)) { - return false; - } - const strlen = this._sock.rQshift32(); - let reason = ""; - - if (strlen > 0) { - if (this._sock.rQwait("reason", strlen, 8)) { return false; } - reason = this._sock.rQshiftStr(strlen); - } - - if (reason !== "") { - this.dispatchEvent(new CustomEvent( - "securityfailure", - { detail: { status: security_result_status, reason: reason } })); - - return this._fail("Security negotiation failed" + context + - " (reason: " + reason + ")"); - } else { - this.dispatchEvent(new CustomEvent( - "securityfailure", - { detail: { status: security_result_status } })); - - return this._fail("Security negotiation failed" + context); - } - } - - // authentication - _negotiate_xvp_auth() { - if (!this._rfb_credentials.username || - !this._rfb_credentials.password || - !this._rfb_credentials.target) { - this.dispatchEvent(new CustomEvent( - "credentialsrequired", - { detail: { types: ["username", "password", "target"] } })); - return false; - } - - const xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) + - String.fromCharCode(this._rfb_credentials.target.length) + - this._rfb_credentials.username + - this._rfb_credentials.target; - this._sock.send_string(xvp_auth_str); - this._rfb_auth_scheme = 2; - return this._negotiate_authentication(); - } - - _negotiate_std_vnc_auth() { - if (this._sock.rQwait("auth challenge", 16)) { return false; } - - // KasmVNC uses basic Auth, clear the VNC password, which is not used - this._rfb_credentials.password = ""; - - // TODO(directxman12): make genDES not require an Array - const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16)); - const response = RFB.genDES(this._rfb_credentials.password, challenge); - this._sock.send(response); - this._rfb_init_state = "SecurityResult"; - return true; - } - - _negotiate_tight_tunnels(numTunnels) { - const clientSupportedTunnelTypes = { - 0: { vendor: 'TGHT', signature: 'NOTUNNEL' } - }; - const serverSupportedTunnelTypes = {}; - // receive tunnel capabilities - for (let i = 0; i < numTunnels; i++) { - const cap_code = this._sock.rQshift32(); - const cap_vendor = this._sock.rQshiftStr(4); - const cap_signature = this._sock.rQshiftStr(8); - serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature }; - } - - Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes); - - // Siemens touch panels have a VNC server that supports NOTUNNEL, - // but forgets to advertise it. Try to detect such servers by - // looking for their custom tunnel type. - if (serverSupportedTunnelTypes[1] && - (serverSupportedTunnelTypes[1].vendor === "SICR") && - (serverSupportedTunnelTypes[1].signature === "SCHANNEL")) { - Log.Debug("Detected Siemens server. Assuming NOTUNNEL support."); - serverSupportedTunnelTypes[0] = { vendor: 'TGHT', signature: 'NOTUNNEL' }; - } - - // choose the notunnel type - if (serverSupportedTunnelTypes[0]) { - if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor || - serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) { - return this._fail("Client's tunnel type had the incorrect " + - "vendor or signature"); - } - Log.Debug("Selected tunnel type: " + clientSupportedTunnelTypes[0]); - this._sock.send([0, 0, 0, 0]); // use NOTUNNEL - return false; // wait until we receive the sub auth count to continue - } else { - return this._fail("Server wanted tunnels, but doesn't support " + - "the notunnel type"); - } - } - - _negotiate_tight_auth() { - if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation - if (this._sock.rQwait("num tunnels", 4)) { return false; } - const numTunnels = this._sock.rQshift32(); - if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; } - - this._rfb_tightvnc = true; - - if (numTunnels > 0) { - this._negotiate_tight_tunnels(numTunnels); - return false; // wait until we receive the sub auth to continue - } - } - - // second pass, do the sub-auth negotiation - if (this._sock.rQwait("sub auth count", 4)) { return false; } - const subAuthCount = this._sock.rQshift32(); - if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected - this._rfb_init_state = 'SecurityResult'; - return true; - } - - if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; } - - const clientSupportedTypes = { - 'STDVNOAUTH__': 1, - 'STDVVNCAUTH_': 2 - }; - - const serverSupportedTypes = []; - - for (let i = 0; i < subAuthCount; i++) { - this._sock.rQshift32(); // capNum - const capabilities = this._sock.rQshiftStr(12); - serverSupportedTypes.push(capabilities); - } - - Log.Debug("Server Tight authentication types: " + serverSupportedTypes); - - for (let authType in clientSupportedTypes) { - if (serverSupportedTypes.indexOf(authType) != -1) { - this._sock.send([0, 0, 0, clientSupportedTypes[authType]]); - Log.Debug("Selected authentication type: " + authType); - - switch (authType) { - case 'STDVNOAUTH__': // no auth - this._rfb_init_state = 'SecurityResult'; - return true; - case 'STDVVNCAUTH_': // VNC auth - this._rfb_auth_scheme = 2; - return this._init_msg(); - default: - return this._fail("Unsupported tiny auth scheme " + - "(scheme: " + authType + ")"); - } - } - } - - return this._fail("No supported sub-auth types!"); - } - - _negotiate_authentication() { - switch (this._rfb_auth_scheme) { - case 0: // connection failed - return this._handle_security_failure("authentication scheme"); - - case 1: // no auth - if (this._rfb_version >= 3.8) { - this._rfb_init_state = 'SecurityResult'; - return true; - } - this._rfb_init_state = 'ClientInitialisation'; - return this._init_msg(); - - case 22: // XVP auth - return this._negotiate_xvp_auth(); - - case 2: // VNC authentication - return this._negotiate_std_vnc_auth(); - - case 16: // TightVNC Security Type - return this._negotiate_tight_auth(); - - default: - return this._fail("Unsupported auth scheme (scheme: " + - this._rfb_auth_scheme + ")"); - } - } - - _handle_security_result() { - if (this._sock.rQwait('VNC auth response ', 4)) { return false; } - - const status = this._sock.rQshift32(); - - if (status === 0) { // OK - this._rfb_init_state = 'ClientInitialisation'; - Log.Debug('Authentication OK'); - return this._init_msg(); - } else { - if (this._rfb_version >= 3.8) { - return this._handle_security_failure("security result", status); - } else { - this.dispatchEvent(new CustomEvent( - "securityfailure", - { detail: { status: status } })); - - return this._fail("Security handshake failed"); - } - } - } - - _negotiate_server_init() { - if (this._sock.rQwait("server initialization", 24)) { return false; } - - /* Screen size */ - const width = this._sock.rQshift16(); - const height = this._sock.rQshift16(); - - /* PIXEL_FORMAT */ - const bpp = this._sock.rQshift8(); - const depth = this._sock.rQshift8(); - const big_endian = this._sock.rQshift8(); - const true_color = this._sock.rQshift8(); - - const red_max = this._sock.rQshift16(); - const green_max = this._sock.rQshift16(); - const blue_max = this._sock.rQshift16(); - const red_shift = this._sock.rQshift8(); - const green_shift = this._sock.rQshift8(); - const blue_shift = this._sock.rQshift8(); - this._sock.rQskipBytes(3); // padding - - // NB(directxman12): we don't want to call any callbacks or print messages until - // *after* we're past the point where we could backtrack - - /* Connection name/title */ - const name_length = this._sock.rQshift32(); - if (this._sock.rQwait('server init name', name_length, 24)) { return false; } - this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length)); - - if (this._rfb_tightvnc) { - if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; } - // In TightVNC mode, ServerInit message is extended - const numServerMessages = this._sock.rQshift16(); - const numClientMessages = this._sock.rQshift16(); - const numEncodings = this._sock.rQshift16(); - this._sock.rQskipBytes(2); // padding - - const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16; - if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; } - - // we don't actually do anything with the capability information that TIGHT sends, - // so we just skip the all of this. - - // TIGHT server message capabilities - this._sock.rQskipBytes(16 * numServerMessages); - - // TIGHT client message capabilities - this._sock.rQskipBytes(16 * numClientMessages); - - // TIGHT encoding capabilities - this._sock.rQskipBytes(16 * numEncodings); - } - - // NB(directxman12): these are down here so that we don't run them multiple times - // if we backtrack - Log.Info("Screen: " + width + "x" + height + - ", bpp: " + bpp + ", depth: " + depth + - ", big_endian: " + big_endian + - ", true_color: " + true_color + - ", red_max: " + red_max + - ", green_max: " + green_max + - ", blue_max: " + blue_max + - ", red_shift: " + red_shift + - ", green_shift: " + green_shift + - ", blue_shift: " + blue_shift); - - if (big_endian !== 0) { - Log.Warn("Server native endian is not little endian"); - } - - if (red_shift !== 16) { - Log.Warn("Server native red-shift is not 16"); - } - - if (blue_shift !== 0) { - Log.Warn("Server native blue-shift is not 0"); - } - - // we're past the point where we could backtrack, so it's safe to call this - this.dispatchEvent(new CustomEvent( - "desktopname", - { detail: { name: this._fb_name } })); - - this._resize(width, height); - - if (!this._viewOnly) { this._keyboard.grab(); } - if (!this._viewOnly) { this._mouse.grab(); } - - this._fb_depth = 24; - - if (this._fb_name === "Intel(r) AMT KVM") { - Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode."); - this._fb_depth = 8; - } - - RFB.messages.pixelFormat(this._sock, this._fb_depth, true); - this._sendEncodings(); - RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height); - - this._updateConnectionState('connected'); - return true; - } - - _hasWebp() { - /* - return new Promise(res => { - const webP = new Image(); - webP.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA'; - webP.onload = webP.onerror = function () { - res(webP.height === 2); - }; - }) - */ - if (!this.enableWebP) - return false; - // It's not possible to check for webp synchronously, and hacking promises - // into everything would be too time-consuming. So test for FF and Chrome. - var uagent = navigator.userAgent.toLowerCase(); - var match = uagent.match(/firefox\/([0-9]+)\./); - if (match && parseInt(match[1]) >= 65) - return true; - match = uagent.match(/chrome\/([0-9]+)\./); - if (match && parseInt(match[1]) >= 23) - return true; - return false; - } - - _sendEncodings() { - const encs = []; - var hasWebp; - - // In preference order - encs.push(encodings.encodingCopyRect); - // Only supported with full depth support - if (this._fb_depth == 24) { - encs.push(encodings.encodingTight); - encs.push(encodings.encodingTightPNG); - encs.push(encodings.encodingHextile); - encs.push(encodings.encodingRRE); - } - encs.push(encodings.encodingRaw); - - // Psuedo-encoding settings - var quality = 6; - var compression = 2; - var screensize = this._screenSize(false); - if (this.videoQuality == 1) { - if (screensize.w > 1280) { - quality = 8; //higher quality needed because scaling enlarges artifacts - } else { - quality = 3; //twice the compression ratio as default, but not horrible quality - } - compression = 6; - } else if (this.videoQuality == 3) { - quality = 8 - } - encs.push(encodings.pseudoEncodingQualityLevel0 + quality); - encs.push(encodings.pseudoEncodingCompressLevel0 + compression); - - encs.push(encodings.pseudoEncodingDesktopSize); - encs.push(encodings.pseudoEncodingLastRect); - encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent); - encs.push(encodings.pseudoEncodingExtendedDesktopSize); - encs.push(encodings.pseudoEncodingXvp); - encs.push(encodings.pseudoEncodingFence); - encs.push(encodings.pseudoEncodingContinuousUpdates); - if (this._hasWebp()) - encs.push(encodings.pseudoEncodingWEBP); - - // kasm settings; the server may be configured to ignore these - encs.push(encodings.pseudoEncodingJpegVideoQualityLevel0 + this.jpegVideoQuality); - encs.push(encodings.pseudoEncodingWebpVideoQualityLevel0 + this.webpVideoQuality); - encs.push(encodings.pseudoEncodingTreatLosslessLevel0 + this.treatLossless); - encs.push(encodings.pseudoEncodingDynamicQualityMinLevel0 + this.dynamicQualityMin); - encs.push(encodings.pseudoEncodingDynamicQualityMaxLevel0 + this.dynamicQualityMax); - encs.push(encodings.pseudoEncodingVideoAreaLevel1 + this.videoArea - 1); - encs.push(encodings.pseudoEncodingVideoTimeLevel0 + this.videoTime); - encs.push(encodings.pseudoEncodingVideoOutTimeLevel1 + this.videoOutTime - 1); - encs.push(encodings.pseudoEncodingVideoScalingLevel0 + this.videoScaling); - encs.push(encodings.pseudoEncodingFrameRateLevel10 + this.frameRate - 10); - encs.push(encodings.pseudoEncodingMaxVideoResolution); - if (this.preferBandwidth) // must be last - server processes in reverse order - encs.push(encodings.pseudoEncodingPreferBandwidth); - - if (this._fb_depth == 24) { - encs.push(encodings.pseudoEncodingCursor); - } - - if (supportsCursorURIs() && this._fb_depth == 24){ - // Allow the user to attempt using a local cursor even if they are using a touch device. KASM-395 - if (this.preferLocalCursor || !isTouchDevice){ - encs.push(encodings.pseudoEncodingCursor) - } - } - - RFB.messages.clientEncodings(this._sock, encs); - } - - /* RFB protocol initialization states: - * ProtocolVersion - * Security - * Authentication - * SecurityResult - * ClientInitialization - not triggered by server message - * ServerInitialization - */ - _init_msg() { - switch (this._rfb_init_state) { - case 'ProtocolVersion': - return this._negotiate_protocol_version(); - - case 'Security': - return this._negotiate_security(); - - case 'Authentication': - return this._negotiate_authentication(); - - case 'SecurityResult': - return this._handle_security_result(); - - case 'ClientInitialisation': - this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation - this._rfb_init_state = 'ServerInitialisation'; - return true; - - case 'ServerInitialisation': - return this._negotiate_server_init(); - - default: - return this._fail("Unknown init state (state: " + - this._rfb_init_state + ")"); - } - } - - _handle_set_colour_map_msg() { - Log.Debug("SetColorMapEntries"); - - return this._fail("Unexpected SetColorMapEntries message"); - } - - _handle_server_cut_text() { - Log.Debug("ServerCutText"); - - if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; } - this._sock.rQskipBytes(3); // Padding - const length = this._sock.rQshift32(); - if (this._sock.rQwait("ServerCutText", length, 8)) { return false; } - - const text = this._sock.rQshiftStr(length); - - if (this._viewOnly) { return true; } - - this.dispatchEvent(new CustomEvent( - "clipboard", - { detail: { text: text } })); - - return true; - } - - _handle_server_stats_msg() { - this._sock.rQskipBytes(3); // Padding - const length = this._sock.rQshift32(); - if (this._sock.rQwait("KASM bottleneck stats", length, 8)) { return false; } - - const text = this._sock.rQshiftStr(length); - - console.log("Received KASM bottleneck stats:"); - console.log(text); - this.dispatchEvent(new CustomEvent( - "bottleneck_stats", - { detail: { text: text } })); - - return true; - } - - _handle_server_fence_msg() { - if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; } - this._sock.rQskipBytes(3); // Padding - let flags = this._sock.rQshift32(); - let length = this._sock.rQshift8(); - - if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; } - - if (length > 64) { - Log.Warn("Bad payload length (" + length + ") in fence response"); - length = 64; - } - - const payload = this._sock.rQshiftStr(length); - - this._supportsFence = true; - - /* - * Fence flags - * - * (1<<0) - BlockBefore - * (1<<1) - BlockAfter - * (1<<2) - SyncNext - * (1<<31) - Request - */ - - if (!(flags & (1<<31))) { - return this._fail("Unexpected fence response"); - } - - // Filter out unsupported flags - // FIXME: support syncNext - flags &= (1<<0) | (1<<1); - - // BlockBefore and BlockAfter are automatically handled by - // the fact that we process each incoming message - // synchronuosly. - RFB.messages.clientFence(this._sock, flags, payload); - - return true; - } - - _handle_xvp_msg() { - if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; } - this._sock.rQskipBytes(1); // Padding - const xvp_ver = this._sock.rQshift8(); - const xvp_msg = this._sock.rQshift8(); - - switch (xvp_msg) { - case 0: // XVP_FAIL - Log.Error("XVP Operation Failed"); - break; - case 1: // XVP_INIT - this._rfb_xvp_ver = xvp_ver; - Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")"); - this._setCapability("power", true); - break; - default: - this._fail("Illegal server XVP message (msg: " + xvp_msg + ")"); - break; - } - - return true; - } - - _normal_msg() { - let msg_type; - if (this._FBU.rects > 0) { - msg_type = 0; - } else { - msg_type = this._sock.rQshift8(); - } - - let first, ret; - switch (msg_type) { - case 0: // FramebufferUpdate - ret = this._framebufferUpdate(); - if (ret && !this._enabledContinuousUpdates) { - RFB.messages.fbUpdateRequest(this._sock, true, 0, 0, - this._fb_width, this._fb_height); - } - return ret; - - case 1: // SetColorMapEntries - return this._handle_set_colour_map_msg(); - - case 2: // Bell - Log.Debug("Bell"); - this.dispatchEvent(new CustomEvent( - "bell", - { detail: {} })); - return true; - - case 3: // ServerCutText - return this._handle_server_cut_text(); - - case 150: // EndOfContinuousUpdates - first = !this._supportsContinuousUpdates; - this._supportsContinuousUpdates = true; - this._enabledContinuousUpdates = false; - if (first) { - this._enabledContinuousUpdates = true; - this._updateContinuousUpdates(); - Log.Info("Enabling continuous updates."); - } else { - // FIXME: We need to send a framebufferupdaterequest here - // if we add support for turning off continuous updates - } - return true; - - case 178: // KASM bottleneck stats - return this._handle_server_stats_msg(); - - case 248: // ServerFence - return this._handle_server_fence_msg(); - - case 250: // XVP - return this._handle_xvp_msg(); - - default: - this._fail("Unexpected server message (type " + msg_type + ")"); - Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30)); - return true; - } - } - - _onFlush() { - this._flushing = false; - // Resume processing - if (this._sock.rQlen > 0) { - this._handle_message(); - } - } - - _framebufferUpdate() { - if (this._FBU.rects === 0) { - if (this._sock.rQwait("FBU header", 3, 1)) { return false; } - this._sock.rQskipBytes(1); // Padding - this._FBU.rects = this._sock.rQshift16(); - - // Make sure the previous frame is fully rendered first - // to avoid building up an excessive queue - if (this._display.pending()) { - this._flushing = true; - this._display.flush(); - return false; - } - } - - while (this._FBU.rects > 0) { - if (this._FBU.encoding === null) { - if (this._sock.rQwait("rect header", 12)) { return false; } - /* New FramebufferUpdate */ - - const hdr = this._sock.rQshiftBytes(12); - this._FBU.x = (hdr[0] << 8) + hdr[1]; - this._FBU.y = (hdr[2] << 8) + hdr[3]; - this._FBU.width = (hdr[4] << 8) + hdr[5]; - this._FBU.height = (hdr[6] << 8) + hdr[7]; - this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) + - (hdr[10] << 8) + hdr[11], 10); - } - - if (!this._handleRect()) { - return false; - } - - this._FBU.rects--; - this._FBU.encoding = null; - } - - if (document.visibilityState !== "hidden") { - this._display.flip(); - } - - return true; // We finished this FBU - } - - _handleRect() { - switch (this._FBU.encoding) { - case encodings.pseudoEncodingLastRect: - this._FBU.rects = 1; // Will be decreased when we return - return true; - - case encodings.pseudoEncodingCursor: - return this._handleCursor(); - - case encodings.pseudoEncodingQEMUExtendedKeyEvent: - // Old Safari doesn't support creating keyboard events - try { - const keyboardEvent = document.createEvent("keyboardEvent"); - if (keyboardEvent.code !== undefined) { - this._qemuExtKeyEventSupported = true; - } - } catch (err) { - // Do nothing - } - return true; - - case encodings.pseudoEncodingDesktopSize: - this._resize(this._FBU.width, this._FBU.height); - return true; - - case encodings.pseudoEncodingExtendedDesktopSize: - return this._handleExtendedDesktopSize(); - - default: - return this._handleDataRect(); - } - } - - _handleCursor() { - const hotx = this._FBU.x; // hotspot-x - const hoty = this._FBU.y; // hotspot-y - const w = this._FBU.width; - const h = this._FBU.height; - - const pixelslength = w * h * 4; - const masklength = Math.ceil(w / 8) * h; - - let bytes = pixelslength + masklength; - if (this._sock.rQwait("cursor encoding", bytes)) { - return false; - } - - // Decode from BGRX pixels + bit mask to RGBA - const pixels = this._sock.rQshiftBytes(pixelslength); - const mask = this._sock.rQshiftBytes(masklength); - let rgba = new Uint8Array(w * h * 4); - - let pix_idx = 0; - for (let y = 0; y < h; y++) { - for (let x = 0; x < w; x++) { - let mask_idx = y * Math.ceil(w / 8) + Math.floor(x / 8); - let alpha = (mask[mask_idx] << (x % 8)) & 0x80 ? 255 : 0; - rgba[pix_idx ] = pixels[pix_idx + 2]; - rgba[pix_idx + 1] = pixels[pix_idx + 1]; - rgba[pix_idx + 2] = pixels[pix_idx]; - rgba[pix_idx + 3] = alpha; - pix_idx += 4; - } - } - - this._updateCursor(rgba, hotx, hoty, w, h); - - return true; - } - - _handleExtendedDesktopSize() { - if (this._sock.rQwait("ExtendedDesktopSize", 4)) { - return false; - } - - const number_of_screens = this._sock.rQpeek8(); - - let bytes = 4 + (number_of_screens * 16); - if (this._sock.rQwait("ExtendedDesktopSize", bytes)) { - return false; - } - - const firstUpdate = !this._supportsSetDesktopSize; - this._supportsSetDesktopSize = true; - - // Normally we only apply the current resize mode after a - // window resize event. However there is no such trigger on the - // initial connect. And we don't know if the server supports - // resizing until we've gotten here. - if (firstUpdate) { - this._requestRemoteResize(); - - RFB.messages.setMaxVideoResolution(this._sock, - this._maxVideoResolutionX, - this._maxVideoResolutionY); - this.sentEventsCounter+=1; - } - - this._sock.rQskipBytes(1); // number-of-screens - this._sock.rQskipBytes(3); // padding - - for (let i = 0; i < number_of_screens; i += 1) { - // Save the id and flags of the first screen - if (i === 0) { - this._screen_id = this._sock.rQshiftBytes(4); // id - this._sock.rQskipBytes(2); // x-position - this._sock.rQskipBytes(2); // y-position - this._sock.rQskipBytes(2); // width - this._sock.rQskipBytes(2); // height - this._screen_flags = this._sock.rQshiftBytes(4); // flags - } else { - this._sock.rQskipBytes(16); - } - } - - /* - * The x-position indicates the reason for the change: - * - * 0 - server resized on its own - * 1 - this client requested the resize - * 2 - another client requested the resize - */ - - // We need to handle errors when we requested the resize. - if (this._FBU.x === 1 && this._FBU.y !== 0) { - let msg = ""; - // The y-position indicates the status code from the server - switch (this._FBU.y) { - case 1: - msg = "Resize is administratively prohibited"; - break; - case 2: - msg = "Out of resources"; - break; - case 3: - msg = "Invalid screen layout"; - break; - default: - msg = "Unknown reason"; - break; - } - Log.Warn("Server did not accept the resize request: " - + msg); - } else { - this._resize(this._FBU.width, this._FBU.height); - } - - return true; - } - - _handleDataRect() { - let decoder = this._decoders[this._FBU.encoding]; - if (!decoder) { - this._fail("Unsupported encoding (encoding: " + - this._FBU.encoding + ")"); - return false; - } - - try { - return decoder.decodeRect(this._FBU.x, this._FBU.y, - this._FBU.width, this._FBU.height, - this._sock, this._display, - this._fb_depth); - } catch (err) { - this._fail("Error decoding rect: " + err); - return false; - } - } - - _updateContinuousUpdates() { - if (!this._enabledContinuousUpdates) { return; } - - RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0, - this._fb_width, this._fb_height); - } - - _resize(width, height) { - this._fb_width = width; - this._fb_height = height; - - this._display.resize(this._fb_width, this._fb_height); - - // Adjust the visible viewport based on the new dimensions - this._updateClip(); - this._updateScale(); - - this._updateContinuousUpdates(); - } - - _xvpOp(ver, op) { - if (this._rfb_xvp_ver < ver) { return; } - Log.Info("Sending XVP operation " + op + " (version " + ver + ")"); - RFB.messages.xvpOp(this._sock, ver, op); - } - - _updateCursor(rgba, hotx, hoty, w, h) { - this._cursorImage = { - rgbaPixels: rgba, - hotx: hotx, hoty: hoty, w: w, h: h, - }; - this._refreshCursor(); - } - - _shouldShowDotCursor() { - // Called when this._cursorImage is updated - if (!this._showDotCursor) { - // User does not want to see the dot, so... - return false; - } - - // The dot should not be shown if the cursor is already visible, - // i.e. contains at least one not-fully-transparent pixel. - // So iterate through all alpha bytes in rgba and stop at the - // first non-zero. - for (let i = 3; i < this._cursorImage.rgbaPixels.length; i += 4) { - if (this._cursorImage.rgbaPixels[i]) { - return false; - } - } - - // At this point, we know that the cursor is fully transparent, and - // the user wants to see the dot instead of this. - return true; - } - - _refreshCursor() { - const image = this._shouldShowDotCursor() ? RFB.cursors.dot : this._cursorImage; - this._cursor.change(image.rgbaPixels, - image.hotx, image.hoty, - image.w, image.h - ); - } - - static genDES(password, challenge) { - const passwd = []; - for (let i = 0; i < password.length; i++) { - passwd.push(password.charCodeAt(i)); - } - return (new DES(passwd)).encrypt(challenge); - } -} - -// Class Methods -RFB.messages = { - keyEvent(sock, keysym, down) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 4; // msg-type - buff[offset + 1] = down; - - buff[offset + 2] = 0; - buff[offset + 3] = 0; - - buff[offset + 4] = (keysym >> 24); - buff[offset + 5] = (keysym >> 16); - buff[offset + 6] = (keysym >> 8); - buff[offset + 7] = keysym; - - sock._sQlen += 8; - sock.flush(); - }, - - QEMUExtendedKeyEvent(sock, keysym, down, keycode) { - function getRFBkeycode(xt_scancode) { - const upperByte = (keycode >> 8); - const lowerByte = (keycode & 0x00ff); - if (upperByte === 0xe0 && lowerByte < 0x7f) { - return lowerByte | 0x80; - } - return xt_scancode; - } - - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 255; // msg-type - buff[offset + 1] = 0; // sub msg-type - - buff[offset + 2] = (down >> 8); - buff[offset + 3] = down; - - buff[offset + 4] = (keysym >> 24); - buff[offset + 5] = (keysym >> 16); - buff[offset + 6] = (keysym >> 8); - buff[offset + 7] = keysym; - - const RFBkeycode = getRFBkeycode(keycode); - - buff[offset + 8] = (RFBkeycode >> 24); - buff[offset + 9] = (RFBkeycode >> 16); - buff[offset + 10] = (RFBkeycode >> 8); - buff[offset + 11] = RFBkeycode; - - sock._sQlen += 12; - sock.flush(); - }, - - pointerEvent(sock, x, y, mask) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 5; // msg-type - - buff[offset + 1] = mask; - - buff[offset + 2] = x >> 8; - buff[offset + 3] = x; - - buff[offset + 4] = y >> 8; - buff[offset + 5] = y; - - sock._sQlen += 6; - sock.flush(); - }, - - // TODO(directxman12): make this unicode compatible? - clientCutText(sock, text) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 6; // msg-type - - buff[offset + 1] = 0; // padding - buff[offset + 2] = 0; // padding - buff[offset + 3] = 0; // padding - - let length = text.length; - - buff[offset + 4] = length >> 24; - buff[offset + 5] = length >> 16; - buff[offset + 6] = length >> 8; - buff[offset + 7] = length; - - sock._sQlen += 8; - - // We have to keep track of from where in the text we begin creating the - // buffer for the flush in the next iteration. - let textOffset = 0; - - let remaining = length; - while (remaining > 0) { - - let flushSize = Math.min(remaining, (sock._sQbufferSize - sock._sQlen)); - if (flushSize <= 0) { - this._fail("Clipboard contents could not be sent"); - break; - } - - for (let i = 0; i < flushSize; i++) { - buff[sock._sQlen + i] = text.charCodeAt(textOffset + i); - } - - sock._sQlen += flushSize; - sock.flush(); - - remaining -= flushSize; - textOffset += flushSize; - } - }, - - setDesktopSize(sock, width, height, id, flags) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 251; // msg-type - buff[offset + 1] = 0; // padding - buff[offset + 2] = width >> 8; // width - buff[offset + 3] = width; - buff[offset + 4] = height >> 8; // height - buff[offset + 5] = height; - - buff[offset + 6] = 1; // number-of-screens - buff[offset + 7] = 0; // padding - - // screen array - buff[offset + 8] = id >> 24; // id - buff[offset + 9] = id >> 16; - buff[offset + 10] = id >> 8; - buff[offset + 11] = id; - buff[offset + 12] = 0; // x-position - buff[offset + 13] = 0; - buff[offset + 14] = 0; // y-position - buff[offset + 15] = 0; - buff[offset + 16] = width >> 8; // width - buff[offset + 17] = width; - buff[offset + 18] = height >> 8; // height - buff[offset + 19] = height; - buff[offset + 20] = flags >> 24; // flags - buff[offset + 21] = flags >> 16; - buff[offset + 22] = flags >> 8; - buff[offset + 23] = flags; - - sock._sQlen += 24; - sock.flush(); - }, - - setMaxVideoResolution(sock, width, height) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 252; // msg-type - buff[offset + 1] = width >> 8; // width - buff[offset + 2] = width; - buff[offset + 3] = height >> 8; // height - buff[offset + 4] = height; - - sock._sQlen += 5; - sock.flush(); - }, - - clientFence(sock, flags, payload) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 248; // msg-type - - buff[offset + 1] = 0; // padding - buff[offset + 2] = 0; // padding - buff[offset + 3] = 0; // padding - - buff[offset + 4] = flags >> 24; // flags - buff[offset + 5] = flags >> 16; - buff[offset + 6] = flags >> 8; - buff[offset + 7] = flags; - - const n = payload.length; - - buff[offset + 8] = n; // length - - for (let i = 0; i < n; i++) { - buff[offset + 9 + i] = payload.charCodeAt(i); - } - - sock._sQlen += 9 + n; - sock.flush(); - }, - - requestStats(sock) { - const buff = sock._sQ; - const offset = sock._sQlen; - - if (buff == null) { return; } - - buff[offset] = 178; // msg-type - - buff[offset + 1] = 0; // padding - buff[offset + 2] = 0; // padding - buff[offset + 3] = 0; // padding - - sock._sQlen += 4; - sock.flush(); - }, - - enableContinuousUpdates(sock, enable, x, y, width, height) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 150; // msg-type - buff[offset + 1] = enable; // enable-flag - - buff[offset + 2] = x >> 8; // x - buff[offset + 3] = x; - buff[offset + 4] = y >> 8; // y - buff[offset + 5] = y; - buff[offset + 6] = width >> 8; // width - buff[offset + 7] = width; - buff[offset + 8] = height >> 8; // height - buff[offset + 9] = height; - - sock._sQlen += 10; - sock.flush(); - }, - - pixelFormat(sock, depth, true_color) { - const buff = sock._sQ; - const offset = sock._sQlen; - - let bpp; - - if (depth > 16) { - bpp = 32; - } else if (depth > 8) { - bpp = 16; - } else { - bpp = 8; - } - - const bits = Math.floor(depth/3); - - buff[offset] = 0; // msg-type - - buff[offset + 1] = 0; // padding - buff[offset + 2] = 0; // padding - buff[offset + 3] = 0; // padding - - buff[offset + 4] = bpp; // bits-per-pixel - buff[offset + 5] = depth; // depth - buff[offset + 6] = 0; // little-endian - buff[offset + 7] = true_color ? 1 : 0; // true-color - - buff[offset + 8] = 0; // red-max - buff[offset + 9] = (1 << bits) - 1; // red-max - - buff[offset + 10] = 0; // green-max - buff[offset + 11] = (1 << bits) - 1; // green-max - - buff[offset + 12] = 0; // blue-max - buff[offset + 13] = (1 << bits) - 1; // blue-max - - buff[offset + 14] = bits * 2; // red-shift - buff[offset + 15] = bits * 1; // green-shift - buff[offset + 16] = bits * 0; // blue-shift - - buff[offset + 17] = 0; // padding - buff[offset + 18] = 0; // padding - buff[offset + 19] = 0; // padding - - sock._sQlen += 20; - sock.flush(); - }, - - clientEncodings(sock, encodings) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 2; // msg-type - buff[offset + 1] = 0; // padding - - buff[offset + 2] = encodings.length >> 8; - buff[offset + 3] = encodings.length; - - let j = offset + 4; - for (let i = 0; i < encodings.length; i++) { - const enc = encodings[i]; - buff[j] = enc >> 24; - buff[j + 1] = enc >> 16; - buff[j + 2] = enc >> 8; - buff[j + 3] = enc; - - j += 4; - } - - sock._sQlen += j - offset; - sock.flush(); - }, - - fbUpdateRequest(sock, incremental, x, y, w, h) { - const buff = sock._sQ; - const offset = sock._sQlen; - - if (typeof(x) === "undefined") { x = 0; } - if (typeof(y) === "undefined") { y = 0; } - - buff[offset] = 3; // msg-type - buff[offset + 1] = incremental ? 1 : 0; - - buff[offset + 2] = (x >> 8) & 0xFF; - buff[offset + 3] = x & 0xFF; - - buff[offset + 4] = (y >> 8) & 0xFF; - buff[offset + 5] = y & 0xFF; - - buff[offset + 6] = (w >> 8) & 0xFF; - buff[offset + 7] = w & 0xFF; - - buff[offset + 8] = (h >> 8) & 0xFF; - buff[offset + 9] = h & 0xFF; - - sock._sQlen += 10; - sock.flush(); - }, - - xvpOp(sock, ver, op) { - const buff = sock._sQ; - const offset = sock._sQlen; - - buff[offset] = 250; // msg-type - buff[offset + 1] = 0; // padding - - buff[offset + 2] = ver; - buff[offset + 3] = op; - - sock._sQlen += 4; - sock.flush(); - } -}; - -RFB.cursors = { - none: { - rgbaPixels: new Uint8Array(), - w: 0, h: 0, - hotx: 0, hoty: 0, - }, - - dot: { - /* eslint-disable indent */ - rgbaPixels: new Uint8Array([ - 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, - 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255, - 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, - ]), - /* eslint-enable indent */ - w: 3, h: 3, - hotx: 1, hoty: 1, - } -}; diff --git a/kasmweb/core/util/browser.js b/kasmweb/core/util/browser.js deleted file mode 100644 index 026a31a..0000000 --- a/kasmweb/core/util/browser.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -import * as Log from './logging.js'; - -// Touch detection -export let isTouchDevice = ('ontouchstart' in document.documentElement) || - // requried for Chrome debugger - (document.ontouchstart !== undefined) || - // required for MS Surface - (navigator.maxTouchPoints > 0) || - (navigator.msMaxTouchPoints > 0); -window.addEventListener('touchstart', function onFirstTouch() { - isTouchDevice = true; - window.removeEventListener('touchstart', onFirstTouch, false); -}, false); - - -// The goal is to find a certain physical width, the devicePixelRatio -// brings us a bit closer but is not optimal. -export let dragThreshold = 10 * (window.devicePixelRatio || 1); - -let _cursor_uris_supported = null; - -export function supportsCursorURIs() { - if (_cursor_uris_supported === null) { - try { - const target = document.createElement('canvas'); - target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default'; - - if (target.style.cursor) { - Log.Info("Data URI scheme cursor supported"); - _cursor_uris_supported = true; - } else { - Log.Warn("Data URI scheme cursor not supported"); - _cursor_uris_supported = false; - } - } catch (exc) { - Log.Error("Data URI scheme cursor test exception: " + exc); - _cursor_uris_supported = false; - } - } - - return _cursor_uris_supported; -} - -export function isMac() { - return navigator && !!(/mac/i).exec(navigator.platform); -} - -export function isWindows() { - return navigator && !!(/win/i).exec(navigator.platform); -} - -export function isIOS() { - return navigator && - (!!(/ipad/i).exec(navigator.platform) || - !!(/iphone/i).exec(navigator.platform) || - !!(/ipod/i).exec(navigator.platform)); -} - -export function isAndroid() { - return navigator && !!(/android/i).exec(navigator.userAgent); -} - -export function isSafari() { - return navigator && (navigator.userAgent.indexOf('Safari') !== -1 && - navigator.userAgent.indexOf('Chrome') === -1); -} - -export function isIE() { - return navigator && !!(/trident/i).exec(navigator.userAgent); -} - -export function isEdge() { - return navigator && !!(/edge/i).exec(navigator.userAgent); -} - -export function isFirefox() { - return navigator && !!(/firefox/i).exec(navigator.userAgent); -} - diff --git a/kasmweb/core/util/cursor.js b/kasmweb/core/util/cursor.js deleted file mode 100644 index b032ab6..0000000 --- a/kasmweb/core/util/cursor.js +++ /dev/null @@ -1,221 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -import { supportsCursorURIs, isTouchDevice } from './browser.js'; - -const useFallback = !supportsCursorURIs() || isTouchDevice; - -export default class Cursor { - constructor(container) { - this._target = null; - - this._canvas = document.createElement('canvas'); - - if (useFallback) { - this._canvas.style.position = 'fixed'; - this._canvas.style.zIndex = '65535'; - this._canvas.style.pointerEvents = 'none'; - // Can't use "display" because of Firefox bug #1445997 - this._canvas.style.visibility = 'hidden'; - document.body.appendChild(this._canvas); - } - - this._position = { x: 0, y: 0 }; - this._hotSpot = { x: 0, y: 0 }; - - this._eventHandlers = { - 'mouseover': this._handleMouseOver.bind(this), - 'mouseleave': this._handleMouseLeave.bind(this), - 'mousemove': this._handleMouseMove.bind(this), - 'mouseup': this._handleMouseUp.bind(this), - 'touchstart': this._handleTouchStart.bind(this), - 'touchmove': this._handleTouchMove.bind(this), - 'touchend': this._handleTouchEnd.bind(this), - }; - } - - attach(target) { - if (this._target) { - this.detach(); - } - - this._target = target; - - if (useFallback) { - // FIXME: These don't fire properly except for mouse - /// movement in IE. We want to also capture element - // movement, size changes, visibility, etc. - const options = { capture: true, passive: true }; - this._target.addEventListener('mouseover', this._eventHandlers.mouseover, options); - this._target.addEventListener('mouseleave', this._eventHandlers.mouseleave, options); - this._target.addEventListener('mousemove', this._eventHandlers.mousemove, options); - this._target.addEventListener('mouseup', this._eventHandlers.mouseup, options); - - // There is no "touchleave" so we monitor touchstart globally - window.addEventListener('touchstart', this._eventHandlers.touchstart, options); - this._target.addEventListener('touchmove', this._eventHandlers.touchmove, options); - this._target.addEventListener('touchend', this._eventHandlers.touchend, options); - } - - this.clear(); - } - - detach() { - if (useFallback) { - const options = { capture: true, passive: true }; - this._target.removeEventListener('mouseover', this._eventHandlers.mouseover, options); - this._target.removeEventListener('mouseleave', this._eventHandlers.mouseleave, options); - this._target.removeEventListener('mousemove', this._eventHandlers.mousemove, options); - this._target.removeEventListener('mouseup', this._eventHandlers.mouseup, options); - - window.removeEventListener('touchstart', this._eventHandlers.touchstart, options); - this._target.removeEventListener('touchmove', this._eventHandlers.touchmove, options); - this._target.removeEventListener('touchend', this._eventHandlers.touchend, options); - } - - this._target = null; - } - - change(rgba, hotx, hoty, w, h) { - if ((w === 0) || (h === 0)) { - this.clear(); - return; - } - - this._position.x = this._position.x + this._hotSpot.x - hotx; - this._position.y = this._position.y + this._hotSpot.y - hoty; - this._hotSpot.x = hotx; - this._hotSpot.y = hoty; - - let ctx = this._canvas.getContext('2d'); - - this._canvas.width = w; - this._canvas.height = h; - - let img; - try { - // IE doesn't support this - img = new ImageData(new Uint8ClampedArray(rgba), w, h); - } catch (ex) { - img = ctx.createImageData(w, h); - img.data.set(new Uint8ClampedArray(rgba)); - } - ctx.clearRect(0, 0, w, h); - ctx.putImageData(img, 0, 0); - - if (useFallback) { - this._updatePosition(); - } else { - let url = this._canvas.toDataURL(); - this._target.style.cursor = 'url(' + url + ')' + hotx + ' ' + hoty + ', default'; - } - } - - clear() { - this._target.style.cursor = 'none'; - this._canvas.width = 0; - this._canvas.height = 0; - this._position.x = this._position.x + this._hotSpot.x; - this._position.y = this._position.y + this._hotSpot.y; - this._hotSpot.x = 0; - this._hotSpot.y = 0; - } - - _handleMouseOver(event) { - // This event could be because we're entering the target, or - // moving around amongst its sub elements. Let the move handler - // sort things out. - this._handleMouseMove(event); - } - - _handleMouseLeave(event) { - this._hideCursor(); - } - - _handleMouseMove(event) { - this._updateVisibility(event.target); - - this._position.x = event.clientX - this._hotSpot.x; - this._position.y = event.clientY - this._hotSpot.y; - - this._updatePosition(); - } - - _handleMouseUp(event) { - // We might get this event because of a drag operation that - // moved outside of the target. Check what's under the cursor - // now and adjust visibility based on that. - let target = document.elementFromPoint(event.clientX, event.clientY); - this._updateVisibility(target); - } - - _handleTouchStart(event) { - // Just as for mouseover, we let the move handler deal with it - this._handleTouchMove(event); - } - - _handleTouchMove(event) { - this._updateVisibility(event.target); - - this._position.x = event.changedTouches[0].clientX - this._hotSpot.x; - this._position.y = event.changedTouches[0].clientY - this._hotSpot.y; - - this._updatePosition(); - } - - _handleTouchEnd(event) { - // Same principle as for mouseup - let target = document.elementFromPoint(event.changedTouches[0].clientX, - event.changedTouches[0].clientY); - this._updateVisibility(target); - } - - _showCursor() { - if (this._canvas.style.visibility === 'hidden') { - this._canvas.style.visibility = ''; - } - } - - _hideCursor() { - if (this._canvas.style.visibility !== 'hidden') { - this._canvas.style.visibility = 'hidden'; - } - } - - // Should we currently display the cursor? - // (i.e. are we over the target, or a child of the target without a - // different cursor set) - _shouldShowCursor(target) { - // Easy case - if (target === this._target) { - return true; - } - // Other part of the DOM? - if (!this._target.contains(target)) { - return false; - } - // Has the child its own cursor? - // FIXME: How can we tell that a sub element has an - // explicit "cursor: none;"? - if (window.getComputedStyle(target).cursor !== 'none') { - return false; - } - return true; - } - - _updateVisibility(target) { - if (this._shouldShowCursor(target)) { - this._showCursor(); - } else { - this._hideCursor(); - } - } - - _updatePosition() { - this._canvas.style.left = this._position.x + "px"; - this._canvas.style.top = this._position.y + "px"; - } -} diff --git a/kasmweb/core/util/events.js b/kasmweb/core/util/events.js deleted file mode 100644 index f122279..0000000 --- a/kasmweb/core/util/events.js +++ /dev/null @@ -1,139 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -/* - * Cross-browser event and position routines - */ - -export function getPointerEvent(e) { - return e.changedTouches ? e.changedTouches[0] : e.touches ? e.touches[0] : e; -} - -export function stopEvent(e) { - e.stopPropagation(); - e.preventDefault(); -} - -// Emulate Element.setCapture() when not supported -let _captureRecursion = false; -let _captureElem = null; -function _captureProxy(e) { - // Recursion protection as we'll see our own event - if (_captureRecursion) return; - - // Clone the event as we cannot dispatch an already dispatched event - const newEv = new e.constructor(e.type, e); - - _captureRecursion = true; - _captureElem.dispatchEvent(newEv); - _captureRecursion = false; - - // Avoid double events - e.stopPropagation(); - - // Respect the wishes of the redirected event handlers - if (newEv.defaultPrevented) { - e.preventDefault(); - } - - // Implicitly release the capture on button release - if (e.type === "mouseup") { - releaseCapture(); - } -} - -// Follow cursor style of target element -function _captureElemChanged() { - const captureElem = document.getElementById("noVNC_mouse_capture_elem"); - captureElem.style.cursor = window.getComputedStyle(_captureElem).cursor; -} - -const _captureObserver = new MutationObserver(_captureElemChanged); - -let _captureIndex = 0; - -export function setCapture(elem) { - if (elem.setCapture) { - - elem.setCapture(); - - // IE releases capture on 'click' events which might not trigger - elem.addEventListener('mouseup', releaseCapture); - - } else { - // Release any existing capture in case this method is - // called multiple times without coordination - releaseCapture(); - - let captureElem = document.getElementById("noVNC_mouse_capture_elem"); - - if (captureElem === null) { - captureElem = document.createElement("div"); - captureElem.id = "noVNC_mouse_capture_elem"; - captureElem.style.position = "fixed"; - captureElem.style.top = "0px"; - captureElem.style.left = "0px"; - captureElem.style.width = "100%"; - captureElem.style.height = "100%"; - captureElem.style.zIndex = 10000; - captureElem.style.display = "none"; - document.body.appendChild(captureElem); - - // This is to make sure callers don't get confused by having - // our blocking element as the target - captureElem.addEventListener('contextmenu', _captureProxy); - - captureElem.addEventListener('mousemove', _captureProxy); - captureElem.addEventListener('mouseup', _captureProxy); - } - - _captureElem = elem; - _captureIndex++; - - // Track cursor and get initial cursor - _captureObserver.observe(elem, {attributes: true}); - _captureElemChanged(); - - captureElem.style.display = ""; - - // We listen to events on window in order to keep tracking if it - // happens to leave the viewport - window.addEventListener('mousemove', _captureProxy); - window.addEventListener('mouseup', _captureProxy); - } -} - -export function releaseCapture() { - if (document.releaseCapture) { - - document.releaseCapture(); - - } else { - if (!_captureElem) { - return; - } - - // There might be events already queued, so we need to wait for - // them to flush. E.g. contextmenu in Microsoft Edge - window.setTimeout((expected) => { - // Only clear it if it's the expected grab (i.e. no one - // else has initiated a new grab) - if (_captureIndex === expected) { - _captureElem = null; - } - }, 0, _captureIndex); - - _captureObserver.disconnect(); - - const captureElem = document.getElementById("noVNC_mouse_capture_elem"); - captureElem.style.display = "none"; - - window.removeEventListener('mousemove', _captureProxy); - window.removeEventListener('mouseup', _captureProxy); - } -} diff --git a/kasmweb/core/util/eventtarget.js b/kasmweb/core/util/eventtarget.js deleted file mode 100644 index d74ed28..0000000 --- a/kasmweb/core/util/eventtarget.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -export default class EventTargetMixin { - constructor() { - this._listeners = new Map(); - } - - addEventListener(type, callback) { - if (!this._listeners.has(type)) { - this._listeners.set(type, new Set()); - } - this._listeners.get(type).add(callback); - } - - removeEventListener(type, callback) { - if (this._listeners.has(type)) { - this._listeners.get(type).delete(callback); - } - } - - dispatchEvent(event) { - if (!this._listeners.has(event.type)) { - return true; - } - this._listeners.get(event.type) - .forEach(callback => callback.call(this, event), this); - return !event.defaultPrevented; - } -} diff --git a/kasmweb/core/util/logging.js b/kasmweb/core/util/logging.js deleted file mode 100644 index 036a7dd..0000000 --- a/kasmweb/core/util/logging.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -/* - * Logging/debug routines - */ - -let _log_level = 'warn'; - -let Debug = () => {}; -let Info = () => {}; -let Warn = () => {}; -let Error = () => {}; - -export function init_logging(level) { - if (typeof level === 'undefined') { - level = _log_level; - } else { - _log_level = level; - } - - Debug = Info = Warn = Error = () => {}; - - if (typeof window.console !== "undefined") { - /* eslint-disable no-console, no-fallthrough */ - switch (level) { - case 'debug': - Debug = console.debug.bind(window.console); - case 'info': - Info = console.info.bind(window.console); - case 'warn': - Warn = console.warn.bind(window.console); - case 'error': - Error = console.error.bind(window.console); - case 'none': - break; - default: - throw new Error("invalid logging type '" + level + "'"); - } - /* eslint-enable no-console, no-fallthrough */ - } -} - -export function get_logging() { - return _log_level; -} - -export { Debug, Info, Warn, Error }; - -// Initialize logging level -init_logging(); diff --git a/kasmweb/core/util/polyfill.js b/kasmweb/core/util/polyfill.js deleted file mode 100644 index 648ceeb..0000000 --- a/kasmweb/core/util/polyfill.js +++ /dev/null @@ -1,54 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -/* Polyfills to provide new APIs in old browsers */ - -/* Object.assign() (taken from MDN) */ -if (typeof Object.assign != 'function') { - // Must be writable: true, enumerable: false, configurable: true - Object.defineProperty(Object, "assign", { - value: function assign(target, varArgs) { // .length of function is 2 - 'use strict'; - if (target == null) { // TypeError if undefined or null - throw new TypeError('Cannot convert undefined or null to object'); - } - - const to = Object(target); - - for (let index = 1; index < arguments.length; index++) { - const nextSource = arguments[index]; - - if (nextSource != null) { // Skip over if undefined or null - for (let nextKey in nextSource) { - // Avoid bugs when hasOwnProperty is shadowed - if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { - to[nextKey] = nextSource[nextKey]; - } - } - } - } - return to; - }, - writable: true, - configurable: true - }); -} - -/* CustomEvent constructor (taken from MDN) */ -(() => { - function CustomEvent(event, params) { - params = params || { bubbles: false, cancelable: false, detail: undefined }; - const evt = document.createEvent( 'CustomEvent' ); - evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); - return evt; - } - - CustomEvent.prototype = window.Event.prototype; - - if (typeof window.CustomEvent !== "function") { - window.CustomEvent = CustomEvent; - } -})(); diff --git a/kasmweb/core/util/strings.js b/kasmweb/core/util/strings.js deleted file mode 100644 index 61f4f23..0000000 --- a/kasmweb/core/util/strings.js +++ /dev/null @@ -1,14 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * See README.md for usage and integration instructions. - */ - -/* - * Decode from UTF-8 - */ -export function decodeUTF8(utf8string) { - return decodeURIComponent(escape(utf8string)); -} diff --git a/kasmweb/core/websock.js b/kasmweb/core/websock.js deleted file mode 100644 index 51b9a66..0000000 --- a/kasmweb/core/websock.js +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Websock: high-performance binary WebSockets - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - * - * Websock is similar to the standard WebSocket object but with extra - * buffer handling. - * - * Websock has built-in receive queue buffering; the message event - * does not contain actual data but is simply a notification that - * there is new data available. Several rQ* methods are available to - * read binary data off of the receive queue. - */ - -import * as Log from './util/logging.js'; - -// this has performance issues in some versions Chromium, and -// doesn't gain a tremendous amount of performance increase in Firefox -// at the moment. It may be valuable to turn it on in the future. -const ENABLE_COPYWITHIN = false; -const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB - -export default class Websock { - constructor() { - this._websocket = null; // WebSocket object - - this._rQi = 0; // Receive queue index - this._rQlen = 0; // Next write position in the receive queue - this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) - this._rQmax = this._rQbufferSize / 8; - // called in init: this._rQ = new Uint8Array(this._rQbufferSize); - this._rQ = null; // Receive queue - - this._sQbufferSize = 1024 * 10; // 10 KiB - // called in init: this._sQ = new Uint8Array(this._sQbufferSize); - this._sQlen = 0; - this._sQ = null; // Send queue - - this._eventHandlers = { - message: () => {}, - open: () => {}, - close: () => {}, - error: () => {} - }; - } - - // Getters and Setters - get sQ() { - return this._sQ; - } - - get rQ() { - return this._rQ; - } - - get rQi() { - return this._rQi; - } - - set rQi(val) { - this._rQi = val; - } - - // Receive Queue - get rQlen() { - return this._rQlen - this._rQi; - } - - rQpeek8() { - return this._rQ[this._rQi]; - } - - rQskipBytes(bytes) { - this._rQi += bytes; - } - - rQshift8() { - return this._rQshift(1); - } - - rQshift16() { - return this._rQshift(2); - } - - rQshift32() { - return this._rQshift(4); - } - - // TODO(directxman12): test performance with these vs a DataView - _rQshift(bytes) { - let res = 0; - for (let byte = bytes - 1; byte >= 0; byte--) { - res += this._rQ[this._rQi++] << (byte * 8); - } - return res; - } - - rQshiftStr(len) { - if (typeof(len) === 'undefined') { len = this.rQlen; } - let str = ""; - // Handle large arrays in steps to avoid long strings on the stack - for (let i = 0; i < len; i += 4096) { - let part = this.rQshiftBytes(Math.min(4096, len - i)); - str += String.fromCharCode.apply(null, part); - } - return str; - } - - rQshiftBytes(len) { - if (typeof(len) === 'undefined') { len = this.rQlen; } - this._rQi += len; - return new Uint8Array(this._rQ.buffer, this._rQi - len, len); - } - - rQshiftTo(target, len) { - if (len === undefined) { len = this.rQlen; } - // TODO: make this just use set with views when using a ArrayBuffer to store the rQ - target.set(new Uint8Array(this._rQ.buffer, this._rQi, len)); - this._rQi += len; - } - - rQslice(start, end = this.rQlen) { - return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start); - } - - // Check to see if we must wait for 'num' bytes (default to FBU.bytes) - // to be available in the receive queue. Return true if we need to - // wait (and possibly print a debug message), otherwise false. - rQwait(msg, num, goback) { - if (this.rQlen < num) { - if (goback) { - if (this._rQi < goback) { - throw new Error("rQwait cannot backup " + goback + " bytes"); - } - this._rQi -= goback; - } - return true; // true means need more data - } - return false; - } - - // Send Queue - - flush() { - if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) { - this._websocket.send(this._encode_message()); - this._sQlen = 0; - } - } - - send(arr) { - this._sQ.set(arr, this._sQlen); - this._sQlen += arr.length; - this.flush(); - } - - send_string(str) { - this.send(str.split('').map(chr => chr.charCodeAt(0))); - } - - // Event Handlers - off(evt) { - this._eventHandlers[evt] = () => {}; - } - - on(evt, handler) { - this._eventHandlers[evt] = handler; - } - - _allocate_buffers() { - this._rQ = new Uint8Array(this._rQbufferSize); - this._sQ = new Uint8Array(this._sQbufferSize); - } - - init() { - this._allocate_buffers(); - this._rQi = 0; - this._websocket = null; - } - - open(uri, protocols) { - this.init(); - - this._websocket = new WebSocket(uri, protocols); - this._websocket.binaryType = 'arraybuffer'; - - this._websocket.onmessage = this._recv_message.bind(this); - this._websocket.onopen = () => { - Log.Debug('>> WebSock.onopen'); - if (this._websocket.protocol) { - Log.Info("Server choose sub-protocol: " + this._websocket.protocol); - } - - this._eventHandlers.open(); - Log.Debug("<< WebSock.onopen"); - }; - this._websocket.onclose = (e) => { - Log.Debug(">> WebSock.onclose"); - this._eventHandlers.close(e); - Log.Debug("<< WebSock.onclose"); - }; - this._websocket.onerror = (e) => { - Log.Debug(">> WebSock.onerror: " + e); - this._eventHandlers.error(e); - Log.Debug("<< WebSock.onerror: " + e); - }; - } - - close() { - if (this._websocket) { - if ((this._websocket.readyState === WebSocket.OPEN) || - (this._websocket.readyState === WebSocket.CONNECTING)) { - Log.Info("Closing WebSocket connection"); - this._websocket.close(); - } - - this._websocket.onmessage = () => {}; - } - } - - // private methods - _encode_message() { - // Put in a binary arraybuffer - // according to the spec, you can send ArrayBufferViews with the send method - return new Uint8Array(this._sQ.buffer, 0, this._sQlen); - } - - _expand_compact_rQ(min_fit) { - const resizeNeeded = min_fit || this.rQlen > this._rQbufferSize / 2; - if (resizeNeeded) { - if (!min_fit) { - // just double the size if we need to do compaction - this._rQbufferSize *= 2; - } else { - // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8 - this._rQbufferSize = (this.rQlen + min_fit) * 8; - } - } - - // we don't want to grow unboundedly - if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { - this._rQbufferSize = MAX_RQ_GROW_SIZE; - if (this._rQbufferSize - this.rQlen < min_fit) { - throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); - } - } - - if (resizeNeeded) { - const old_rQbuffer = this._rQ.buffer; - this._rQmax = this._rQbufferSize / 8; - this._rQ = new Uint8Array(this._rQbufferSize); - this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); - } else { - if (ENABLE_COPYWITHIN) { - this._rQ.copyWithin(0, this._rQi); - } else { - this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi)); - } - } - - this._rQlen = this._rQlen - this._rQi; - this._rQi = 0; - } - - _decode_message(data) { - // push arraybuffer values onto the end - const u8 = new Uint8Array(data); - if (u8.length > this._rQbufferSize - this._rQlen) { - this._expand_compact_rQ(u8.length); - } - this._rQ.set(u8, this._rQlen); - this._rQlen += u8.length; - } - - _recv_message(e) { - this._decode_message(e.data); - if (this.rQlen > 0) { - this._eventHandlers.message(); - // Compact the receive queue - if (this._rQlen == this._rQi) { - this._rQlen = 0; - this._rQi = 0; - } else if (this._rQlen > this._rQmax) { - this._expand_compact_rQ(); - } - } else { - Log.Debug("Ignoring empty message"); - } - } -} diff --git a/kasmweb/docs/API-internal.md b/kasmweb/docs/API-internal.md deleted file mode 100644 index 0b29afb..0000000 --- a/kasmweb/docs/API-internal.md +++ /dev/null @@ -1,122 +0,0 @@ -# 1. Internal Modules - -The noVNC client is composed of several internal modules that handle -rendering, input, networking, etc. Each of the modules is designed to -be cross-browser and independent from each other. - -Note however that the API of these modules is not guaranteed to be -stable, and this documentation is not maintained as well as the -official external API. - - -## 1.1 Module List - -* __Mouse__ (core/input/mouse.js): Mouse input event handler with -limited touch support. - -* __Keyboard__ (core/input/keyboard.js): Keyboard input event handler with -non-US keyboard support. Translates keyDown and keyUp events to X11 -keysym values. - -* __Display__ (core/display.js): Efficient 2D rendering abstraction -layered on the HTML5 canvas element. - -* __Websock__ (core/websock.js): Websock client from websockify -with transparent binary data support. -[Websock API](https://github.com/novnc/websockify/wiki/websock.js) wiki page. - - -## 1.2 Callbacks - -For the Mouse, Keyboard and Display objects the callback functions are -assigned to configuration attributes, just as for the RFB object. The -WebSock module has a method named 'on' that takes two parameters: the -callback event name, and the callback function. - -## 2. Modules - -## 2.1 Mouse Module - -### 2.1.1 Configuration Attributes - -| name | type | mode | default | description -| ----------- | ---- | ---- | -------- | ------------ -| touchButton | int | RW | 1 | Button mask (1, 2, 4) for which click to send on touch devices. 0 means ignore clicks. - -### 2.1.2 Methods - -| name | parameters | description -| ------ | ---------- | ------------ -| grab | () | Begin capturing mouse events -| ungrab | () | Stop capturing mouse events - -### 2.1.2 Callbacks - -| name | parameters | description -| ------------- | ------------------- | ------------ -| onmousebutton | (x, y, down, bmask) | Handler for mouse button click/release -| onmousemove | (x, y) | Handler for mouse movement - - -## 2.2 Keyboard Module - -### 2.2.1 Configuration Attributes - -None - -### 2.2.2 Methods - -| name | parameters | description -| ------ | ---------- | ------------ -| grab | () | Begin capturing keyboard events -| ungrab | () | Stop capturing keyboard events - -### 2.2.3 Callbacks - -| name | parameters | description -| ---------- | -------------------- | ------------ -| onkeypress | (keysym, code, down) | Handler for key press/release - - -## 2.3 Display Module - -### 2.3.1 Configuration Attributes - -| name | type | mode | default | description -| ------------ | ----- | ---- | ------- | ------------ -| logo | raw | RW | | Logo to display when cleared: {"width": width, "height": height, "type": mime-type, "data": data} -| scale | float | RW | 1.0 | Display area scale factor 0.0 - 1.0 -| clipViewport | bool | RW | false | Use viewport clipping -| width | int | RO | | Display area width -| height | int | RO | | Display area height - -### 2.3.2 Methods - -| name | parameters | description -| ------------------ | ------------------------------------------------------- | ------------ -| viewportChangePos | (deltaX, deltaY) | Move the viewport relative to the current location -| viewportChangeSize | (width, height) | Change size of the viewport -| absX | (x) | Return X relative to the remote display -| absY | (y) | Return Y relative to the remote display -| resize | (width, height) | Set width and height -| flip | (from_queue) | Update the visible canvas with the contents of the rendering canvas -| clear | () | Clear the display (show logo if set) -| pending | () | Check if there are waiting items in the render queue -| flush | () | Resume processing the render queue unless it's empty -| fillRect | (x, y, width, height, color, from_queue) | Draw a filled in rectangle -| copyImage | (old_x, old_y, new_x, new_y, width, height, from_queue) | Copy a rectangular area -| imageRect | (x, y, mime, arr) | Draw a rectangle with an image -| startTile | (x, y, width, height, color) | Begin updating a tile -| subTile | (tile, x, y, w, h, color) | Update a sub-rectangle within the given tile -| finishTile | () | Draw the current tile to the display -| blitImage | (x, y, width, height, arr, offset, from_queue) | Blit pixels (of R,G,B,A) to the display -| blitRgbImage | (x, y, width, height, arr, offset, from_queue) | Blit RGB encoded image to display -| blitRgbxImage | (x, y, width, height, arr, offset, from_queue) | Blit RGBX encoded image to display -| drawImage | (img, x, y) | Draw image and track damage -| autoscale | (containerWidth, containerHeight) | Scale the display - -### 2.3.3 Callbacks - -| name | parameters | description -| ------- | ---------- | ------------ -| onflush | () | A display flush has been requested and we are now ready to resume FBU processing diff --git a/kasmweb/docs/API.md b/kasmweb/docs/API.md deleted file mode 100644 index d587429..0000000 --- a/kasmweb/docs/API.md +++ /dev/null @@ -1,375 +0,0 @@ -# noVNC API - -The interface of the noVNC client consists of a single RFB object that -is instantiated once per connection. - -## RFB - -The `RFB` object represents a single connection to a VNC server. It -communicates using a WebSocket that must provide a standard RFB -protocol stream. - -### Constructor - -[`RFB()`](#rfb-1) - - Creates and returns a new `RFB` object. - -### Properties - -`viewOnly` - - Is a `boolean` indicating if any events (e.g. key presses or mouse - movement) should be prevented from being sent to the server. - Disabled by default. - -`focusOnClick` - - Is a `boolean` indicating if keyboard focus should automatically be - moved to the remote session when a `mousedown` or `touchstart` - event is received. - -`touchButton` - - Is a `long` controlling the button mask that should be simulated - when a touch event is recieved. Uses the same values as - [`MouseEvent.button`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button). - Is set to `1` by default. - -`clipViewport` - - Is a `boolean` indicating if the remote session should be clipped - to its container. When disabled scrollbars will be shown to handle - the resulting overflow. Disabled by default. - -`dragViewport` - - Is a `boolean` indicating if mouse events should control the - relative position of a clipped remote session. Only relevant if - `clipViewport` is enabled. Disabled by default. - -`scaleViewport` - - Is a `boolean` indicating if the remote session should be scaled - locally so it fits its container. When disabled it will be centered - if the remote session is smaller than its container, or handled - according to `clipViewport` if it is larger. Disabled by default. - -`resizeSession` - - Is a `boolean` indicating if a request to resize the remote session - should be sent whenever the container changes dimensions. Disabled - by default. - -`showDotCursor` - - Is a `boolean` indicating whether a dot cursor should be shown - instead of a zero-sized or fully-transparent cursor if the server - sets such invisible cursor. Disabled by default. - -`background` - - Is a valid CSS [background](https://developer.mozilla.org/en-US/docs/Web/CSS/background) - style value indicating which background style should be applied - to the element containing the remote session screen. The default value is `rgb(40, 40, 40)` - (solid gray color). - -`capabilities` *Read only* - - Is an `Object` indicating which optional extensions are available - on the server. Some methods may only be called if the corresponding - capability is set. The following capabilities are defined: - - | name | type | description - | -------- | --------- | ----------- - | `power` | `boolean` | Machine power control is available - -### Events - -[`connect`](#connect) - - The `connect` event is fired when the `RFB` object has completed - the connection and handshaking with the server. - -[`disconnect`](#disconnected) - - The `disconnect` event is fired when the `RFB` object disconnects. - -[`credentialsrequired`](#credentialsrequired) - - The `credentialsrequired` event is fired when more credentials must - be given to continue. - -[`securityfailure`](#securityfailure) - - The `securityfailure` event is fired when the security negotiation - with the server fails. - -[`clipboard`](#clipboard) - - The `clipboard` event is fired when clipboard data is received from - the server. - -[`bell`](#bell) - - The `bell` event is fired when a audible bell request is received - from the server. - -[`desktopname`](#desktopname) - - The `desktopname` event is fired when the remote desktop name - changes. - -[`capabilities`](#capabilities) - - The `capabilities` event is fired when `RFB.capabilities` is - updated. - -### Methods - -[`RFB.disconnect()`](#rfbdisconnect) - - Disconnect from the server. - -[`RFB.sendCredentials()`](#rfbsendcredentials) - - Send credentials to server. Should be called after the - [`credentialsrequired`](#credentialsrequired) event has fired. - -[`RFB.sendKey()`](#rfbsendKey) - - Send a key event. - -[`RFB.sendCtrlAltDel()`](#rfbsendctrlaltdel) - - Send Ctrl-Alt-Del key sequence. - -[`RFB.focus()`](#rfbfocus) - - Move keyboard focus to the remote session. - -[`RFB.blur()`](#rfbblur) - - Remove keyboard focus from the remote session. - -[`RFB.machineShutdown()`](#rfbmachineshutdown) - - Request a shutdown of the remote machine. - -[`RFB.machineReboot()`](#rfbmachinereboot) - - Request a reboot of the remote machine. - -[`RFB.machineReset()`](#rfbmachinereset) - - Request a reset of the remote machine. - -[`RFB.clipboardPasteFrom()`](#rfbclipboardPasteFrom) - - Send clipboard contents to server. - -### Details - -#### RFB() - -The `RFB()` constructor returns a new `RFB` object and initiates a new -connection to a specified VNC server. - -##### Syntax - - let rfb = new RFB( target, url [, options] ); - -###### Parameters - -**`target`** - - A block [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) - that specifies where the `RFB` object should attach itself. The - existing contents of the `HTMLElement` will be untouched, but new - elements will be added during the lifetime of the `RFB` object. - -**`url`** - - A `DOMString` specifying the VNC server to connect to. This must be - a valid WebSocket URL. - -**`options`** *Optional* - - An `Object` specifying extra details about how the connection - should be made. - - Possible options: - - `shared` - - A `boolean` indicating if the remote server should be shared or - if any other connected clients should be disconnected. Enabled - by default. - - `credentials` - - An `Object` specifying the credentials to provide to the server - when authenticating. The following credentials are possible: - - | name | type | description - | ------------ | ----------- | ----------- - | `"username"` | `DOMString` | The user that authenticates - | `"password"` | `DOMString` | Password for the user - | `"target"` | `DOMString` | Target machine or session - - `repeaterID` - - A `DOMString` specifying the ID to provide to any VNC repeater - encountered. - -#### connect - -The `connect` event is fired after all the handshaking with the server -is completed and the connection is fully established. After this event -the `RFB` object is ready to recieve graphics updates and to send input. - -#### disconnect - -The `disconnect` event is fired when the connection has been -terminated. The `detail` property is an `Object` that contains the -property `clean`. `clean` is a `boolean` indicating if the termination -was clean or not. In the event of an unexpected termination or an error -`clean` will be set to false. - -#### credentialsrequired - -The `credentialsrequired` event is fired when the server requests more -credentials than were specified to [`RFB()`](#rfb-1). The `detail` -property is an `Object` containing the property `types` which is an -`Array` of `DOMString` listing the credentials that are required. - -#### securityfailure - -The `securityfailure` event is fired when the handshaking process with -the server fails during the security negotiation step. The `detail` -property is an `Object` containing the following properties: - -| Property | Type | Description -| -------- | ----------- | ----------- -| `status` | `long` | The failure status code -| `reason` | `DOMString` | The **optional** reason for the failure - -The property `status` corresponds to the -[SecurityResult](https://github.com/rfbproto/rfbproto/blob/master/rfbproto.rst#securityresult) -status code in cases of failure. A status of zero will not be sent in -this event since that indicates a successful security handshaking -process. The optional property `reason` is provided by the server and -thus the language of the string is not known. However most servers will -probably send English strings. The server can choose to not send a -reason and in these cases the `reason` property will be omitted. - -#### clipboard - -The `clipboard` event is fired when the server has sent clipboard data. -The `detail` property is an `Object` containing the property `text` -which is a `DOMString` with the clipboard data. - -#### bell - -The `bell` event is fired when the server has requested an audible -bell. - -#### desktopname - -The `desktopname` event is fired when the name of the remote desktop -changes. The `detail` property is an `Object` with the property `name` -which is a `DOMString` specifying the new name. - -#### capabilities - -The `capabilities` event is fired whenever an entry is added or removed -from `RFB.capabilities`. The `detail` property is an `Object` with the -property `capabilities` containing the new value of `RFB.capabilities`. - -#### RFB.disconnect() - -The `RFB.disconnect()` method is used to disconnect from the currently -connected server. - -##### Syntax - - RFB.disconnect( ); - -#### RFB.sendCredentials() - -The `RFB.sendCredentials()` method is used to provide the missing -credentials after a `credentialsrequired` event has been fired. - -##### Syntax - - RFB.sendCredentials( credentials ); - -###### Parameters - -**`credentials`** - - An `Object` specifying the credentials to provide to the server - when authenticating. See [`RFB()`](#rfb-1) for details. - -#### RFB.sendKey() - -The `RFB.sendKey()` method is used to send a key event to the server. - -##### Syntax - - RFB.sendKey( keysym, code [, down] ); - -###### Parameters - -**`keysym`** - - A `long` specifying the RFB keysym to send. Can be `0` if a valid - **`code`** is specified. - -**`code`** - - A `DOMString` specifying the physical key to send. Valid values are - those that can be specified to - [`KeyboardEvent.code`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code). - If the physical key cannot be determined then `null` shall be - specified. - -**`down`** *Optional* - - A `boolean` specifying if a press or a release event should be - sent. If omitted then both a press and release event are sent. - -#### RFB.sendCtrlAltDel() - -The `RFB.sendCtrlAltDel()` method is used to send the key sequence -*left Control*, *left Alt*, *Delete*. This is a convenience wrapper -around [`RFB.sendKey()`](#rfbsendkey). - -##### Syntax - - RFB.sendCtrlAltDel( ); - -#### RFB.focus() - -The `RFB.focus()` method sets the keyboard focus on the remote session. -Keyboard events will be sent to the remote server after this point. - -##### Syntax - - RFB.focus( ); - -#### RFB.blur() - -The `RFB.blur()` method remove keyboard focus on the remote session. -Keyboard events will no longer be sent to the remote server after this -point. - -##### Syntax - - RFB.blur( ); - -#### RFB.machineShutdown() - -The `RFB.machineShutdown()` method is used to request to shut down the -remote machine. The capability `power` must be set for this method to -have any effect. - -##### Syntax - - RFB.machineShutdown( ); - -#### RFB.machineReboot() - -The `RFB.machineReboot()` method is used to request a clean reboot of -the remote machine. The capability `power` must be set for this method -to have any effect. - -##### Syntax - - RFB.machineReboot( ); - -#### RFB.machineReset() - -The `RFB.machineReset()` method is used to request a forced reset of -the remote machine. The capability `power` must be set for this method -to have any effect. - -##### Syntax - - RFB.machineReset( ); - -#### RFB.clipboardPasteFrom() - -The `RFB.clipboardPasteFrom()` method is used to send clipboard data -to the remote server. - -##### Syntax - - RFB.clipboardPasteFrom( text ); - -###### Parameters - -**`text`** - - A `DOMString` specifying the clipboard data to send. Currently only - characters from ISO 8859-1 are supported. diff --git a/kasmweb/docs/EMBEDDING.md b/kasmweb/docs/EMBEDDING.md deleted file mode 100644 index 5399b48..0000000 --- a/kasmweb/docs/EMBEDDING.md +++ /dev/null @@ -1,119 +0,0 @@ -# Embedding and Deploying noVNC Application - -This document describes how to embed and deploy the noVNC application, which -includes settings and a full user interface. If you are looking for -documentation on how to use the core noVNC library in your own application, -then please see our [library documentation](LIBRARY.md). - -## Files - -The noVNC application consists of the following files and directories: - -* `vnc.html` - The main page for the application and where users should go. It - is possible to rename this file. - -* `app/` - Support files for the application. Contains code, images, styles and - translations. - -* `core/` - The core noVNC library. - -* `vendor/` - Third party support libraries used by the application and the - core library. - -The most basic deployment consists of simply serving these files from a web -server and setting up a WebSocket proxy to the VNC server. - -## Parameters - -The noVNC application can be controlled by including certain settings in the -query string. Currently the following options are available: - -* `autoconnect` - Automatically connect as soon as the page has finished - loading. - -* `reconnect` - If noVNC should automatically reconnect if the connection is - dropped. - -* `reconnect_delay` - How long to wait in milliseconds before attempting to - reconnect. - -* `host` - The WebSocket host to connect to. - -* `port` - The WebSocket port to connect to. - -* `encrypt` - If TLS should be used for the WebSocket connection. - -* `path` - The WebSocket path to use. - -* `password` - The password sent to the server, if required. - -* `repeaterID` - The repeater ID to use if a VNC repeater is detected. - -* `shared` - If other VNC clients should be disconnected when noVNC connects. - -* `bell` - If the keyboard bell should be enabled or not. - -* `view_only` - If the remote session should be in non-interactive mode. - -* `view_clip` - If the remote session should be clipped or use scrollbars if - it cannot fit in the browser. - -* `resize` - How to resize the remote session if it is not the same size as - the browser window. Can be one of `off`, `scale` and `remote`. - -* `show_dot` - If a dot cursor should be shown when the remote server provides - no local cursor, or provides a fully-transparent (invisible) cursor. - -* `logging` - The console log level. Can be one of `error`, `warn`, `info` or - `debug`. - -## Pre-conversion of Modules - -noVNC is written using ECMAScript 6 modules. Many of the major browsers support -these modules natively, but not all. By default the noVNC application includes -a script that can convert these modules to an older format as they are being -loaded. However this process can be slow and severely increases the load time -for the application. - -It is possible to perform this conversion ahead of time, avoiding the extra -load times. To do this please follow these steps: - - 1. Install Node.js - 2. Run `npm install` in the noVNC directory - 3. Run `./utils/use_require.js --with-app --as commonjs` - -This will produce a `build/` directory that includes everything needed to run -the noVNC application. - -## HTTP Serving Considerations -### Browser Cache Issue - -If you serve noVNC files using a web server that provides an ETag header, and -include any options in the query string, a nasty browser cache issue can bite -you on upgrade, resulting in a red error box. The issue is caused by a mismatch -between the new vnc.html (which is reloaded because the user has used it with -new query string after the upgrade) and the old javascript files (that the -browser reuses from its cache). To avoid this issue, the browser must be told -to always revalidate cached files using conditional requests. The correct -semantics are achieved via the (confusingly named) `Cache-Control: no-cache` -header that needs to be provided in the web server responses. - -### Example Server Configurations - -Apache: - -``` - # In the main configuration file - # (Debian/Ubuntu users: use "a2enmod headers" instead) - LoadModule headers_module modules/mod_headers.so - - # In the or block related to noVNC - Header set Cache-Control "no-cache" -``` - -Nginx: - -``` - # In the location block related to noVNC - add_header Cache-Control no-cache; -``` diff --git a/kasmweb/docs/LIBRARY.md b/kasmweb/docs/LIBRARY.md deleted file mode 100644 index 63f55e8..0000000 --- a/kasmweb/docs/LIBRARY.md +++ /dev/null @@ -1,35 +0,0 @@ -# Using the noVNC JavaScript library - -This document describes how to make use of the noVNC JavaScript library for -integration in your own VNC client application. If you wish to embed the more -complete noVNC application with its included user interface then please see -our [embedding documentation](EMBEDDING.md). - -## API - -The API of noVNC consists of a single object called `RFB`. The formal -documentation for that object can be found in our [API documentation](API.md). - -## Example - -noVNC includes a small example application called `vnc_lite.html`. This does -not make use of all the features of noVNC, but is a good start to see how to -do things. - -## Conversion of Modules - -noVNC is written using ECMAScript 6 modules. Many of the major browsers support -these modules natively, but not all. They are also not supported by Node.js. To -use noVNC in these places the library must first be converted. - -Fortunately noVNC includes a script to handle this conversion. Please follow -the following steps: - - 1. Install Node.js - 2. Run `npm install` in the noVNC directory - 3. Run `./utils/use_require.js --as ` - -Several module formats are available. Please run -`./utils/use_require.js --help` to see them all. - -The result of the conversion is available in the `lib/` directory. diff --git a/kasmweb/docs/LICENSE.BSD-2-Clause b/kasmweb/docs/LICENSE.BSD-2-Clause deleted file mode 100644 index 9d66ec9..0000000 --- a/kasmweb/docs/LICENSE.BSD-2-Clause +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) , -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. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/kasmweb/docs/LICENSE.BSD-3-Clause b/kasmweb/docs/LICENSE.BSD-3-Clause deleted file mode 100644 index e160466..0000000 --- a/kasmweb/docs/LICENSE.BSD-3-Clause +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) , -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 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/kasmweb/docs/LICENSE.MPL-2.0 b/kasmweb/docs/LICENSE.MPL-2.0 deleted file mode 100644 index 14e2f77..0000000 --- a/kasmweb/docs/LICENSE.MPL-2.0 +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/kasmweb/docs/LICENSE.OFL-1.1 b/kasmweb/docs/LICENSE.OFL-1.1 deleted file mode 100644 index 77b1731..0000000 --- a/kasmweb/docs/LICENSE.OFL-1.1 +++ /dev/null @@ -1,91 +0,0 @@ -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/kasmweb/docs/flash_policy.txt b/kasmweb/docs/flash_policy.txt deleted file mode 100644 index df325c0..0000000 --- a/kasmweb/docs/flash_policy.txt +++ /dev/null @@ -1,4 +0,0 @@ -Manual setup: - -DATA="echo \'\'" -/usr/bin/socat -T 1 TCP-L:843,reuseaddr,fork,crlf SYSTEM:"$DATA" diff --git a/kasmweb/docs/links b/kasmweb/docs/links deleted file mode 100644 index 31544ce..0000000 --- a/kasmweb/docs/links +++ /dev/null @@ -1,76 +0,0 @@ -New tight PNG protocol: - http://wiki.qemu.org/VNC_Tight_PNG - http://xf.iksaif.net/blog/index.php?post/2010/06/14/QEMU:-Tight-PNG-and-some-profiling - -RFB protocol and extensions: - http://tigervnc.org/cgi-bin/rfbproto - -Canvas Browser Compatibility: - http://philip.html5.org/tests/canvas/suite/tests/results.html - -WebSockets API standard: - http://www.whatwg.org/specs/web-apps/current-work/complete.html#websocket - http://dev.w3.org/html5/websockets/ - http://www.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-00.txt - -Browser Keyboard Events detailed: - http://unixpapa.com/js/key.html - -ActionScript (Flash) WebSocket implementation: - http://github.com/gimite/web-socket-js - -ActionScript (Flash) crypto/TLS library: - http://code.google.com/p/as3crypto - http://github.com/lyokato/as3crypto_patched - -TLS Protocol: - http://en.wikipedia.org/wiki/Transport_Layer_Security - -Generate self-signed certificate: - http://docs.python.org/dev/library/ssl.html#certificates - -Cursor appearance/style (for Cursor pseudo-encoding): - http://en.wikipedia.org/wiki/ICO_(file_format) - http://www.daubnet.com/en/file-format-cur - https://developer.mozilla.org/en/Using_URL_values_for_the_cursor_property - http://www.fileformat.info/format/bmp/egff.htm - -Icon/Cursor file format: - http://msdn.microsoft.com/en-us/library/ms997538 - http://msdn.microsoft.com/en-us/library/aa921550.aspx - http://msdn.microsoft.com/en-us/library/aa930622.aspx - - -RDP Protocol specification: - http://msdn.microsoft.com/en-us/library/cc240445(v=PROT.10).aspx - - -Related projects: - - guacamole: http://guacamole.sourceforge.net/ - - - Web client, but Java servlet does pre-processing - - jsvnc: http://code.google.com/p/jsvnc/ - - - No releases - - webvnc: http://code.google.com/p/webvnc/ - - - Jetty web server gateway, no updates since April 2008. - - RealVNC Java applet: http://www.realvnc.com/support/javavncviewer.html - - - Java applet - - Flashlight-VNC: http://www.wizhelp.com/flashlight-vnc/ - - - Adobe Flash implementation - - FVNC: http://osflash.org/fvnc - - - Adbove Flash implementation - - CanVNC: http://canvnc.sourceforge.net/ - - - HTML client with REST to VNC python proxy. Mostly vapor. diff --git a/kasmweb/docs/notes b/kasmweb/docs/notes deleted file mode 100644 index dfef0bd..0000000 --- a/kasmweb/docs/notes +++ /dev/null @@ -1,5 +0,0 @@ -Rebuilding inflator.js - -- Download pako from npm -- Install browserify using npm -- browserify core/inflator.mod.js -o core/inflator.js -s Inflator diff --git a/kasmweb/docs/rfb_notes b/kasmweb/docs/rfb_notes deleted file mode 100644 index 643e16c..0000000 --- a/kasmweb/docs/rfb_notes +++ /dev/null @@ -1,147 +0,0 @@ -5.1.1 ProtocolVersion: 12, 12 bytes - - - Sent by server, max supported - 12 ascii - "RFB 003.008\n" - - Response by client, version to use - 12 ascii - "RFB 003.003\n" - -5.1.2 Authentication: >=4, [16, 4] bytes - - - Sent by server - CARD32 - authentication-scheme - 0 - connection failed - CARD32 - length - length - reason - 1 - no authentication - - 2 - VNC authentication - 16 CARD8 - challenge (random bytes) - - - Response by client (if VNC authentication) - 16 CARD8 - client encrypts the challenge with DES, using user - password as key, sends resulting 16 byte response - - - Response by server (if VNC authentication) - CARD32 - 0 - OK - 1 - failed - 2 - too-many - -5.1.3 ClientInitialisation: 1 byte - - Sent by client - CARD8 - shared-flag, 0 exclusive, non-zero shared - -5.1.4 ServerInitialisation: >=24 bytes - - Sent by server - CARD16 - framebuffer-width - CARD16 - framebuffer-height - 16 byte PIXEL_FORMAT - server-pixel-format - CARD8 - bits-per-pixel - CARD8 - depth - CARD8 - big-endian-flag, non-zero is big endian - CARD8 - true-color-flag, non-zero then next 6 apply - CARD16 - red-max - CARD16 - green-max - CARD16 - blue-max - CARD8 - red-shift - CARD8 - green-shift - CARD8 - blue-shift - 3 bytes - padding - CARD32 - name-length - - CARD8[length] - name-string - - - -Client to Server Messages: - -5.2.1 SetPixelFormat: 20 bytes - CARD8: 0 - message-type - ... - -5.2.2 FixColourMapEntries: >=6 bytes - CARD8: 1 - message-type - ... - -5.2.3 SetEncodings: >=8 bytes - CARD8: 2 - message-type - CARD8 - padding - CARD16 - numer-of-encodings - - CARD32 - encoding-type in preference order - 0 - raw - 1 - copy-rectangle - 2 - RRE - 4 - CoRRE - 5 - hextile - -5.2.4 FramebufferUpdateRequest (10 bytes) - CARD8: 3 - message-type - CARD8 - incremental (0 for full-update, non-zero for incremental) - CARD16 - x-position - CARD16 - y-position - CARD16 - width - CARD16 - height - - -5.2.5 KeyEvent: 8 bytes - CARD8: 4 - message-type - CARD8 - down-flag - 2 bytes - padding - CARD32 - key (X-Windows keysym values) - -5.2.6 PointerEvent: 6 bytes - CARD8: 5 - message-type - CARD8 - button-mask - CARD16 - x-position - CARD16 - y-position - -5.2.7 ClientCutText: >=9 bytes - CARD8: 6 - message-type - ... - - -Server to Client Messages: - -5.3.1 FramebufferUpdate - CARD8: 0 - message-type - 1 byte - padding - CARD16 - number-of-rectangles - - CARD16 - x-position - CARD16 - y-position - CARD16 - width - CARD16 - height - CARD16 - encoding-type: - 0 - raw - 1 - copy rectangle - 2 - RRE - 4 - CoRRE - 5 - hextile - - raw: - - width x height pixel values - - copy rectangle: - CARD16 - src-x-position - CARD16 - src-y-position - - RRE: - CARD32 - N number-of-subrectangles - Nxd bytes - background-pixel-value (d bits-per-pixel) - - ... - -5.3.2 SetColourMapEntries (no support) - CARD8: 1 - message-type - ... - -5.3.3 Bell - CARD8: 2 - message-type - -5.3.4 ServerCutText - CARD8: 3 - message-type - - - - - diff --git a/kasmweb/docs/rfbproto-3.3.pdf b/kasmweb/docs/rfbproto-3.3.pdf deleted file mode 100644 index 56b8764..0000000 Binary files a/kasmweb/docs/rfbproto-3.3.pdf and /dev/null differ diff --git a/kasmweb/docs/rfbproto-3.7.pdf b/kasmweb/docs/rfbproto-3.7.pdf deleted file mode 100644 index 1ef5462..0000000 Binary files a/kasmweb/docs/rfbproto-3.7.pdf and /dev/null differ diff --git a/kasmweb/docs/rfbproto-3.8.pdf b/kasmweb/docs/rfbproto-3.8.pdf deleted file mode 100644 index 8f0730f..0000000 Binary files a/kasmweb/docs/rfbproto-3.8.pdf and /dev/null differ diff --git a/kasmweb/karma.conf.js b/kasmweb/karma.conf.js deleted file mode 100644 index 5cbd7a5..0000000 --- a/kasmweb/karma.conf.js +++ /dev/null @@ -1,134 +0,0 @@ -// Karma configuration - -module.exports = (config) => { - const customLaunchers = {}; - let browsers = []; - let useSauce = false; - - // use Sauce when running on Travis - if (process.env.TRAVIS_JOB_NUMBER) { - useSauce = true; - } - - if (useSauce && process.env.TEST_BROWSER_NAME && process.env.TEST_BROWSER_NAME != 'PhantomJS') { - const names = process.env.TEST_BROWSER_NAME.split(','); - const platforms = process.env.TEST_BROWSER_OS.split(','); - const versions = process.env.TEST_BROWSER_VERSION - ? process.env.TEST_BROWSER_VERSION.split(',') - : [null]; - - for (let i = 0; i < names.length; i++) { - for (let j = 0; j < platforms.length; j++) { - for (let k = 0; k < versions.length; k++) { - let launcher_name = 'sl_' + platforms[j].replace(/[^a-zA-Z0-9]/g, '') + '_' + names[i]; - if (versions[k]) { - launcher_name += '_' + versions[k]; - } - - customLaunchers[launcher_name] = { - base: 'SauceLabs', - browserName: names[i], - platform: platforms[j], - }; - - if (versions[i]) { - customLaunchers[launcher_name].version = versions[k]; - } - } - } - } - - browsers = Object.keys(customLaunchers); - } else { - useSauce = false; - //browsers = ['PhantomJS']; - browsers = []; - } - - const my_conf = { - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['mocha', 'sinon-chai'], - - // list of files / patterns to load in the browser (loaded in order) - files: [ - { pattern: 'app/localization.js', included: false }, - { pattern: 'app/webutil.js', included: false }, - { pattern: 'core/**/*.js', included: false }, - { pattern: 'vendor/pako/**/*.js', included: false }, - { pattern: 'vendor/browser-es-module-loader/dist/*.js*', included: false }, - { pattern: 'tests/test.*.js', included: false }, - { pattern: 'tests/fake.*.js', included: false }, - { pattern: 'tests/assertions.js', included: false }, - 'vendor/promise.js', - 'tests/karma-test-main.js', - ], - - client: { - mocha: { - // replace Karma debug page with mocha display - 'reporter': 'html', - 'ui': 'bdd' - } - }, - - // list of files to exclude - exclude: [ - ], - - customLaunchers: customLaunchers, - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: browsers, - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['mocha'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: true, - - // Increase timeout in case connection is slow/we run more browsers than possible - // (we currently get 3 for free, and we try to run 7, so it can take a while) - captureTimeout: 240000, - - // similarly to above - browserNoActivityTimeout: 100000, - }; - - if (useSauce) { - my_conf.reporters.push('saucelabs'); - my_conf.captureTimeout = 0; // use SL timeout - my_conf.sauceLabs = { - testName: 'noVNC Tests (all)', - startConnect: false, - tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER - }; - } - - config.set(my_conf); -}; diff --git a/kasmweb/load.html b/kasmweb/load.html deleted file mode 100644 index c294eea..0000000 --- a/kasmweb/load.html +++ /dev/null @@ -1,370 +0,0 @@ - - - - - - KasmVNC - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
Kasm encountered an error:
-
-
-
-
- -
- Loading statistics... -
- - -
- -
-
- -
- -

- - - viewport drag - - -
- No mousebutton - Left mousebutton - Middle mousebutton - Right mousebutton - Keyboard -
- - -
- Extra keys -
-
- Ctrl - Alt - Windows - Tab - Esc - Ctrl+Alt+Del -
-
-
- - - Shutdown/Reboot -
-
-
- Power -
- - - -
-
- - - Clipboard -
-
-
- Clipboard -
- -
- -
-
- - - Fullscreen - - - Settings -
-
-
    -
  • - Settings -
  • -
  • - -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • - - -
  • -
  • - - -
  • -

  • -
  • - -
  • -
  • - - -
  • -

  • -
  • -
    Advanced
    -
      -
    • - - -
    • -
    • -
      WebSocket
      -
        -
      • - -
      • -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
    • -

    • -
    • - -
    • -
    • - - -
    • -

    • -
    • - -
    • -

    • - -
    • - -
    • -
    -
  • -
-
-
- - - Disconnect - -
-
- -
- -
- - - - - -
-
- -
- Connect -
-
-
- - -
-
-
    -
  • - - -
  • -
  • - -
  • -
-
-
- - -
-
-
- -
-
-
- - -
- - -
- - - - diff --git a/kasmweb/package.json b/kasmweb/package.json deleted file mode 100644 index 266a5a0..0000000 --- a/kasmweb/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "name": "@novnc/novnc", - "version": "1.0.0", - "description": "An HTML5 VNC client", - "browser": "lib/rfb", - "directories": { - "lib": "lib", - "doc": "docs", - "test": "tests" - }, - "files": [ - "lib", - "AUTHORS", - "VERSION", - "docs/API.md", - "docs/LIBRARY.md", - "docs/LICENSE*", - "core", - "vendor/pako" - ], - "scripts": { - "lint": "eslint app core po tests utils", - "test": "karma start karma.conf.js", - "prepublish": "node ./utils/use_require.js --as commonjs --clean", - "build": "webpack --config webpack.config.js", - "build-production": "cross-env NODE_ENV=production webpack --config webpack.config.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/novnc/noVNC.git" - }, - "author": "Joel Martin (https://github.com/kanaka)", - "contributors": [ - "Solly Ross (https://github.com/directxman12)", - "Peter Åstrand (https://github.com/astrand)", - "Samuel Mannehed (https://github.com/samhed)", - "Pierre Ossman (https://github.com/CendioOssman)" - ], - "license": "MPL-2.0", - "bugs": { - "url": "https://github.com/novnc/noVNC/issues" - }, - "homepage": "https://github.com/novnc/noVNC", - "devDependencies": { - "@babel/core": "^7.12.10", - "@babel/preset-env": "^7.12.11", - "babel-core": "^6.22.1", - "babel-loader": "^8.2.2", - "babel-plugin-add-module-exports": "^0.2.1", - "babel-plugin-import-redirect": "*", - "babel-plugin-syntax-dynamic-import": "^6.18.0", - "babel-plugin-transform-es2015-modules-amd": "^6.22.0", - "babel-plugin-transform-es2015-modules-commonjs": "^6.18.0", - "babel-plugin-transform-es2015-modules-systemjs": "^6.22.0", - "babel-plugin-transform-es2015-modules-umd": "^6.22.0", - "babel-preset-es2015": "^6.24.1", - "babelify": "^7.3.0", - "browserify": "^13.1.0", - "chai": "^3.5.0", - "clean-webpack-plugin": "^3.0.0", - "commander": "^2.9.0", - "css-loader": "^5.0.1", - "css-minimizer-webpack-plugin": "^1.1.5", - "es-module-loader": "^2.1.0", - "eslint": "^4.16.0", - "file-loader": "^6.2.0", - "fs-extra": "^1.0.0", - "html-loader": "^1.3.2", - "html-webpack-inline-svg-plugin": "^2.3.0", - "html-webpack-plugin": "^4.5.0", - "jsdom": "*", - "karma": "^1.3.0", - "karma-mocha": "^1.3.0", - "karma-mocha-reporter": "^2.2.0", - "karma-sauce-launcher": "^1.0.0", - "karma-sinon-chai": "^2.0.0", - "mini-css-extract-plugin": "^1.3.3", - "mocha": "^3.1.2", - "node-getopt": "*", - "po2json": "*", - "postcss-loader": "^4.1.0", - "preload-webpack-plugin": "^3.0.0-beta.4", - "requirejs": "^2.3.2", - "rollup": "^0.41.4", - "rollup-plugin-node-resolve": "^2.0.0", - "sass": "^1.30.0", - "sass-loader": "^10.1.0", - "sinon": "^4.0.0", - "sinon-chai": "^2.8.0", - "svg-sprite-html-webpack": "^2.3.0", - "webpack": "^4.29.6", - "webpack-cli": "^3.2.3" - }, - "dependencies": {}, - "keywords": [ - "vnc", - "rfb", - "novnc", - "websockify" - ] -} diff --git a/kasmweb/po/Makefile b/kasmweb/po/Makefile deleted file mode 100644 index f9756bd..0000000 --- a/kasmweb/po/Makefile +++ /dev/null @@ -1,35 +0,0 @@ -all: -.PHONY: update-po update-js update-pot - -LINGUAS := cs de el es ko nl pl sv tr zh_CN zh_TW - -VERSION := $(shell grep '"version"' ../package.json | cut -d '"' -f 4) - -POFILES := $(addsuffix .po,$(LINGUAS)) -JSONFILES := $(addprefix ../app/locale/,$(addsuffix .json,$(LINGUAS))) - -update-po: $(POFILES) -update-js: $(JSONFILES) - -%.po: noVNC.pot - msgmerge --update --lang=$* $@ $< -../app/locale/%.json: %.po - ./po2js $< $@ - -update-pot: - xgettext --output=noVNC.js.pot \ - --copyright-holder="The noVNC Authors" \ - --package-name="noVNC" \ - --package-version="$(VERSION)" \ - --msgid-bugs-address="novnc@googlegroups.com" \ - --add-comments=TRANSLATORS: \ - --from-code=UTF-8 \ - --sort-by-file \ - ../app/*.js \ - ../core/*.js \ - ../core/input/*.js - ./xgettext-html --output=noVNC.html.pot \ - ../vnc.html - msgcat --output-file=noVNC.pot \ - --sort-by-file noVNC.js.pot noVNC.html.pot - rm -f noVNC.js.pot noVNC.html.pot diff --git a/kasmweb/po/cs.po b/kasmweb/po/cs.po deleted file mode 100644 index 2b1efd8..0000000 --- a/kasmweb/po/cs.po +++ /dev/null @@ -1,294 +0,0 @@ -# Czech translations for noVNC package. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Petr , 2018. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 1.0.0-testing.2\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2018-10-19 12:00+0200\n" -"PO-Revision-Date: 2018-10-19 12:00+0200\n" -"Last-Translator: Petr \n" -"Language-Team: Czech\n" -"Language: cs\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" - -#: ../app/ui.js:389 -msgid "Connecting..." -msgstr "Připojení..." - -#: ../app/ui.js:396 -msgid "Disconnecting..." -msgstr "Odpojení..." - -#: ../app/ui.js:402 -msgid "Reconnecting..." -msgstr "Obnova připojení..." - -#: ../app/ui.js:407 -msgid "Internal error" -msgstr "Vnitřní chyba" - -#: ../app/ui.js:997 -msgid "Must set host" -msgstr "Hostitel musí být nastavení" - -#: ../app/ui.js:1079 -msgid "Connected (encrypted) to " -msgstr "Připojení (šifrované) k " - -#: ../app/ui.js:1081 -msgid "Connected (unencrypted) to " -msgstr "Připojení (nešifrované) k " - -#: ../app/ui.js:1104 -msgid "Something went wrong, connection is closed" -msgstr "Něco se pokazilo, odpojeno" - -#: ../app/ui.js:1107 -msgid "Failed to connect to server" -msgstr "Chyba připojení k serveru" - -#: ../app/ui.js:1117 -msgid "Disconnected" -msgstr "Odpojeno" - -#: ../app/ui.js:1130 -msgid "New connection has been rejected with reason: " -msgstr "Nové připojení bylo odmítnuto s odůvodněním: " - -#: ../app/ui.js:1133 -msgid "New connection has been rejected" -msgstr "Nové připojení bylo odmítnuto" - -#: ../app/ui.js:1153 -msgid "Password is required" -msgstr "Je vyžadováno heslo" - -#: ../vnc.html:84 -msgid "noVNC encountered an error:" -msgstr "noVNC narazilo na chybu:" - -#: ../vnc.html:94 -msgid "Hide/Show the control bar" -msgstr "Skrýt/zobrazit ovládací panel" - -#: ../vnc.html:101 -msgid "Move/Drag Viewport" -msgstr "Přesunout/přetáhnout výřez" - -#: ../vnc.html:101 -msgid "viewport drag" -msgstr "přesun výřezu" - -#: ../vnc.html:107 ../vnc.html:110 ../vnc.html:113 ../vnc.html:116 -msgid "Active Mouse Button" -msgstr "Aktivní tlačítka myši" - -#: ../vnc.html:107 -msgid "No mousebutton" -msgstr "Žádné" - -#: ../vnc.html:110 -msgid "Left mousebutton" -msgstr "Levé tlačítko myši" - -#: ../vnc.html:113 -msgid "Middle mousebutton" -msgstr "Prostřední tlačítko myši" - -#: ../vnc.html:116 -msgid "Right mousebutton" -msgstr "Pravé tlačítko myši" - -#: ../vnc.html:119 -msgid "Keyboard" -msgstr "Klávesnice" - -#: ../vnc.html:119 -msgid "Show Keyboard" -msgstr "Zobrazit klávesnici" - -#: ../vnc.html:126 -msgid "Extra keys" -msgstr "Extra klávesy" - -#: ../vnc.html:126 -msgid "Show Extra Keys" -msgstr "Zobrazit extra klávesy" - -#: ../vnc.html:131 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:131 -msgid "Toggle Ctrl" -msgstr "Přepnout Ctrl" - -#: ../vnc.html:134 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:134 -msgid "Toggle Alt" -msgstr "Přepnout Alt" - -#: ../vnc.html:137 -msgid "Send Tab" -msgstr "Odeslat tabulátor" - -#: ../vnc.html:137 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:140 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:140 -msgid "Send Escape" -msgstr "Odeslat Esc" - -#: ../vnc.html:143 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl+Alt+Del" - -#: ../vnc.html:143 -msgid "Send Ctrl-Alt-Del" -msgstr "Poslat Ctrl-Alt-Del" - -#: ../vnc.html:151 -msgid "Shutdown/Reboot" -msgstr "Vypnutí/Restart" - -#: ../vnc.html:151 -msgid "Shutdown/Reboot..." -msgstr "Vypnutí/Restart..." - -#: ../vnc.html:157 -msgid "Power" -msgstr "Napájení" - -#: ../vnc.html:159 -msgid "Shutdown" -msgstr "Vypnout" - -#: ../vnc.html:160 -msgid "Reboot" -msgstr "Restart" - -#: ../vnc.html:161 -msgid "Reset" -msgstr "Reset" - -#: ../vnc.html:166 ../vnc.html:172 -msgid "Clipboard" -msgstr "Schránka" - -#: ../vnc.html:176 -msgid "Clear" -msgstr "Vymazat" - -#: ../vnc.html:182 -msgid "Fullscreen" -msgstr "Celá obrazovka" - -#: ../vnc.html:187 ../vnc.html:194 -msgid "Settings" -msgstr "Nastavení" - -#: ../vnc.html:197 -msgid "Shared Mode" -msgstr "Sdílený režim" - -#: ../vnc.html:200 -msgid "View Only" -msgstr "Pouze prohlížení" - -#: ../vnc.html:204 -msgid "Clip to Window" -msgstr "Přizpůsobit oknu" - -#: ../vnc.html:207 -msgid "Scaling Mode:" -msgstr "Přizpůsobení velikosti" - -#: ../vnc.html:209 -msgid "None" -msgstr "Žádné" - -#: ../vnc.html:210 -msgid "Local Scaling" -msgstr "Místní" - -#: ../vnc.html:211 -msgid "Remote Resizing" -msgstr "Vzdálené" - -#: ../vnc.html:216 -msgid "Advanced" -msgstr "Pokročilé" - -#: ../vnc.html:219 -msgid "Repeater ID:" -msgstr "ID opakovače" - -#: ../vnc.html:223 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:226 -msgid "Encrypt" -msgstr "Šifrování:" - -#: ../vnc.html:229 -msgid "Host:" -msgstr "Hostitel:" - -#: ../vnc.html:233 -msgid "Port:" -msgstr "Port:" - -#: ../vnc.html:237 -msgid "Path:" -msgstr "Cesta" - -#: ../vnc.html:244 -msgid "Automatic Reconnect" -msgstr "Automatická obnova připojení" - -#: ../vnc.html:247 -msgid "Reconnect Delay (ms):" -msgstr "Zpoždění připojení (ms)" - -#: ../vnc.html:252 -msgid "Show Dot when No Cursor" -msgstr "Tečka místo chybějícího kurzoru myši" - -#: ../vnc.html:257 -msgid "Logging:" -msgstr "Logování:" - -#: ../vnc.html:269 -msgid "Disconnect" -msgstr "Odpojit" - -#: ../vnc.html:288 -msgid "Connect" -msgstr "Připojit" - -#: ../vnc.html:298 -msgid "Password:" -msgstr "Heslo" - -#: ../vnc.html:302 -msgid "Send Password" -msgstr "Odeslat heslo" - -#: ../vnc.html:312 -msgid "Cancel" -msgstr "Zrušit" diff --git a/kasmweb/po/de.po b/kasmweb/po/de.po deleted file mode 100644 index 0c3fa0d..0000000 --- a/kasmweb/po/de.po +++ /dev/null @@ -1,303 +0,0 @@ -# German translations for noVNC package -# German translation for noVNC. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Loek Janssen , 2016. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 0.6.1\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-11-24 07:16+0000\n" -"PO-Revision-Date: 2017-11-24 08:20+0100\n" -"Last-Translator: Dominik Csapak \n" -"Language-Team: none\n" -"Language: de\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" -"X-Generator: Poedit 1.8.11\n" - -#: ../app/ui.js:404 -msgid "Connecting..." -msgstr "Verbinden..." - -#: ../app/ui.js:411 -msgid "Disconnecting..." -msgstr "Verbindung trennen..." - -#: ../app/ui.js:417 -msgid "Reconnecting..." -msgstr "Verbindung wiederherstellen..." - -#: ../app/ui.js:422 -msgid "Internal error" -msgstr "Interner Fehler" - -#: ../app/ui.js:1019 -msgid "Must set host" -msgstr "Richten Sie den Server ein" - -#: ../app/ui.js:1099 -msgid "Connected (encrypted) to " -msgstr "Verbunden mit (verschlüsselt) " - -#: ../app/ui.js:1101 -msgid "Connected (unencrypted) to " -msgstr "Verbunden mit (unverschlüsselt) " - -#: ../app/ui.js:1119 -msgid "Something went wrong, connection is closed" -msgstr "Etwas lief schief, Verbindung wurde getrennt" - -#: ../app/ui.js:1129 -msgid "Disconnected" -msgstr "Verbindung zum Server getrennt" - -#: ../app/ui.js:1142 -msgid "New connection has been rejected with reason: " -msgstr "Verbindung wurde aus folgendem Grund abgelehnt: " - -#: ../app/ui.js:1145 -msgid "New connection has been rejected" -msgstr "Verbindung wurde abgelehnt" - -#: ../app/ui.js:1166 -msgid "Password is required" -msgstr "Passwort ist erforderlich" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "Ein Fehler ist aufgetreten:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Kontrollleiste verstecken/anzeigen" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Ansichtsfenster verschieben/ziehen" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "Ansichtsfenster ziehen" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Aktive Maustaste" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Keine Maustaste" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Linke Maustaste" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Mittlere Maustaste" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Rechte Maustaste" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Tastatur" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Tastatur anzeigen" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Zusatztasten" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Zusatztasten anzeigen" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Strg" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Strg umschalten" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Alt umschalten" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Tab senden" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Escape senden" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Strg+Alt+Entf" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Strg+Alt+Entf senden" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Herunterfahren/Neustarten" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Herunterfahren/Neustarten..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Energie" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Herunterfahren" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Neustarten" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Zurücksetzen" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Zwischenablage" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Löschen" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Vollbild" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Einstellungen" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Geteilter Modus" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Nur betrachten" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Auf Fenster begrenzen" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Skalierungsmodus:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Keiner" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Lokales skalieren" - -#: ../vnc.html:216 -msgid "Remote Resizing" -msgstr "Serverseitiges skalieren" - -#: ../vnc.html:221 -msgid "Advanced" -msgstr "Erweitert" - -#: ../vnc.html:224 -msgid "Repeater ID:" -msgstr "Repeater ID:" - -#: ../vnc.html:228 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:231 -msgid "Encrypt" -msgstr "Verschlüsselt" - -#: ../vnc.html:234 -msgid "Host:" -msgstr "Server:" - -#: ../vnc.html:238 -msgid "Port:" -msgstr "Port:" - -#: ../vnc.html:242 -msgid "Path:" -msgstr "Pfad:" - -#: ../vnc.html:249 -msgid "Automatic Reconnect" -msgstr "Automatisch wiederverbinden" - -#: ../vnc.html:252 -msgid "Reconnect Delay (ms):" -msgstr "Wiederverbindungsverzögerung (ms):" - -#: ../vnc.html:258 -msgid "Logging:" -msgstr "Protokollierung:" - -#: ../vnc.html:270 -msgid "Disconnect" -msgstr "Verbindung trennen" - -#: ../vnc.html:289 -msgid "Connect" -msgstr "Verbinden" - -#: ../vnc.html:299 -msgid "Password:" -msgstr "Passwort:" - -#: ../vnc.html:313 -msgid "Cancel" -msgstr "Abbrechen" - -#: ../vnc.html:329 -msgid "Canvas not supported." -msgstr "Canvas nicht unterstützt." - -#~ msgid "Disconnect timeout" -#~ msgstr "Zeitüberschreitung beim Trennen" - -#~ msgid "Local Downscaling" -#~ msgstr "Lokales herunterskalieren" - -#~ msgid "Local Cursor" -#~ msgstr "Lokaler Mauszeiger" - -#~ msgid "Forcing clipping mode since scrollbars aren't supported by IE in fullscreen" -#~ msgstr "'Clipping-Modus' aktiviert, Scrollbalken in 'IE-Vollbildmodus' werden nicht unterstützt" - -#~ msgid "True Color" -#~ msgstr "True Color" diff --git a/kasmweb/po/el.po b/kasmweb/po/el.po deleted file mode 100644 index 5213ae5..0000000 --- a/kasmweb/po/el.po +++ /dev/null @@ -1,323 +0,0 @@ -# Greek translations for noVNC package. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Giannis Kosmas , 2016. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 0.6.1\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-11-17 21:40+0200\n" -"PO-Revision-Date: 2017-10-11 16:16+0200\n" -"Last-Translator: Giannis Kosmas \n" -"Language-Team: none\n" -"Language: el\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" - -#: ../app/ui.js:404 -msgid "Connecting..." -msgstr "Συνδέεται..." - -#: ../app/ui.js:411 -msgid "Disconnecting..." -msgstr "Aποσυνδέεται..." - -#: ../app/ui.js:417 -msgid "Reconnecting..." -msgstr "Επανασυνδέεται..." - -#: ../app/ui.js:422 -msgid "Internal error" -msgstr "Εσωτερικό σφάλμα" - -#: ../app/ui.js:1019 -msgid "Must set host" -msgstr "Πρέπει να οριστεί ο διακομιστής" - -#: ../app/ui.js:1099 -msgid "Connected (encrypted) to " -msgstr "Συνδέθηκε (κρυπτογραφημένα) με το " - -#: ../app/ui.js:1101 -msgid "Connected (unencrypted) to " -msgstr "Συνδέθηκε (μη κρυπτογραφημένα) με το " - -#: ../app/ui.js:1119 -msgid "Something went wrong, connection is closed" -msgstr "Κάτι πήγε στραβά, η σύνδεση διακόπηκε" - -#: ../app/ui.js:1129 -msgid "Disconnected" -msgstr "Αποσυνδέθηκε" - -#: ../app/ui.js:1142 -msgid "New connection has been rejected with reason: " -msgstr "Η νέα σύνδεση απορρίφθηκε διότι: " - -#: ../app/ui.js:1145 -msgid "New connection has been rejected" -msgstr "Η νέα σύνδεση απορρίφθηκε " - -#: ../app/ui.js:1166 -msgid "Password is required" -msgstr "Απαιτείται ο κωδικός πρόσβασης" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "το noVNC αντιμετώπισε ένα σφάλμα:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Απόκρυψη/Εμφάνιση γραμμής ελέγχου" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Μετακίνηση/Σύρσιμο Θεατού πεδίου" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "σύρσιμο θεατού πεδίου" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Ενεργό Πλήκτρο Ποντικιού" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Χωρίς Πλήκτρο Ποντικιού" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Αριστερό Πλήκτρο Ποντικιού" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Μεσαίο Πλήκτρο Ποντικιού" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Δεξί Πλήκτρο Ποντικιού" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Πληκτρολόγιο" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Εμφάνιση Πληκτρολογίου" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Επιπλέον πλήκτρα" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Εμφάνιση Επιπλέον Πλήκτρων" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Εναλλαγή Ctrl" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Εναλλαγή Alt" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Αποστολή Tab" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Αποστολή Escape" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl+Alt+Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Αποστολή Ctrl-Alt-Del" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Κλείσιμο/Επανεκκίνηση" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Κλείσιμο/Επανεκκίνηση..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Απενεργοποίηση" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Κλείσιμο" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Επανεκκίνηση" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Επαναφορά" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Πρόχειρο" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Καθάρισμα" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Πλήρης Οθόνη" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Ρυθμίσεις" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Κοινόχρηστη Λειτουργία" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Μόνο Θέαση" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Αποκοπή στο όριο του Παράθυρου" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Λειτουργία Κλιμάκωσης:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Καμία" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Τοπική Κλιμάκωση" - -#: ../vnc.html:216 -msgid "Remote Resizing" -msgstr "Απομακρυσμένη Αλλαγή μεγέθους" - -#: ../vnc.html:221 -msgid "Advanced" -msgstr "Για προχωρημένους" - -#: ../vnc.html:224 -msgid "Repeater ID:" -msgstr "Repeater ID:" - -#: ../vnc.html:228 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:231 -msgid "Encrypt" -msgstr "Κρυπτογράφηση" - -#: ../vnc.html:234 -msgid "Host:" -msgstr "Όνομα διακομιστή:" - -#: ../vnc.html:238 -msgid "Port:" -msgstr "Πόρτα διακομιστή:" - -#: ../vnc.html:242 -msgid "Path:" -msgstr "Διαδρομή:" - -#: ../vnc.html:249 -msgid "Automatic Reconnect" -msgstr "Αυτόματη επανασύνδεση" - -#: ../vnc.html:252 -msgid "Reconnect Delay (ms):" -msgstr "Καθυστέρηση επανασύνδεσης (ms):" - -#: ../vnc.html:258 -msgid "Logging:" -msgstr "Καταγραφή:" - -#: ../vnc.html:270 -msgid "Disconnect" -msgstr "Αποσύνδεση" - -#: ../vnc.html:289 -msgid "Connect" -msgstr "Σύνδεση" - -#: ../vnc.html:299 -msgid "Password:" -msgstr "Κωδικός Πρόσβασης:" - -#: ../vnc.html:313 -msgid "Cancel" -msgstr "Ακύρωση" - -#: ../vnc.html:329 -msgid "Canvas not supported." -msgstr "Δεν υποστηρίζεται το στοιχείο Canvas" - -#~ msgid "Disconnect timeout" -#~ msgstr "Παρέλευση χρονικού ορίου αποσύνδεσης" - -#~ msgid "Local Downscaling" -#~ msgstr "Τοπική Συρρίκνωση" - -#~ msgid "Local Cursor" -#~ msgstr "Τοπικός Δρομέας" - -#~ msgid "" -#~ "Forcing clipping mode since scrollbars aren't supported by IE in " -#~ "fullscreen" -#~ msgstr "" -#~ "Εφαρμογή λειτουργίας αποκοπής αφού δεν υποστηρίζονται οι λωρίδες κύλισης " -#~ "σε πλήρη οθόνη στον IE" - -#~ msgid "True Color" -#~ msgstr "Πραγματικά Χρώματα" - -#~ msgid "Style:" -#~ msgstr "Στυλ:" - -#~ msgid "default" -#~ msgstr "προεπιλεγμένο" - -#~ msgid "Apply" -#~ msgstr "Εφαρμογή" - -#~ msgid "Connection" -#~ msgstr "Σύνδεση" - -#~ msgid "Token:" -#~ msgstr "Διακριτικό:" - -#~ msgid "Send Password" -#~ msgstr "Αποστολή Κωδικού Πρόσβασης" diff --git a/kasmweb/po/es.po b/kasmweb/po/es.po deleted file mode 100644 index e15655f..0000000 --- a/kasmweb/po/es.po +++ /dev/null @@ -1,283 +0,0 @@ -# Spanish translations for noVNC package -# Traducciones al español para el paquete noVNC. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Juanjo Diaz , 2018. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 1.0.0-testing.2\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-10-06 10:07+0200\n" -"PO-Revision-Date: 2018-01-30 19:14-0800\n" -"Last-Translator: Juanjo Diaz \n" -"Language-Team: Spanish\n" -"Language: es\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" - -#: ../app/ui.js:430 -msgid "Connecting..." -msgstr "Conectando..." - -#: ../app/ui.js:438 -msgid "Connected (encrypted) to " -msgstr "Conectado (con encriptación) a" - -#: ../app/ui.js:440 -msgid "Connected (unencrypted) to " -msgstr "Conectado (sin encriptación) a" - -#: ../app/ui.js:446 -msgid "Disconnecting..." -msgstr "Desconectando..." - -#: ../app/ui.js:450 -msgid "Disconnected" -msgstr "Desconectado" - -#: ../app/ui.js:1052 ../core/rfb.js:248 -msgid "Must set host" -msgstr "Debes configurar el host" - -#: ../app/ui.js:1101 -msgid "Reconnecting..." -msgstr "Reconectando..." - -#: ../app/ui.js:1140 -msgid "Password is required" -msgstr "Contraseña es obligatoria" - -#: ../core/rfb.js:548 -msgid "Disconnect timeout" -msgstr "Tiempo de desconexión agotado" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "noVNC ha encontrado un error:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Ocultar/Mostrar la barra de control" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Mover/Arrastrar la ventana" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "Arrastrar la ventana" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Botón activo del ratón" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Ningún botón del ratón" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Botón izquierdo del ratón" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Botón central del ratón" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Botón derecho del ratón" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Teclado" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Mostrar teclado" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Teclas adicionales" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Mostrar Teclas Adicionales" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Pulsar/Soltar Ctrl" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Pulsar/Soltar Alt" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Enviar Tabulación" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tabulación" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Enviar Escape" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl+Alt+Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Enviar Ctrl+Alt+Del" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Apagar/Reiniciar" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Apagar/Reiniciar..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Encender" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Apagar" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Reiniciar" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Restablecer" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Portapapeles" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Vaciar" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Pantalla Completa" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Configuraciones" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Modo Compartido" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Solo visualización" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Recortar al tamaño de la ventana" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Modo de escalado:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Ninguno" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Escalado Local" - -#: ../vnc.html:216 -msgid "Local Downscaling" -msgstr "Reducción de escala local" - -#: ../vnc.html:217 -msgid "Remote Resizing" -msgstr "Cambio de tamaño remoto" - -#: ../vnc.html:222 -msgid "Advanced" -msgstr "Avanzado" - -#: ../vnc.html:225 -msgid "Local Cursor" -msgstr "Cursor Local" - -#: ../vnc.html:229 -msgid "Repeater ID:" -msgstr "ID del Repetidor" - -#: ../vnc.html:233 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:236 -msgid "Encrypt" -msgstr "" - -#: ../vnc.html:239 -msgid "Host:" -msgstr "Host" - -#: ../vnc.html:243 -msgid "Port:" -msgstr "Puesto" - -#: ../vnc.html:247 -msgid "Path:" -msgstr "Ruta" - -#: ../vnc.html:254 -msgid "Automatic Reconnect" -msgstr "Reconexión automática" - -#: ../vnc.html:257 -msgid "Reconnect Delay (ms):" -msgstr "Retraso en la reconexión (ms)" - -#: ../vnc.html:263 -msgid "Logging:" -msgstr "Logging" - -#: ../vnc.html:275 -msgid "Disconnect" -msgstr "Desconectar" - -#: ../vnc.html:294 -msgid "Connect" -msgstr "Conectar" - -#: ../vnc.html:304 -msgid "Password:" -msgstr "Contraseña" - -#: ../vnc.html:318 -msgid "Cancel" -msgstr "Cancelar" - -#: ../vnc.html:334 -msgid "Canvas not supported." -msgstr "Canvas no está soportado" diff --git a/kasmweb/po/ko.po b/kasmweb/po/ko.po deleted file mode 100644 index 87ae106..0000000 --- a/kasmweb/po/ko.po +++ /dev/null @@ -1,290 +0,0 @@ -# SOME DESCRIPTIVE TITLE. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Baw Appie , 2018. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: noVNC 1.0.0-testing.2\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2018-01-31 16:29+0100\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: Baw Appie \n" -"Language-Team: Korean\n" -"Language: ko\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" - -#: ../app/ui.js:395 -msgid "Connecting..." -msgstr "연결중..." - -#: ../app/ui.js:402 -msgid "Disconnecting..." -msgstr "연결 해제중..." - -#: ../app/ui.js:408 -msgid "Reconnecting..." -msgstr "재연결중..." - -#: ../app/ui.js:413 -msgid "Internal error" -msgstr "내부 오류" - -#: ../app/ui.js:1002 -msgid "Must set host" -msgstr "호스트는 설정되어야 합니다." - -#: ../app/ui.js:1083 -msgid "Connected (encrypted) to " -msgstr "다음과 (암호화되어) 연결되었습니다:" - -#: ../app/ui.js:1085 -msgid "Connected (unencrypted) to " -msgstr "다음과 (암호화 없이) 연결되었습니다:" - -#: ../app/ui.js:1108 -msgid "Something went wrong, connection is closed" -msgstr "무언가 잘못되었습니다, 연결이 닫혔습니다." - -#: ../app/ui.js:1111 -msgid "Failed to connect to server" -msgstr "서버에 연결하지 못했습니다." - -#: ../app/ui.js:1121 -msgid "Disconnected" -msgstr "연결이 해제되었습니다." - -#: ../app/ui.js:1134 -msgid "New connection has been rejected with reason: " -msgstr "새 연결이 다음 이유로 거부되었습니다:" - -#: ../app/ui.js:1137 -msgid "New connection has been rejected" -msgstr "새 연결이 거부되었습니다." - -#: ../app/ui.js:1158 -msgid "Password is required" -msgstr "비밀번호가 필요합니다." - -#: ../vnc.html:91 -msgid "noVNC encountered an error:" -msgstr "noVNC에 오류가 발생했습니다:" - -#: ../vnc.html:101 -msgid "Hide/Show the control bar" -msgstr "컨트롤 바 숨기기/보이기" - -#: ../vnc.html:108 -msgid "Move/Drag Viewport" -msgstr "움직이기/드래그 뷰포트" - -#: ../vnc.html:108 -msgid "viewport drag" -msgstr "뷰포트 드래그" - -#: ../vnc.html:114 ../vnc.html:117 ../vnc.html:120 ../vnc.html:123 -msgid "Active Mouse Button" -msgstr "마우스 버튼 활성화" - -#: ../vnc.html:114 -msgid "No mousebutton" -msgstr "마우스 버튼 없음" - -#: ../vnc.html:117 -msgid "Left mousebutton" -msgstr "왼쪽 마우스 버튼" - -#: ../vnc.html:120 -msgid "Middle mousebutton" -msgstr "중간 마우스 버튼" - -#: ../vnc.html:123 -msgid "Right mousebutton" -msgstr "오른쪽 마우스 버튼" - -#: ../vnc.html:126 -msgid "Keyboard" -msgstr "키보드" - -#: ../vnc.html:126 -msgid "Show Keyboard" -msgstr "키보드 보이기" - -#: ../vnc.html:133 -msgid "Extra keys" -msgstr "기타 키들" - -#: ../vnc.html:133 -msgid "Show Extra Keys" -msgstr "기타 키들 보이기" - -#: ../vnc.html:138 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:138 -msgid "Toggle Ctrl" -msgstr "Ctrl 켜기/끄기" - -#: ../vnc.html:141 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:141 -msgid "Toggle Alt" -msgstr "Alt 켜기/끄기" - -#: ../vnc.html:144 -msgid "Send Tab" -msgstr "Tab 보내기" - -#: ../vnc.html:144 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:147 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:147 -msgid "Send Escape" -msgstr "Esc 보내기" - -#: ../vnc.html:150 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl+Alt+Del" - -#: ../vnc.html:150 -msgid "Send Ctrl-Alt-Del" -msgstr "Ctrl+Alt+Del 보내기" - -#: ../vnc.html:158 -msgid "Shutdown/Reboot" -msgstr "셧다운/리붓" - -#: ../vnc.html:158 -msgid "Shutdown/Reboot..." -msgstr "셧다운/리붓..." - -#: ../vnc.html:164 -msgid "Power" -msgstr "전원" - -#: ../vnc.html:166 -msgid "Shutdown" -msgstr "셧다운" - -#: ../vnc.html:167 -msgid "Reboot" -msgstr "리붓" - -#: ../vnc.html:168 -msgid "Reset" -msgstr "리셋" - -#: ../vnc.html:173 ../vnc.html:179 -msgid "Clipboard" -msgstr "클립보드" - -#: ../vnc.html:183 -msgid "Clear" -msgstr "지우기" - -#: ../vnc.html:189 -msgid "Fullscreen" -msgstr "전체화면" - -#: ../vnc.html:194 ../vnc.html:201 -msgid "Settings" -msgstr "설정" - -#: ../vnc.html:204 -msgid "Shared Mode" -msgstr "공유 모드" - -#: ../vnc.html:207 -msgid "View Only" -msgstr "보기 전용" - -#: ../vnc.html:211 -msgid "Clip to Window" -msgstr "창에 클립" - -#: ../vnc.html:214 -msgid "Scaling Mode:" -msgstr "스케일링 모드:" - -#: ../vnc.html:216 -msgid "None" -msgstr "없음" - -#: ../vnc.html:217 -msgid "Local Scaling" -msgstr "로컬 스케일링" - -#: ../vnc.html:218 -msgid "Remote Resizing" -msgstr "원격 크기 조절" - -#: ../vnc.html:223 -msgid "Advanced" -msgstr "고급" - -#: ../vnc.html:226 -msgid "Repeater ID:" -msgstr "중계 ID" - -#: ../vnc.html:230 -msgid "WebSocket" -msgstr "웹소켓" - -#: ../vnc.html:233 -msgid "Encrypt" -msgstr "암호화" - -#: ../vnc.html:236 -msgid "Host:" -msgstr "호스트:" - -#: ../vnc.html:240 -msgid "Port:" -msgstr "포트:" - -#: ../vnc.html:244 -msgid "Path:" -msgstr "위치:" - -#: ../vnc.html:251 -msgid "Automatic Reconnect" -msgstr "자동 재연결" - -#: ../vnc.html:254 -msgid "Reconnect Delay (ms):" -msgstr "재연결 지연 시간 (ms)" - -#: ../vnc.html:260 -msgid "Logging:" -msgstr "로깅" - -#: ../vnc.html:272 -msgid "Disconnect" -msgstr "연결 해제" - -#: ../vnc.html:291 -msgid "Connect" -msgstr "연결" - -#: ../vnc.html:301 -msgid "Password:" -msgstr "비밀번호:" - -#: ../vnc.html:305 -msgid "Send Password" -msgstr "비밀번호 전송" - -#: ../vnc.html:315 -msgid "Cancel" -msgstr "취소" diff --git a/kasmweb/po/nl.po b/kasmweb/po/nl.po deleted file mode 100644 index 410e620..0000000 --- a/kasmweb/po/nl.po +++ /dev/null @@ -1,290 +0,0 @@ -# Dutch translations for noVNC package -# Nederlandse vertalingen voor het pakket noVNC. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Loek Janssen , 2016. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 0.6.1\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-10-06 10:07+0200\n" -"PO-Revision-Date: 2017-10-11 16:16+0200\n" -"Last-Translator: Yuri van Oers \n" -"Language-Team: none\n" -"Language: nl\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" - -#: ../app/ui.js:430 -msgid "Connecting..." -msgstr "Verbinden..." - -#: ../app/ui.js:438 -msgid "Connected (encrypted) to " -msgstr "Verbonden (versleuteld) met " - -#: ../app/ui.js:440 -msgid "Connected (unencrypted) to " -msgstr "Verbonden (onversleuteld) met " - -#: ../app/ui.js:446 -msgid "Disconnecting..." -msgstr "Verbinding verbreken..." - -#: ../app/ui.js:450 -msgid "Disconnected" -msgstr "Verbinding verbroken" - -#: ../app/ui.js:1052 ../core/rfb.js:248 -msgid "Must set host" -msgstr "Host moeten worden ingesteld" - -#: ../app/ui.js:1101 -msgid "Reconnecting..." -msgstr "Opnieuw verbinding maken..." - -#: ../app/ui.js:1140 -msgid "Password is required" -msgstr "Wachtwoord is vereist" - -#: ../core/rfb.js:548 -msgid "Disconnect timeout" -msgstr "Timeout tijdens verbreken van verbinding" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "noVNC heeft een fout bemerkt:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Verberg/Toon de bedieningsbalk" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Verplaats/Versleep Kijkvenster" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "kijkvenster slepen" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Actieve Muisknop" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Geen muisknop" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Linker muisknop" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Middelste muisknop" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Rechter muisknop" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Toetsenbord" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Toon Toetsenbord" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Extra toetsen" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Toon Extra Toetsen" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Ctrl aan/uitzetten" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Alt aan/uitzetten" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Tab Sturen" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Escape Sturen" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl-Alt-Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Ctrl-Alt-Del Sturen" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Uitschakelen/Herstarten" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Uitschakelen/Herstarten..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Systeem" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Uitschakelen" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Herstarten" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Resetten" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Klembord" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Wissen" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Volledig Scherm" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Instellingen" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Gedeelde Modus" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Alleen Kijken" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Randen buiten venster afsnijden" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Schaalmodus:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Geen" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Lokaal Schalen" - -#: ../vnc.html:216 -msgid "Local Downscaling" -msgstr "Lokaal Neerschalen" - -#: ../vnc.html:217 -msgid "Remote Resizing" -msgstr "Op Afstand Formaat Wijzigen" - -#: ../vnc.html:222 -msgid "Advanced" -msgstr "Geavanceerd" - -#: ../vnc.html:225 -msgid "Local Cursor" -msgstr "Lokale Cursor" - -#: ../vnc.html:229 -msgid "Repeater ID:" -msgstr "Repeater ID:" - -#: ../vnc.html:233 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:236 -msgid "Encrypt" -msgstr "Versleutelen" - -#: ../vnc.html:239 -msgid "Host:" -msgstr "Host:" - -#: ../vnc.html:243 -msgid "Port:" -msgstr "Poort:" - -#: ../vnc.html:247 -msgid "Path:" -msgstr "Pad:" - -#: ../vnc.html:254 -msgid "Automatic Reconnect" -msgstr "Automatisch Opnieuw Verbinden" - -#: ../vnc.html:257 -msgid "Reconnect Delay (ms):" -msgstr "Vertraging voor Opnieuw Verbinden (ms):" - -#: ../vnc.html:263 -msgid "Logging:" -msgstr "Logmeldingen:" - -#: ../vnc.html:275 -msgid "Disconnect" -msgstr "Verbinding verbreken" - -#: ../vnc.html:294 -msgid "Connect" -msgstr "Verbinden" - -#: ../vnc.html:304 -msgid "Password:" -msgstr "Wachtwoord:" - -#: ../vnc.html:318 -msgid "Cancel" -msgstr "Annuleren" - -#: ../vnc.html:334 -msgid "Canvas not supported." -msgstr "Canvas wordt niet ondersteund." - -#~ msgid "" -#~ "Forcing clipping mode since scrollbars aren't supported by IE in " -#~ "fullscreen" -#~ msgstr "" -#~ "''Clipping mode' ingeschakeld, omdat schuifbalken in volledige-scherm-" -#~ "modus in IE niet worden ondersteund" diff --git a/kasmweb/po/noVNC.pot b/kasmweb/po/noVNC.pot deleted file mode 100644 index 200be01..0000000 --- a/kasmweb/po/noVNC.pot +++ /dev/null @@ -1,302 +0,0 @@ -# SOME DESCRIPTIVE TITLE. -# Copyright (C) YEAR The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# FIRST AUTHOR , YEAR. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: noVNC 1.1.0\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2019-01-16 11:06+0100\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"Language: \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=CHARSET\n" -"Content-Transfer-Encoding: 8bit\n" - -#: ../app/ui.js:387 -msgid "Connecting..." -msgstr "" - -#: ../app/ui.js:394 -msgid "Disconnecting..." -msgstr "" - -#: ../app/ui.js:400 -msgid "Reconnecting..." -msgstr "" - -#: ../app/ui.js:405 -msgid "Internal error" -msgstr "" - -#: ../app/ui.js:995 -msgid "Must set host" -msgstr "" - -#: ../app/ui.js:1077 -msgid "Connected (encrypted) to " -msgstr "" - -#: ../app/ui.js:1079 -msgid "Connected (unencrypted) to " -msgstr "" - -#: ../app/ui.js:1102 -msgid "Something went wrong, connection is closed" -msgstr "" - -#: ../app/ui.js:1105 -msgid "Failed to connect to server" -msgstr "" - -#: ../app/ui.js:1115 -msgid "Disconnected" -msgstr "" - -#: ../app/ui.js:1128 -msgid "New connection has been rejected with reason: " -msgstr "" - -#: ../app/ui.js:1131 -msgid "New connection has been rejected" -msgstr "" - -#: ../app/ui.js:1151 -msgid "Password is required" -msgstr "" - -#: ../vnc.html:84 -msgid "noVNC encountered an error:" -msgstr "" - -#: ../vnc.html:94 -msgid "Hide/Show the control bar" -msgstr "" - -#: ../vnc.html:101 -msgid "Move/Drag Viewport" -msgstr "" - -#: ../vnc.html:101 -msgid "viewport drag" -msgstr "" - -#: ../vnc.html:107 ../vnc.html:110 ../vnc.html:113 ../vnc.html:116 -msgid "Active Mouse Button" -msgstr "" - -#: ../vnc.html:107 -msgid "No mousebutton" -msgstr "" - -#: ../vnc.html:110 -msgid "Left mousebutton" -msgstr "" - -#: ../vnc.html:113 -msgid "Middle mousebutton" -msgstr "" - -#: ../vnc.html:116 -msgid "Right mousebutton" -msgstr "" - -#: ../vnc.html:119 -msgid "Keyboard" -msgstr "" - -#: ../vnc.html:119 -msgid "Show Keyboard" -msgstr "" - -#: ../vnc.html:126 -msgid "Extra keys" -msgstr "" - -#: ../vnc.html:126 -msgid "Show Extra Keys" -msgstr "" - -#: ../vnc.html:131 -msgid "Ctrl" -msgstr "" - -#: ../vnc.html:131 -msgid "Toggle Ctrl" -msgstr "" - -#: ../vnc.html:134 -msgid "Alt" -msgstr "" - -#: ../vnc.html:134 -msgid "Toggle Alt" -msgstr "" - -#: ../vnc.html:137 -msgid "Toggle Windows" -msgstr "" - -#: ../vnc.html:137 -msgid "Windows" -msgstr "" - -#: ../vnc.html:140 -msgid "Send Tab" -msgstr "" - -#: ../vnc.html:140 -msgid "Tab" -msgstr "" - -#: ../vnc.html:143 -msgid "Esc" -msgstr "" - -#: ../vnc.html:143 -msgid "Send Escape" -msgstr "" - -#: ../vnc.html:146 -msgid "Ctrl+Alt+Del" -msgstr "" - -#: ../vnc.html:146 -msgid "Send Ctrl-Alt-Del" -msgstr "" - -#: ../vnc.html:154 -msgid "Shutdown/Reboot" -msgstr "" - -#: ../vnc.html:154 -msgid "Shutdown/Reboot..." -msgstr "" - -#: ../vnc.html:160 -msgid "Power" -msgstr "" - -#: ../vnc.html:162 -msgid "Shutdown" -msgstr "" - -#: ../vnc.html:163 -msgid "Reboot" -msgstr "" - -#: ../vnc.html:164 -msgid "Reset" -msgstr "" - -#: ../vnc.html:169 ../vnc.html:175 -msgid "Clipboard" -msgstr "" - -#: ../vnc.html:179 -msgid "Clear" -msgstr "" - -#: ../vnc.html:185 -msgid "Fullscreen" -msgstr "" - -#: ../vnc.html:190 ../vnc.html:197 -msgid "Settings" -msgstr "" - -#: ../vnc.html:200 -msgid "Shared Mode" -msgstr "" - -#: ../vnc.html:203 -msgid "View Only" -msgstr "" - -#: ../vnc.html:207 -msgid "Clip to Window" -msgstr "" - -#: ../vnc.html:210 -msgid "Scaling Mode:" -msgstr "" - -#: ../vnc.html:212 -msgid "None" -msgstr "" - -#: ../vnc.html:213 -msgid "Local Scaling" -msgstr "" - -#: ../vnc.html:214 -msgid "Remote Resizing" -msgstr "" - -#: ../vnc.html:219 -msgid "Advanced" -msgstr "" - -#: ../vnc.html:222 -msgid "Repeater ID:" -msgstr "" - -#: ../vnc.html:226 -msgid "WebSocket" -msgstr "" - -#: ../vnc.html:229 -msgid "Encrypt" -msgstr "" - -#: ../vnc.html:232 -msgid "Host:" -msgstr "" - -#: ../vnc.html:236 -msgid "Port:" -msgstr "" - -#: ../vnc.html:240 -msgid "Path:" -msgstr "" - -#: ../vnc.html:247 -msgid "Automatic Reconnect" -msgstr "" - -#: ../vnc.html:250 -msgid "Reconnect Delay (ms):" -msgstr "" - -#: ../vnc.html:255 -msgid "Show Dot when No Cursor" -msgstr "" - -#: ../vnc.html:260 -msgid "Logging:" -msgstr "" - -#: ../vnc.html:272 -msgid "Disconnect" -msgstr "" - -#: ../vnc.html:291 -msgid "Connect" -msgstr "" - -#: ../vnc.html:301 -msgid "Password:" -msgstr "" - -#: ../vnc.html:305 -msgid "Send Password" -msgstr "" - -#: ../vnc.html:315 -msgid "Cancel" -msgstr "" diff --git a/kasmweb/po/pl.po b/kasmweb/po/pl.po deleted file mode 100644 index 5acfdc4..0000000 --- a/kasmweb/po/pl.po +++ /dev/null @@ -1,325 +0,0 @@ -# Polish translations for noVNC package. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Mariusz Jamro , 2017. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 0.6.1\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-11-21 19:53+0100\n" -"PO-Revision-Date: 2017-11-21 19:54+0100\n" -"Last-Translator: Mariusz Jamro \n" -"Language-Team: Polish\n" -"Language: pl\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 " -"|| n%100>=20) ? 1 : 2);\n" -"X-Generator: Poedit 2.0.1\n" - -#: ../app/ui.js:404 -msgid "Connecting..." -msgstr "Łączenie..." - -#: ../app/ui.js:411 -msgid "Disconnecting..." -msgstr "Rozłączanie..." - -#: ../app/ui.js:417 -msgid "Reconnecting..." -msgstr "Łączenie..." - -#: ../app/ui.js:422 -msgid "Internal error" -msgstr "Błąd wewnętrzny" - -#: ../app/ui.js:1019 -msgid "Must set host" -msgstr "Host i port są wymagane" - -#: ../app/ui.js:1099 -msgid "Connected (encrypted) to " -msgstr "Połączenie (szyfrowane) z " - -#: ../app/ui.js:1101 -msgid "Connected (unencrypted) to " -msgstr "Połączenie (nieszyfrowane) z " - -#: ../app/ui.js:1119 -msgid "Something went wrong, connection is closed" -msgstr "Coś poszło źle, połączenie zostało zamknięte" - -#: ../app/ui.js:1129 -msgid "Disconnected" -msgstr "Rozłączony" - -#: ../app/ui.js:1142 -msgid "New connection has been rejected with reason: " -msgstr "Nowe połączenie zostało odrzucone z powodu: " - -#: ../app/ui.js:1145 -msgid "New connection has been rejected" -msgstr "Nowe połączenie zostało odrzucone" - -#: ../app/ui.js:1166 -msgid "Password is required" -msgstr "Hasło jest wymagane" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "noVNC napotkało błąd:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Pokaż/Ukryj pasek ustawień" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Ruszaj/Przeciągaj Viewport" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "przeciągnij viewport" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Aktywny Przycisk Myszy" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Brak przycisku myszy" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Lewy przycisk myszy" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Środkowy przycisk myszy" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Prawy przycisk myszy" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Klawiatura" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Pokaż klawiaturę" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Przyciski dodatkowe" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Pokaż przyciski dodatkowe" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Przełącz Ctrl" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Przełącz Alt" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Wyślij Tab" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Wyślij Escape" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl+Alt+Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Wyślij Ctrl-Alt-Del" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Wyłącz/Uruchom ponownie" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Wyłącz/Uruchom ponownie..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Włączony" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Wyłącz" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Uruchom ponownie" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Resetuj" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Schowek" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Wyczyść" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Pełny ekran" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Ustawienia" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Tryb Współdzielenia" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Tylko Podgląd" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Przytnij do Okna" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Tryb Skalowania:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Brak" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Skalowanie lokalne" - -#: ../vnc.html:216 -msgid "Remote Resizing" -msgstr "Skalowanie zdalne" - -#: ../vnc.html:221 -msgid "Advanced" -msgstr "Zaawansowane" - -#: ../vnc.html:224 -msgid "Repeater ID:" -msgstr "ID Repeatera:" - -#: ../vnc.html:228 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:231 -msgid "Encrypt" -msgstr "Szyfrowanie" - -#: ../vnc.html:234 -msgid "Host:" -msgstr "Host:" - -#: ../vnc.html:238 -msgid "Port:" -msgstr "Port:" - -#: ../vnc.html:242 -msgid "Path:" -msgstr "Ścieżka:" - -#: ../vnc.html:249 -msgid "Automatic Reconnect" -msgstr "Automatycznie wznawiaj połączenie" - -#: ../vnc.html:252 -msgid "Reconnect Delay (ms):" -msgstr "Opóźnienie wznawiania (ms):" - -#: ../vnc.html:258 -msgid "Logging:" -msgstr "Poziom logowania:" - -#: ../vnc.html:270 -msgid "Disconnect" -msgstr "Rozłącz" - -#: ../vnc.html:289 -msgid "Connect" -msgstr "Połącz" - -#: ../vnc.html:299 -msgid "Password:" -msgstr "Hasło:" - -#: ../vnc.html:313 -msgid "Cancel" -msgstr "Anuluj" - -#: ../vnc.html:329 -msgid "Canvas not supported." -msgstr "Element Canvas nie jest wspierany." - -#~ msgid "Disconnect timeout" -#~ msgstr "Timeout rozłączenia" - -#~ msgid "Local Downscaling" -#~ msgstr "Downscaling lokalny" - -#~ msgid "Local Cursor" -#~ msgstr "Lokalny kursor" - -#~ msgid "" -#~ "Forcing clipping mode since scrollbars aren't supported by IE in " -#~ "fullscreen" -#~ msgstr "" -#~ "Wymuszam clipping mode ponieważ paski przewijania nie są wspierane przez " -#~ "IE w trybie pełnoekranowym" - -#~ msgid "True Color" -#~ msgstr "True Color" - -#~ msgid "Style:" -#~ msgstr "Styl:" - -#~ msgid "default" -#~ msgstr "domyślny" - -#~ msgid "Apply" -#~ msgstr "Zapisz" - -#~ msgid "Connection" -#~ msgstr "Połączenie" - -#~ msgid "Token:" -#~ msgstr "Token:" - -#~ msgid "Send Password" -#~ msgstr "Wyślij Hasło" diff --git a/kasmweb/po/po2js b/kasmweb/po/po2js deleted file mode 100755 index 03c1490..0000000 --- a/kasmweb/po/po2js +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env node -/* - * ps2js: gettext .po to noVNC .js converter - * Copyright (C) 2018 The noVNC Authors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -const getopt = require('node-getopt'); -const fs = require('fs'); -const po2json = require("po2json"); - -const opt = getopt.create([ - ['h' , 'help' , 'display this help'], -]).bindHelp().parseSystem(); - -if (opt.argv.length != 2) { - console.error("Incorrect number of arguments given"); - process.exit(1); -} - -const data = po2json.parseFileSync(opt.argv[0]); - -const bodyPart = Object.keys(data).filter((msgid) => msgid !== "").map((msgid) => { - if (msgid === "") return; - const msgstr = data[msgid][1]; - return " " + JSON.stringify(msgid) + ": " + JSON.stringify(msgstr); -}).join(",\n"); - -const output = "{\n" + bodyPart + "\n}"; - -fs.writeFileSync(opt.argv[1], output); diff --git a/kasmweb/po/sv.po b/kasmweb/po/sv.po deleted file mode 100644 index 6111fdd..0000000 --- a/kasmweb/po/sv.po +++ /dev/null @@ -1,284 +0,0 @@ -# Swedish translations for noVNC package -# Svenska översättningar för paket noVNC. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Samuel Mannehed , 2016. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 0.6.1\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-10-06 10:07+0200\n" -"PO-Revision-Date: 2017-10-06 10:18+0200\n" -"Last-Translator: Pierre Ossman \n" -"Language-Team: none\n" -"Language: sv\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" -"X-Generator: Poedit 2.0.3\n" - -#: ../app/ui.js:430 -msgid "Connecting..." -msgstr "Ansluter..." - -#: ../app/ui.js:438 -msgid "Connected (encrypted) to " -msgstr "Ansluten (krypterat) till " - -#: ../app/ui.js:440 -msgid "Connected (unencrypted) to " -msgstr "Ansluten (okrypterat) till " - -#: ../app/ui.js:446 -msgid "Disconnecting..." -msgstr "Kopplar ner..." - -#: ../app/ui.js:450 -msgid "Disconnected" -msgstr "Frånkopplad" - -#: ../app/ui.js:1052 ../core/rfb.js:248 -msgid "Must set host" -msgstr "Du måste specifiera en värd" - -#: ../app/ui.js:1101 -msgid "Reconnecting..." -msgstr "Återansluter..." - -#: ../app/ui.js:1140 -msgid "Password is required" -msgstr "Lösenord krävs" - -#: ../core/rfb.js:548 -msgid "Disconnect timeout" -msgstr "Det tog för lång tid att koppla ner" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "noVNC stötte på ett problem:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Göm/Visa kontrollbaren" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Flytta/Dra Vyn" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "dra vy" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Aktiv musknapp" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Ingen musknapp" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Vänster musknapp" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Mitten-musknapp" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Höger musknapp" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Tangentbord" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Visa Tangentbord" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Extraknappar" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Visa Extraknappar" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Växla Ctrl" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Växla Alt" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Skicka Tab" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Skicka Escape" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl+Alt+Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Skicka Ctrl-Alt-Del" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Stäng av/Boota om" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Stäng av/Boota om..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Ström" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Stäng av" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Boota om" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Återställ" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Urklipp" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Rensa" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Fullskärm" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Inställningar" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Delat Läge" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Endast Visning" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Begränsa till Fönster" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Skalningsläge:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Ingen" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Lokal Skalning" - -#: ../vnc.html:216 -msgid "Local Downscaling" -msgstr "Lokal Nedskalning" - -#: ../vnc.html:217 -msgid "Remote Resizing" -msgstr "Ändra Storlek" - -#: ../vnc.html:222 -msgid "Advanced" -msgstr "Avancerat" - -#: ../vnc.html:225 -msgid "Local Cursor" -msgstr "Lokal Muspekare" - -#: ../vnc.html:229 -msgid "Repeater ID:" -msgstr "Repeater-ID:" - -#: ../vnc.html:233 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:236 -msgid "Encrypt" -msgstr "Kryptera" - -#: ../vnc.html:239 -msgid "Host:" -msgstr "Värd:" - -#: ../vnc.html:243 -msgid "Port:" -msgstr "Port:" - -#: ../vnc.html:247 -msgid "Path:" -msgstr "Sökväg:" - -#: ../vnc.html:254 -msgid "Automatic Reconnect" -msgstr "Automatisk Återanslutning" - -#: ../vnc.html:257 -msgid "Reconnect Delay (ms):" -msgstr "Fördröjning (ms):" - -#: ../vnc.html:263 -msgid "Logging:" -msgstr "Loggning:" - -#: ../vnc.html:275 -msgid "Disconnect" -msgstr "Koppla från" - -#: ../vnc.html:294 -msgid "Connect" -msgstr "Anslut" - -#: ../vnc.html:304 -msgid "Password:" -msgstr "Lösenord:" - -#: ../vnc.html:318 -msgid "Cancel" -msgstr "Avbryt" - -#: ../vnc.html:334 -msgid "Canvas not supported." -msgstr "Canvas stöds ej" diff --git a/kasmweb/po/tr.po b/kasmweb/po/tr.po deleted file mode 100644 index 8b5c181..0000000 --- a/kasmweb/po/tr.po +++ /dev/null @@ -1,288 +0,0 @@ -# Turkish translations for noVNC package -# Turkish translation for noVNC. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Ömer ÇAKMAK , 2018. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 0.6.1\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2017-11-24 07:16+0000\n" -"PO-Revision-Date: 2018-01-05 19:07+0300\n" -"Last-Translator: Ömer ÇAKMAK \n" -"Language-Team: Türkçe \n" -"Language: tr\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=1; plural=0;\n" -"X-Generator: Gtranslator 2.91.7\n" - -#: ../app/ui.js:404 -msgid "Connecting..." -msgstr "Bağlanıyor..." - -#: ../app/ui.js:411 -msgid "Disconnecting..." -msgstr "Bağlantı kesiliyor..." - -#: ../app/ui.js:417 -msgid "Reconnecting..." -msgstr "Yeniden bağlantı kuruluyor..." - -#: ../app/ui.js:422 -msgid "Internal error" -msgstr "İç hata" - -#: ../app/ui.js:1019 -msgid "Must set host" -msgstr "Sunucuyu kur" - -#: ../app/ui.js:1099 -msgid "Connected (encrypted) to " -msgstr "Bağlı (şifrelenmiş)" - -#: ../app/ui.js:1101 -msgid "Connected (unencrypted) to " -msgstr "Bağlandı (şifrelenmemiş)" - -#: ../app/ui.js:1119 -msgid "Something went wrong, connection is closed" -msgstr "Bir şeyler ters gitti, bağlantı kesildi" - -#: ../app/ui.js:1129 -msgid "Disconnected" -msgstr "Bağlantı kesildi" - -#: ../app/ui.js:1142 -msgid "New connection has been rejected with reason: " -msgstr "Bağlantı aşağıdaki nedenlerden dolayı reddedildi: " - -#: ../app/ui.js:1145 -msgid "New connection has been rejected" -msgstr "Bağlantı reddedildi" - -#: ../app/ui.js:1166 -msgid "Password is required" -msgstr "Şifre gerekli" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "Bir hata oluştu:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "Denetim masasını Gizle/Göster" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "Görünümü Taşı/Sürükle" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "Görüntü penceresini sürükle" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "Aktif Fare Düğmesi" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "Fare düğmesi yok" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "Farenin sol düğmesi" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "Farenin orta düğmesi" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "Farenin sağ düğmesi" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "Klavye" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "Klavye Düzenini Göster" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "Ekstra tuşlar" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "Ekstra tuşları göster" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "Ctrl Değiştir " - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "Alt Değiştir" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "Sekme Gönder" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Sekme" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "Boşluk Gönder" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl + Alt + Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "Ctrl-Alt-Del Gönder" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "Kapat/Yeniden Başlat" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "Kapat/Yeniden Başlat..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "Güç" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "Kapat" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "Yeniden Başlat" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "Sıfırla" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "Pano" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "Temizle" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "Tam Ekran" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "Ayarlar" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "Paylaşım Modu" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "Sadece Görüntüle" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "Pencereye Tıkla" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "Ölçekleme Modu:" - -#: ../vnc.html:214 -msgid "None" -msgstr "Bilinmeyen" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "Yerel Ölçeklendirme" - -#: ../vnc.html:216 -msgid "Remote Resizing" -msgstr "Uzaktan Yeniden Boyutlandırma" - -#: ../vnc.html:221 -msgid "Advanced" -msgstr "Gelişmiş" - -#: ../vnc.html:224 -msgid "Repeater ID:" -msgstr "Tekralayıcı ID:" - -#: ../vnc.html:228 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:231 -msgid "Encrypt" -msgstr "Şifrele" - -#: ../vnc.html:234 -msgid "Host:" -msgstr "Ana makine:" - -#: ../vnc.html:238 -msgid "Port:" -msgstr "Port:" - -#: ../vnc.html:242 -msgid "Path:" -msgstr "Yol:" - -#: ../vnc.html:249 -msgid "Automatic Reconnect" -msgstr "Otomatik Yeniden Bağlan" - -#: ../vnc.html:252 -msgid "Reconnect Delay (ms):" -msgstr "Yeniden Bağlanma Süreci (ms):" - -#: ../vnc.html:258 -msgid "Logging:" -msgstr "Giriş yapılıyor:" - -#: ../vnc.html:270 -msgid "Disconnect" -msgstr "Bağlantıyı Kes" - -#: ../vnc.html:289 -msgid "Connect" -msgstr "Bağlan" - -#: ../vnc.html:299 -msgid "Password:" -msgstr "Parola:" - -#: ../vnc.html:313 -msgid "Cancel" -msgstr "Vazgeç" - -#: ../vnc.html:329 -msgid "Canvas not supported." -msgstr "Tuval desteklenmiyor." diff --git a/kasmweb/po/xgettext-html b/kasmweb/po/xgettext-html deleted file mode 100755 index 547f568..0000000 --- a/kasmweb/po/xgettext-html +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env node -/* - * xgettext-html: HTML gettext parser - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - */ - -const getopt = require('node-getopt'); -const jsdom = require("jsdom"); -const fs = require("fs"); - -const opt = getopt.create([ - ['o' , 'output=FILE' , 'write output to specified file'], - ['h' , 'help' , 'display this help'], -]).bindHelp().parseSystem(); - -const strings = {}; - -function addString(str, location) { - if (str.length == 0) { - return; - } - - if (strings[str] === undefined) { - strings[str] = {} - } - strings[str][location] = null; -} - -// See https://html.spec.whatwg.org/multipage/dom.html#attr-translate -function process(elem, locator, enabled) { - function isAnyOf(searchElement, items) { - return items.indexOf(searchElement) !== -1; - } - - if (elem.hasAttribute("translate")) { - if (isAnyOf(elem.getAttribute("translate"), ["", "yes"])) { - enabled = true; - } else if (isAnyOf(elem.getAttribute("translate"), ["no"])) { - enabled = false; - } - } - - if (enabled) { - if (elem.hasAttribute("abbr") && - elem.tagName === "TH") { - addString(elem.getAttribute("abbr"), locator(elem)); - } - if (elem.hasAttribute("alt") && - isAnyOf(elem.tagName, ["AREA", "IMG", "INPUT"])) { - addString(elem.getAttribute("alt"), locator(elem)); - } - if (elem.hasAttribute("download") && - isAnyOf(elem.tagName, ["A", "AREA"])) { - addString(elem.getAttribute("download"), locator(elem)); - } - if (elem.hasAttribute("label") && - isAnyOf(elem.tagName, ["MENUITEM", "MENU", "OPTGROUP", - "OPTION", "TRACK"])) { - addString(elem.getAttribute("label"), locator(elem)); - } - if (elem.hasAttribute("placeholder") && - isAnyOf(elem.tagName in ["INPUT", "TEXTAREA"])) { - addString(elem.getAttribute("placeholder"), locator(elem)); - } - if (elem.hasAttribute("title")) { - addString(elem.getAttribute("title"), locator(elem)); - } - if (elem.hasAttribute("value") && - elem.tagName === "INPUT" && - isAnyOf(elem.getAttribute("type"), ["reset", "button", "submit"])) { - addString(elem.getAttribute("value"), locator(elem)); - } - } - - for (let i = 0; i < elem.childNodes.length; i++) { - node = elem.childNodes[i]; - if (node.nodeType === node.ELEMENT_NODE) { - process(node, locator, enabled); - } else if (node.nodeType === node.TEXT_NODE && enabled) { - addString(node.data.trim(), locator(node)); - } - } -} - -for (let i = 0; i < opt.argv.length; i++) { - const fn = opt.argv[i]; - const file = fs.readFileSync(fn, "utf8"); - const dom = new jsdom.JSDOM(file, { includeNodeLocations: true }); - const body = dom.window.document.body; - - function locator(elem) { - const offset = dom.nodeLocation(elem).startOffset; - const line = file.slice(0, offset).split("\n").length; - return fn + ":" + line; - } - - process(body, locator, true); -} - -let output = ""; - -for (str in strings) { - output += "#:"; - for (location in strings[str]) { - output += " " + location; - } - output += "\n"; - - output += "msgid " + JSON.stringify(str) + "\n"; - output += "msgstr \"\"\n"; - output += "\n"; -} - -fs.writeFileSync(opt.options.output, output); diff --git a/kasmweb/po/zh_CN.po b/kasmweb/po/zh_CN.po deleted file mode 100644 index 78bfb95..0000000 --- a/kasmweb/po/zh_CN.po +++ /dev/null @@ -1,284 +0,0 @@ -# Simplified Chinese translations for noVNC package. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Peter Dave Hello , 2018. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 1.0.0-testing.2\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2018-01-10 00:53+0800\n" -"PO-Revision-Date: 2018-04-06 21:33+0800\n" -"Last-Translator: CUI Wei \n" -"Language: zh_CN\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" - -#: ../app/ui.js:395 -msgid "Connecting..." -msgstr "链接中..." - -#: ../app/ui.js:402 -msgid "Disconnecting..." -msgstr "正在中断连接..." - -#: ../app/ui.js:408 -msgid "Reconnecting..." -msgstr "重新链接中..." - -#: ../app/ui.js:413 -msgid "Internal error" -msgstr "内部错误" - -#: ../app/ui.js:1015 -msgid "Must set host" -msgstr "请提供主机名" - -#: ../app/ui.js:1097 -msgid "Connected (encrypted) to " -msgstr "已加密链接到" - -#: ../app/ui.js:1099 -msgid "Connected (unencrypted) to " -msgstr "未加密链接到" - -#: ../app/ui.js:1120 -msgid "Something went wrong, connection is closed" -msgstr "发生错误,链接已关闭" - -#: ../app/ui.js:1123 -msgid "Failed to connect to server" -msgstr "无法链接到服务器" - -#: ../app/ui.js:1133 -msgid "Disconnected" -msgstr "链接已中断" - -#: ../app/ui.js:1146 -msgid "New connection has been rejected with reason: " -msgstr "链接被拒绝,原因:" - -#: ../app/ui.js:1149 -msgid "New connection has been rejected" -msgstr "链接被拒绝" - -#: ../app/ui.js:1170 -msgid "Password is required" -msgstr "请提供密码" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "noVNC 遇到一个错误:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "显示/隐藏控制列" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "拖放显示范围" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "显示范围拖放" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "启动鼠标按鍵" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "禁用鼠标按鍵" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "鼠标左鍵" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "鼠标中鍵" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "鼠标右鍵" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "键盘" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "显示键盘" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "额外按键" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "显示额外按键" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "切换 Ctrl" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "切换 Alt" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "发送 Tab 键" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "发送 Escape 键" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl-Alt-Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "发送 Ctrl-Alt-Del 键" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "关机/重新启动" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "关机/重新启动..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "电源" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "关机" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "重新启动" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "重置" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "剪贴板" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "清除" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "全屏幕" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "设置" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "分享模式" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "仅检视" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "限制/裁切窗口大小" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "缩放模式:" - -#: ../vnc.html:214 -msgid "None" -msgstr "无" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "本地缩放" - -#: ../vnc.html:216 -msgid "Remote Resizing" -msgstr "远程调整大小" - -#: ../vnc.html:221 -msgid "Advanced" -msgstr "高级" - -#: ../vnc.html:224 -msgid "Repeater ID:" -msgstr "中继站 ID" - -#: ../vnc.html:228 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:231 -msgid "Encrypt" -msgstr "加密" - -#: ../vnc.html:234 -msgid "Host:" -msgstr "主机:" - -#: ../vnc.html:238 -msgid "Port:" -msgstr "端口:" - -#: ../vnc.html:242 -msgid "Path:" -msgstr "路径:" - -#: ../vnc.html:249 -msgid "Automatic Reconnect" -msgstr "自动重新链接" - -#: ../vnc.html:252 -msgid "Reconnect Delay (ms):" -msgstr "重新链接间隔 (ms):" - -#: ../vnc.html:258 -msgid "Logging:" -msgstr "日志级别:" - -#: ../vnc.html:270 -msgid "Disconnect" -msgstr "终端链接" - -#: ../vnc.html:289 -msgid "Connect" -msgstr "链接" - -#: ../vnc.html:299 -msgid "Password:" -msgstr "密码:" - -#: ../vnc.html:313 -msgid "Cancel" -msgstr "取消" diff --git a/kasmweb/po/zh_TW.po b/kasmweb/po/zh_TW.po deleted file mode 100644 index 9ddf550..0000000 --- a/kasmweb/po/zh_TW.po +++ /dev/null @@ -1,285 +0,0 @@ -# Traditional Chinese translations for noVNC package. -# Copyright (C) 2018 The noVNC Authors -# This file is distributed under the same license as the noVNC package. -# Peter Dave Hello , 2018. -# -msgid "" -msgstr "" -"Project-Id-Version: noVNC 1.0.0-testing.2\n" -"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2018-01-10 00:53+0800\n" -"PO-Revision-Date: 2018-01-10 01:33+0800\n" -"Last-Translator: Peter Dave Hello \n" -"Language-Team: Peter Dave Hello \n" -"Language: zh\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" - -#: ../app/ui.js:395 -msgid "Connecting..." -msgstr "連線中..." - -#: ../app/ui.js:402 -msgid "Disconnecting..." -msgstr "正在中斷連線..." - -#: ../app/ui.js:408 -msgid "Reconnecting..." -msgstr "重新連線中..." - -#: ../app/ui.js:413 -msgid "Internal error" -msgstr "內部錯誤" - -#: ../app/ui.js:1015 -msgid "Must set host" -msgstr "請提供主機資訊" - -#: ../app/ui.js:1097 -msgid "Connected (encrypted) to " -msgstr "已加密連線到" - -#: ../app/ui.js:1099 -msgid "Connected (unencrypted) to " -msgstr "未加密連線到" - -#: ../app/ui.js:1120 -msgid "Something went wrong, connection is closed" -msgstr "發生錯誤,連線已關閉" - -#: ../app/ui.js:1123 -msgid "Failed to connect to server" -msgstr "無法連線到伺服器" - -#: ../app/ui.js:1133 -msgid "Disconnected" -msgstr "連線已中斷" - -#: ../app/ui.js:1146 -msgid "New connection has been rejected with reason: " -msgstr "連線被拒絕,原因:" - -#: ../app/ui.js:1149 -msgid "New connection has been rejected" -msgstr "連線被拒絕" - -#: ../app/ui.js:1170 -msgid "Password is required" -msgstr "請提供密碼" - -#: ../vnc.html:89 -msgid "noVNC encountered an error:" -msgstr "noVNC 遇到一個錯誤:" - -#: ../vnc.html:99 -msgid "Hide/Show the control bar" -msgstr "顯示/隱藏控制列" - -#: ../vnc.html:106 -msgid "Move/Drag Viewport" -msgstr "拖放顯示範圍" - -#: ../vnc.html:106 -msgid "viewport drag" -msgstr "顯示範圍拖放" - -#: ../vnc.html:112 ../vnc.html:115 ../vnc.html:118 ../vnc.html:121 -msgid "Active Mouse Button" -msgstr "啟用滑鼠按鍵" - -#: ../vnc.html:112 -msgid "No mousebutton" -msgstr "無滑鼠按鍵" - -#: ../vnc.html:115 -msgid "Left mousebutton" -msgstr "滑鼠左鍵" - -#: ../vnc.html:118 -msgid "Middle mousebutton" -msgstr "滑鼠中鍵" - -#: ../vnc.html:121 -msgid "Right mousebutton" -msgstr "滑鼠右鍵" - -#: ../vnc.html:124 -msgid "Keyboard" -msgstr "鍵盤" - -#: ../vnc.html:124 -msgid "Show Keyboard" -msgstr "顯示鍵盤" - -#: ../vnc.html:131 -msgid "Extra keys" -msgstr "額外按鍵" - -#: ../vnc.html:131 -msgid "Show Extra Keys" -msgstr "顯示額外按鍵" - -#: ../vnc.html:136 -msgid "Ctrl" -msgstr "Ctrl" - -#: ../vnc.html:136 -msgid "Toggle Ctrl" -msgstr "切換 Ctrl" - -#: ../vnc.html:139 -msgid "Alt" -msgstr "Alt" - -#: ../vnc.html:139 -msgid "Toggle Alt" -msgstr "切換 Alt" - -#: ../vnc.html:142 -msgid "Send Tab" -msgstr "送出 Tab 鍵" - -#: ../vnc.html:142 -msgid "Tab" -msgstr "Tab" - -#: ../vnc.html:145 -msgid "Esc" -msgstr "Esc" - -#: ../vnc.html:145 -msgid "Send Escape" -msgstr "送出 Escape 鍵" - -#: ../vnc.html:148 -msgid "Ctrl+Alt+Del" -msgstr "Ctrl-Alt-Del" - -#: ../vnc.html:148 -msgid "Send Ctrl-Alt-Del" -msgstr "送出 Ctrl-Alt-Del 快捷鍵" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot" -msgstr "關機/重新啟動" - -#: ../vnc.html:156 -msgid "Shutdown/Reboot..." -msgstr "關機/重新啟動..." - -#: ../vnc.html:162 -msgid "Power" -msgstr "電源" - -#: ../vnc.html:164 -msgid "Shutdown" -msgstr "關機" - -#: ../vnc.html:165 -msgid "Reboot" -msgstr "重新啟動" - -#: ../vnc.html:166 -msgid "Reset" -msgstr "重設" - -#: ../vnc.html:171 ../vnc.html:177 -msgid "Clipboard" -msgstr "剪貼簿" - -#: ../vnc.html:181 -msgid "Clear" -msgstr "清除" - -#: ../vnc.html:187 -msgid "Fullscreen" -msgstr "全螢幕" - -#: ../vnc.html:192 ../vnc.html:199 -msgid "Settings" -msgstr "設定" - -#: ../vnc.html:202 -msgid "Shared Mode" -msgstr "分享模式" - -#: ../vnc.html:205 -msgid "View Only" -msgstr "僅檢視" - -#: ../vnc.html:209 -msgid "Clip to Window" -msgstr "限制/裁切視窗大小" - -#: ../vnc.html:212 -msgid "Scaling Mode:" -msgstr "縮放模式:" - -#: ../vnc.html:214 -msgid "None" -msgstr "無" - -#: ../vnc.html:215 -msgid "Local Scaling" -msgstr "本機縮放" - -#: ../vnc.html:216 -msgid "Remote Resizing" -msgstr "遠端調整大小" - -#: ../vnc.html:221 -msgid "Advanced" -msgstr "進階" - -#: ../vnc.html:224 -msgid "Repeater ID:" -msgstr "中繼站 ID" - -#: ../vnc.html:228 -msgid "WebSocket" -msgstr "WebSocket" - -#: ../vnc.html:231 -msgid "Encrypt" -msgstr "加密" - -#: ../vnc.html:234 -msgid "Host:" -msgstr "主機:" - -#: ../vnc.html:238 -msgid "Port:" -msgstr "連接埠:" - -#: ../vnc.html:242 -msgid "Path:" -msgstr "路徑:" - -#: ../vnc.html:249 -msgid "Automatic Reconnect" -msgstr "自動重新連線" - -#: ../vnc.html:252 -msgid "Reconnect Delay (ms):" -msgstr "重新連線間隔 (ms):" - -#: ../vnc.html:258 -msgid "Logging:" -msgstr "日誌級別:" - -#: ../vnc.html:270 -msgid "Disconnect" -msgstr "中斷連線" - -#: ../vnc.html:289 -msgid "Connect" -msgstr "連線" - -#: ../vnc.html:299 -msgid "Password:" -msgstr "密碼:" - -#: ../vnc.html:313 -msgid "Cancel" -msgstr "取消" diff --git a/kasmweb/tests/.eslintrc b/kasmweb/tests/.eslintrc deleted file mode 100644 index 545fa2e..0000000 --- a/kasmweb/tests/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "env": { - "node": true, - "mocha": true - }, - "globals": { - "chai": false, - "sinon": false - }, - "rules": { - "prefer-arrow-callback": 0, - // Too many anonymous callbacks - "func-names": "off", - } -} diff --git a/kasmweb/tests/assertions.js b/kasmweb/tests/assertions.js deleted file mode 100644 index 07a5c29..0000000 --- a/kasmweb/tests/assertions.js +++ /dev/null @@ -1,101 +0,0 @@ -// noVNC specific assertions -chai.use(function (_chai, utils) { - _chai.Assertion.addMethod('displayed', function (target_data) { - const obj = this._obj; - const ctx = obj._target.getContext('2d'); - const data_cl = ctx.getImageData(0, 0, obj._target.width, obj._target.height).data; - // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray, so work around that - const data = new Uint8Array(data_cl); - const len = data_cl.length; - new chai.Assertion(len).to.be.equal(target_data.length, "unexpected display size"); - let same = true; - for (let i = 0; i < len; i++) { - if (data[i] != target_data[i]) { - same = false; - break; - } - } - if (!same) { - // eslint-disable-next-line no-console - console.log("expected data: %o, actual data: %o", target_data, data); - } - this.assert(same, - "expected #{this} to have displayed the image #{exp}, but instead it displayed #{act}", - "expected #{this} not to have displayed the image #{act}", - target_data, - data); - }); - - _chai.Assertion.addMethod('sent', function (target_data) { - const obj = this._obj; - obj.inspect = () => { - const res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen), - _sQ: new Uint8Array(obj._sQ.buffer, 0, obj._sQlen) }; - res.prototype = obj; - return res; - }; - const data = obj._websocket._get_sent_data(); - let same = true; - if (data.length != target_data.length) { - same = false; - } else { - for (let i = 0; i < data.length; i++) { - if (data[i] != target_data[i]) { - same = false; - break; - } - } - } - if (!same) { - // eslint-disable-next-line no-console - console.log("expected data: %o, actual data: %o", target_data, data); - } - this.assert(same, - "expected #{this} to have sent the data #{exp}, but it actually sent #{act}", - "expected #{this} not to have sent the data #{act}", - Array.prototype.slice.call(target_data), - Array.prototype.slice.call(data)); - }); - - _chai.Assertion.addProperty('array', function () { - utils.flag(this, 'array', true); - }); - - _chai.Assertion.overwriteMethod('equal', function (_super) { - return function assertArrayEqual(target) { - if (utils.flag(this, 'array')) { - const obj = this._obj; - - let same = true; - - if (utils.flag(this, 'deep')) { - for (let i = 0; i < obj.length; i++) { - if (!utils.eql(obj[i], target[i])) { - same = false; - break; - } - } - - this.assert(same, - "expected #{this} to have elements deeply equal to #{exp}", - "expected #{this} not to have elements deeply equal to #{exp}", - Array.prototype.slice.call(target)); - } else { - for (let i = 0; i < obj.length; i++) { - if (obj[i] != target[i]) { - same = false; - break; - } - } - - this.assert(same, - "expected #{this} to have elements equal to #{exp}", - "expected #{this} not to have elements equal to #{exp}", - Array.prototype.slice.call(target)); - } - } else { - _super.apply(this, arguments); - } - }; - }); -}); diff --git a/kasmweb/tests/fake.websocket.js b/kasmweb/tests/fake.websocket.js deleted file mode 100644 index 2e1a3b9..0000000 --- a/kasmweb/tests/fake.websocket.js +++ /dev/null @@ -1,91 +0,0 @@ -import Base64 from '../core/base64.js'; - -// PhantomJS can't create Event objects directly, so we need to use this -function make_event(name, props) { - const evt = document.createEvent('Event'); - evt.initEvent(name, true, true); - if (props) { - for (let prop in props) { - evt[prop] = props[prop]; - } - } - return evt; -} - -export default class FakeWebSocket { - constructor(uri, protocols) { - this.url = uri; - this.binaryType = "arraybuffer"; - this.extensions = ""; - - if (!protocols || typeof protocols === 'string') { - this.protocol = protocols; - } else { - this.protocol = protocols[0]; - } - - this._send_queue = new Uint8Array(20000); - - this.readyState = FakeWebSocket.CONNECTING; - this.bufferedAmount = 0; - - this.__is_fake = true; - } - - close(code, reason) { - this.readyState = FakeWebSocket.CLOSED; - if (this.onclose) { - this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true })); - } - } - - send(data) { - if (this.protocol == 'base64') { - data = Base64.decode(data); - } else { - data = new Uint8Array(data); - } - this._send_queue.set(data, this.bufferedAmount); - this.bufferedAmount += data.length; - } - - _get_sent_data() { - const res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount); - this.bufferedAmount = 0; - return res; - } - - _open() { - this.readyState = FakeWebSocket.OPEN; - if (this.onopen) { - this.onopen(make_event('open')); - } - } - - _receive_data(data) { - this.onmessage(make_event("message", { 'data': data })); - } -} - -FakeWebSocket.OPEN = WebSocket.OPEN; -FakeWebSocket.CONNECTING = WebSocket.CONNECTING; -FakeWebSocket.CLOSING = WebSocket.CLOSING; -FakeWebSocket.CLOSED = WebSocket.CLOSED; - -FakeWebSocket.__is_fake = true; - -FakeWebSocket.replace = () => { - if (!WebSocket.__is_fake) { - const real_version = WebSocket; - // eslint-disable-next-line no-global-assign - WebSocket = FakeWebSocket; - FakeWebSocket.__real_version = real_version; - } -}; - -FakeWebSocket.restore = () => { - if (WebSocket.__is_fake) { - // eslint-disable-next-line no-global-assign - WebSocket = WebSocket.__real_version; - } -}; diff --git a/kasmweb/tests/karma-test-main.js b/kasmweb/tests/karma-test-main.js deleted file mode 100644 index 2843666..0000000 --- a/kasmweb/tests/karma-test-main.js +++ /dev/null @@ -1,48 +0,0 @@ -const TEST_REGEXP = /test\..*\.js/; -const allTestFiles = []; -const extraFiles = ['/base/tests/assertions.js']; - -Object.keys(window.__karma__.files).forEach(function (file) { - if (TEST_REGEXP.test(file)) { - // TODO: normalize? - allTestFiles.push(file); - } -}); - -// Stub out mocha's start function so we can run it once we're done loading -mocha.origRun = mocha.run; -mocha.run = function () {}; - -let script; - -// Script to import all our tests -script = document.createElement("script"); -script.type = "module"; -script.text = ""; -let allModules = allTestFiles.concat(extraFiles); -allModules.forEach(function (file) { - script.text += "import \"" + file + "\";\n"; -}); -script.text += "\nmocha.origRun();\n"; -document.body.appendChild(script); - -// Fallback code for browsers that don't support modules (IE) -script = document.createElement("script"); -script.type = "module"; -script.text = "window._noVNC_has_module_support = true;\n"; -document.body.appendChild(script); - -function fallback() { - if (!window._noVNC_has_module_support) { - /* eslint-disable no-console */ - if (console) { - console.log("No module support detected. Loading fallback..."); - } - /* eslint-enable no-console */ - let loader = document.createElement("script"); - loader.src = "base/vendor/browser-es-module-loader/dist/browser-es-module-loader.js"; - document.body.appendChild(loader); - } -} - -setTimeout(fallback, 500); diff --git a/kasmweb/tests/playback-ui.js b/kasmweb/tests/playback-ui.js deleted file mode 100644 index 65c715a..0000000 --- a/kasmweb/tests/playback-ui.js +++ /dev/null @@ -1,210 +0,0 @@ -/* global VNC_frame_data, VNC_frame_encoding */ - -import * as WebUtil from '../app/webutil.js'; -import RecordingPlayer from './playback.js'; -import Base64 from '../core/base64.js'; - -let frames = null; - -function message(str) { - const cell = document.getElementById('messages'); - cell.textContent += str + "\n"; - cell.scrollTop = cell.scrollHeight; -} - -function loadFile() { - const fname = WebUtil.getQueryVar('data', null); - - if (!fname) { - return Promise.reject("Must specify data=FOO in query string."); - } - - message("Loading " + fname + "..."); - - return new Promise((resolve, reject) => { - const script = document.createElement("script"); - script.onload = resolve; - script.onerror = reject; - document.body.appendChild(script); - script.src = "../recordings/" + fname; - }); -} - -function enableUI() { - const iterations = WebUtil.getQueryVar('iterations', 3); - document.getElementById('iterations').value = iterations; - - const mode = WebUtil.getQueryVar('mode', 3); - if (mode === 'realtime') { - document.getElementById('mode2').checked = true; - } else { - document.getElementById('mode1').checked = true; - } - - message("Loaded " + VNC_frame_data.length + " frames"); - - const startButton = document.getElementById('startButton'); - startButton.disabled = false; - startButton.addEventListener('click', start); - - message("Converting..."); - - frames = VNC_frame_data; - - let encoding; - // Only present in older recordings - if (window.VNC_frame_encoding) { - encoding = VNC_frame_encoding; - } else { - let frame = frames[0]; - let start = frame.indexOf('{', 1) + 1; - if (frame.slice(start, start+4) === 'UkZC') { - encoding = 'base64'; - } else { - encoding = 'binary'; - } - } - - for (let i = 0;i < frames.length;i++) { - let frame = frames[i]; - - if (frame === "EOF") { - frames.splice(i); - break; - } - - let dataIdx = frame.indexOf('{', 1) + 1; - - let time = parseInt(frame.slice(1, dataIdx - 1)); - - let u8; - if (encoding === 'base64') { - u8 = Base64.decode(frame.slice(dataIdx)); - } else { - u8 = new Uint8Array(frame.length - dataIdx); - for (let j = 0; j < frame.length - dataIdx; j++) { - u8[j] = frame.charCodeAt(dataIdx + j); - } - } - - frames[i] = { fromClient: frame[0] === '}', - timestamp: time, - data: u8 }; - } - - message("Ready"); -} - -class IterationPlayer { - constructor(iterations, frames) { - this._iterations = iterations; - - this._iteration = undefined; - this._player = undefined; - - this._start_time = undefined; - - this._frames = frames; - - this._state = 'running'; - - this.onfinish = () => {}; - this.oniterationfinish = () => {}; - this.rfbdisconnected = () => {}; - } - - start(realtime) { - this._iteration = 0; - this._start_time = (new Date()).getTime(); - - this._realtime = realtime; - - this._nextIteration(); - } - - _nextIteration() { - const player = new RecordingPlayer(this._frames, this._disconnected.bind(this)); - player.onfinish = this._iterationFinish.bind(this); - - if (this._state !== 'running') { return; } - - this._iteration++; - if (this._iteration > this._iterations) { - this._finish(); - return; - } - - player.run(this._realtime, false); - } - - _finish() { - const endTime = (new Date()).getTime(); - const totalDuration = endTime - this._start_time; - - const evt = new CustomEvent('finish', - { detail: - { duration: totalDuration, - iterations: this._iterations } } ); - this.onfinish(evt); - } - - _iterationFinish(duration) { - const evt = new CustomEvent('iterationfinish', - { detail: - { duration: duration, - number: this._iteration } } ); - this.oniterationfinish(evt); - - this._nextIteration(); - } - - _disconnected(clean, frame) { - if (!clean) { - this._state = 'failed'; - } - - const evt = new CustomEvent('rfbdisconnected', - { detail: - { clean: clean, - frame: frame, - iteration: this._iteration } } ); - this.onrfbdisconnected(evt); - } -} - -function start() { - document.getElementById('startButton').value = "Running"; - document.getElementById('startButton').disabled = true; - - const iterations = document.getElementById('iterations').value; - - let realtime; - - if (document.getElementById('mode1').checked) { - message(`Starting performance playback (fullspeed) [${iterations} iteration(s)]`); - realtime = false; - } else { - message(`Starting realtime playback [${iterations} iteration(s)]`); - realtime = true; - } - - const player = new IterationPlayer(iterations, frames); - player.oniterationfinish = (evt) => { - message(`Iteration ${evt.detail.number} took ${evt.detail.duration}ms`); - }; - player.onrfbdisconnected = (evt) => { - if (!evt.detail.clean) { - message(`noVNC sent disconnected during iteration ${evt.detail.iteration} frame ${evt.detail.frame}`); - } - }; - player.onfinish = (evt) => { - const iterTime = parseInt(evt.detail.duration / evt.detail.iterations, 10); - message(`${evt.detail.iterations} iterations took ${evt.detail.duration}ms (average ${iterTime}ms / iteration)`); - - document.getElementById('startButton').disabled = false; - document.getElementById('startButton').value = "Start"; - }; - player.start(realtime); -} - -loadFile().then(enableUI).catch(e => message("Error loading recording: " + e)); diff --git a/kasmweb/tests/playback.js b/kasmweb/tests/playback.js deleted file mode 100644 index 5bd8103..0000000 --- a/kasmweb/tests/playback.js +++ /dev/null @@ -1,172 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 (see LICENSE.txt) - */ - -import RFB from '../core/rfb.js'; -import * as Log from '../core/util/logging.js'; - -// Immediate polyfill -if (window.setImmediate === undefined) { - let _immediateIdCounter = 1; - const _immediateFuncs = {}; - - window.setImmediate = (func) => { - const index = _immediateIdCounter++; - _immediateFuncs[index] = func; - window.postMessage("noVNC immediate trigger:" + index, "*"); - return index; - }; - - window.clearImmediate = (id) => { - _immediateFuncs[id]; - }; - - window.addEventListener("message", (event) => { - if ((typeof event.data !== "string") || - (event.data.indexOf("noVNC immediate trigger:") !== 0)) { - return; - } - - const index = event.data.slice("noVNC immediate trigger:".length); - - const callback = _immediateFuncs[index]; - if (callback === undefined) { - return; - } - - delete _immediateFuncs[index]; - - callback(); - }); -} - -export default class RecordingPlayer { - constructor(frames, disconnected) { - this._frames = frames; - - this._disconnected = disconnected; - - this._rfb = undefined; - this._frame_length = this._frames.length; - - this._frame_index = 0; - this._start_time = undefined; - this._realtime = true; - this._trafficManagement = true; - - this._running = false; - - this.onfinish = () => {}; - } - - run(realtime, trafficManagement) { - // initialize a new RFB - this._rfb = new RFB(document.getElementById('VNC_screen'), 'wss://test'); - this._rfb.viewOnly = true; - this._rfb.addEventListener("disconnect", - this._handleDisconnect.bind(this)); - this._rfb.addEventListener("credentialsrequired", - this._handleCredentials.bind(this)); - this._enablePlaybackMode(); - - // reset the frame index and timer - this._frame_index = 0; - this._start_time = (new Date()).getTime(); - - this._realtime = realtime; - this._trafficManagement = (trafficManagement === undefined) ? !realtime : trafficManagement; - - this._running = true; - } - - // _enablePlaybackMode mocks out things not required for running playback - _enablePlaybackMode() { - const self = this; - this._rfb._sock.send = () => {}; - this._rfb._sock.close = () => {}; - this._rfb._sock.flush = () => {}; - this._rfb._sock.open = function () { - this.init(); - this._eventHandlers.open(); - self._queueNextPacket(); - }; - } - - _queueNextPacket() { - if (!this._running) { return; } - - let frame = this._frames[this._frame_index]; - - // skip send frames - while (this._frame_index < this._frame_length && frame.fromClient) { - this._frame_index++; - frame = this._frames[this._frame_index]; - } - - if (this._frame_index >= this._frame_length) { - Log.Debug('Finished, no more frames'); - this._finish(); - return; - } - - if (this._realtime) { - const toffset = (new Date()).getTime() - this._start_time; - let delay = frame.timestamp - toffset; - if (delay < 1) delay = 1; - - setTimeout(this._doPacket.bind(this), delay); - } else { - setImmediate(this._doPacket.bind(this)); - } - } - - _doPacket() { - // Avoid having excessive queue buildup in non-realtime mode - if (this._trafficManagement && this._rfb._flushing) { - const orig = this._rfb._display.onflush; - this._rfb._display.onflush = () => { - this._rfb._display.onflush = orig; - this._rfb._onFlush(); - this._doPacket(); - }; - return; - } - - const frame = this._frames[this._frame_index]; - - this._rfb._sock._recv_message({'data': frame.data}); - this._frame_index++; - - this._queueNextPacket(); - } - - _finish() { - if (this._rfb._display.pending()) { - this._rfb._display.onflush = () => { - if (this._rfb._flushing) { - this._rfb._onFlush(); - } - this._finish(); - }; - this._rfb._display.flush(); - } else { - this._running = false; - this._rfb._sock._eventHandlers.close({code: 1000, reason: ""}); - delete this._rfb; - this.onfinish((new Date()).getTime() - this._start_time); - } - } - - _handleDisconnect(evt) { - this._running = false; - this._disconnected(evt.detail.clean, this._frame_index); - } - - _handleCredentials(evt) { - this._rfb.sendCredentials({"username": "Foo", - "password": "Bar", - "target": "Baz"}); - } -} diff --git a/kasmweb/tests/test.base64.js b/kasmweb/tests/test.base64.js deleted file mode 100644 index 04bd207..0000000 --- a/kasmweb/tests/test.base64.js +++ /dev/null @@ -1,33 +0,0 @@ -const expect = chai.expect; - -import Base64 from '../core/base64.js'; - -describe('Base64 Tools', function () { - "use strict"; - - const BIN_ARR = new Array(256); - for (let i = 0; i < 256; i++) { - BIN_ARR[i] = i; - } - - const B64_STR = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="; - - - describe('encode', function () { - it('should encode a binary string into Base64', function () { - const encoded = Base64.encode(BIN_ARR); - expect(encoded).to.equal(B64_STR); - }); - }); - - describe('decode', function () { - it('should decode a Base64 string into a normal string', function () { - const decoded = Base64.decode(B64_STR); - expect(decoded).to.deep.equal(BIN_ARR); - }); - - it('should throw an error if we have extra characters at the end of the string', function () { - expect(() => Base64.decode(B64_STR+'abcdef')).to.throw(Error); - }); - }); -}); diff --git a/kasmweb/tests/test.display.js b/kasmweb/tests/test.display.js deleted file mode 100644 index b359550..0000000 --- a/kasmweb/tests/test.display.js +++ /dev/null @@ -1,486 +0,0 @@ -const expect = chai.expect; - -import Base64 from '../core/base64.js'; -import Display from '../core/display.js'; - -describe('Display/Canvas Helper', function () { - const checked_data = new Uint8Array([ - 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, - 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, - 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 - ]); - - const basic_data = new Uint8Array([0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]); - - function make_image_canvas(input_data) { - const canvas = document.createElement('canvas'); - canvas.width = 4; - canvas.height = 4; - const ctx = canvas.getContext('2d'); - const data = ctx.createImageData(4, 4); - for (let i = 0; i < checked_data.length; i++) { data.data[i] = input_data[i]; } - ctx.putImageData(data, 0, 0); - return canvas; - } - - function make_image_png(input_data) { - const canvas = make_image_canvas(input_data); - const url = canvas.toDataURL(); - const data = url.split(",")[1]; - return Base64.decode(data); - } - - describe('viewport handling', function () { - let display; - beforeEach(function () { - display = new Display(document.createElement('canvas')); - display.clipViewport = true; - display.resize(5, 5); - display.viewportChangeSize(3, 3); - display.viewportChangePos(1, 1); - }); - - it('should take viewport location into consideration when drawing images', function () { - display.resize(4, 4); - display.viewportChangeSize(2, 2); - display.drawImage(make_image_canvas(basic_data), 1, 1); - display.flip(); - - const expected = new Uint8Array(16); - for (let i = 0; i < 8; i++) { expected[i] = basic_data[i]; } - for (let i = 8; i < 16; i++) { expected[i] = 0; } - expect(display).to.have.displayed(expected); - }); - - it('should resize the target canvas when resizing the viewport', function () { - display.viewportChangeSize(2, 2); - expect(display._target.width).to.equal(2); - expect(display._target.height).to.equal(2); - }); - - it('should move the viewport if necessary', function () { - display.viewportChangeSize(5, 5); - expect(display.absX(0)).to.equal(0); - expect(display.absY(0)).to.equal(0); - expect(display._target.width).to.equal(5); - expect(display._target.height).to.equal(5); - }); - - it('should limit the viewport to the framebuffer size', function () { - display.viewportChangeSize(6, 6); - expect(display._target.width).to.equal(5); - expect(display._target.height).to.equal(5); - }); - - it('should redraw when moving the viewport', function () { - display.flip = sinon.spy(); - display.viewportChangePos(-1, 1); - expect(display.flip).to.have.been.calledOnce; - }); - - it('should redraw when resizing the viewport', function () { - display.flip = sinon.spy(); - display.viewportChangeSize(2, 2); - expect(display.flip).to.have.been.calledOnce; - }); - - it('should show the entire framebuffer when disabling the viewport', function () { - display.clipViewport = false; - expect(display.absX(0)).to.equal(0); - expect(display.absY(0)).to.equal(0); - expect(display._target.width).to.equal(5); - expect(display._target.height).to.equal(5); - }); - - it('should ignore viewport changes when the viewport is disabled', function () { - display.clipViewport = false; - display.viewportChangeSize(2, 2); - display.viewportChangePos(1, 1); - expect(display.absX(0)).to.equal(0); - expect(display.absY(0)).to.equal(0); - expect(display._target.width).to.equal(5); - expect(display._target.height).to.equal(5); - }); - - it('should show the entire framebuffer just after enabling the viewport', function () { - display.clipViewport = false; - display.clipViewport = true; - expect(display.absX(0)).to.equal(0); - expect(display.absY(0)).to.equal(0); - expect(display._target.width).to.equal(5); - expect(display._target.height).to.equal(5); - }); - }); - - describe('resizing', function () { - let display; - beforeEach(function () { - display = new Display(document.createElement('canvas')); - display.clipViewport = false; - display.resize(4, 4); - }); - - it('should change the size of the logical canvas', function () { - display.resize(5, 7); - expect(display._fb_width).to.equal(5); - expect(display._fb_height).to.equal(7); - }); - - it('should keep the framebuffer data', function () { - display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); - display.resize(2, 2); - display.flip(); - const expected = []; - for (let i = 0; i < 4 * 2*2; i += 4) { - expected[i] = 0xff; - expected[i+1] = expected[i+2] = 0; - expected[i+3] = 0xff; - } - expect(display).to.have.displayed(new Uint8Array(expected)); - }); - - describe('viewport', function () { - beforeEach(function () { - display.clipViewport = true; - display.viewportChangeSize(3, 3); - display.viewportChangePos(1, 1); - }); - - it('should keep the viewport position and size if possible', function () { - display.resize(6, 6); - expect(display.absX(0)).to.equal(1); - expect(display.absY(0)).to.equal(1); - expect(display._target.width).to.equal(3); - expect(display._target.height).to.equal(3); - }); - - it('should move the viewport if necessary', function () { - display.resize(3, 3); - expect(display.absX(0)).to.equal(0); - expect(display.absY(0)).to.equal(0); - expect(display._target.width).to.equal(3); - expect(display._target.height).to.equal(3); - }); - - it('should shrink the viewport if necessary', function () { - display.resize(2, 2); - expect(display.absX(0)).to.equal(0); - expect(display.absY(0)).to.equal(0); - expect(display._target.width).to.equal(2); - expect(display._target.height).to.equal(2); - }); - }); - }); - - describe('rescaling', function () { - let display; - let canvas; - - beforeEach(function () { - canvas = document.createElement('canvas'); - display = new Display(canvas); - display.clipViewport = true; - display.resize(4, 4); - display.viewportChangeSize(3, 3); - display.viewportChangePos(1, 1); - document.body.appendChild(canvas); - }); - - afterEach(function () { - document.body.removeChild(canvas); - }); - - it('should not change the bitmap size of the canvas', function () { - display.scale = 2.0; - expect(canvas.width).to.equal(3); - expect(canvas.height).to.equal(3); - }); - - it('should change the effective rendered size of the canvas', function () { - display.scale = 2.0; - expect(canvas.clientWidth).to.equal(6); - expect(canvas.clientHeight).to.equal(6); - }); - - it('should not change when resizing', function () { - display.scale = 2.0; - display.resize(5, 5); - expect(display.scale).to.equal(2.0); - expect(canvas.width).to.equal(3); - expect(canvas.height).to.equal(3); - expect(canvas.clientWidth).to.equal(6); - expect(canvas.clientHeight).to.equal(6); - }); - }); - - describe('autoscaling', function () { - let display; - let canvas; - - beforeEach(function () { - canvas = document.createElement('canvas'); - display = new Display(canvas); - display.clipViewport = true; - display.resize(4, 3); - document.body.appendChild(canvas); - }); - - afterEach(function () { - document.body.removeChild(canvas); - }); - - it('should preserve aspect ratio while autoscaling', function () { - display.autoscale(16, 9); - expect(canvas.clientWidth / canvas.clientHeight).to.equal(4 / 3); - }); - - it('should use width to determine scale when the current aspect ratio is wider than the target', function () { - display.autoscale(9, 16); - expect(display.absX(9)).to.equal(4); - expect(display.absY(18)).to.equal(8); - expect(canvas.clientWidth).to.equal(9); - expect(canvas.clientHeight).to.equal(7); // round 9 / (4 / 3) - }); - - it('should use height to determine scale when the current aspect ratio is taller than the target', function () { - display.autoscale(16, 9); - expect(display.absX(9)).to.equal(3); - expect(display.absY(18)).to.equal(6); - expect(canvas.clientWidth).to.equal(12); // 16 * (4 / 3) - expect(canvas.clientHeight).to.equal(9); - - }); - - it('should not change the bitmap size of the canvas', function () { - display.autoscale(16, 9); - expect(canvas.width).to.equal(4); - expect(canvas.height).to.equal(3); - }); - }); - - describe('drawing', function () { - - // TODO(directxman12): improve the tests for each of the drawing functions to cover more than just the - // basic cases - let display; - beforeEach(function () { - display = new Display(document.createElement('canvas')); - display.resize(4, 4); - }); - - it('should clear the screen on #clear without a logo set', function () { - display.fillRect(0, 0, 4, 4, [0x00, 0x00, 0xff]); - display._logo = null; - display.clear(); - display.resize(4, 4); - const empty = []; - for (let i = 0; i < 4 * display._fb_width * display._fb_height; i++) { empty[i] = 0; } - expect(display).to.have.displayed(new Uint8Array(empty)); - }); - - it('should draw the logo on #clear with a logo set', function (done) { - display._logo = { width: 4, height: 4, type: "image/png", data: make_image_png(checked_data) }; - display.clear(); - display.onflush = () => { - expect(display).to.have.displayed(checked_data); - expect(display._fb_width).to.equal(4); - expect(display._fb_height).to.equal(4); - done(); - }; - display.flush(); - }); - - it('should not draw directly on the target canvas', function () { - display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); - display.flip(); - display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - const expected = []; - for (let i = 0; i < 4 * display._fb_width * display._fb_height; i += 4) { - expected[i] = 0xff; - expected[i+1] = expected[i+2] = 0; - expected[i+3] = 0xff; - } - expect(display).to.have.displayed(new Uint8Array(expected)); - }); - - it('should support filling a rectangle with particular color via #fillRect', function () { - display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - display.fillRect(0, 0, 2, 2, [0xff, 0, 0]); - display.fillRect(2, 2, 2, 2, [0xff, 0, 0]); - display.flip(); - expect(display).to.have.displayed(checked_data); - }); - - it('should support copying an portion of the canvas via #copyImage', function () { - display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - display.fillRect(0, 0, 2, 2, [0xff, 0, 0x00]); - display.copyImage(0, 0, 2, 2, 2, 2); - display.flip(); - expect(display).to.have.displayed(checked_data); - }); - - it('should support drawing images via #imageRect', function (done) { - display.imageRect(0, 0, "image/png", make_image_png(checked_data)); - display.flip(); - display.onflush = () => { - expect(display).to.have.displayed(checked_data); - done(); - }; - display.flush(); - }); - - it('should support drawing tile data with a background color and sub tiles', function () { - display.startTile(0, 0, 4, 4, [0, 0xff, 0]); - display.subTile(0, 0, 2, 2, [0xff, 0, 0]); - display.subTile(2, 2, 2, 2, [0xff, 0, 0]); - display.finishTile(); - display.flip(); - expect(display).to.have.displayed(checked_data); - }); - - // We have a special cache for 16x16 tiles that we need to test - it('should support drawing a 16x16 tile', function () { - const large_checked_data = new Uint8Array(16*16*4); - display.resize(16, 16); - - for (let y = 0;y < 16;y++) { - for (let x = 0;x < 16;x++) { - let pixel; - if ((x < 4) && (y < 4)) { - // NB: of course IE11 doesn't support #slice on ArrayBufferViews... - pixel = Array.prototype.slice.call(checked_data, (y*4+x)*4, (y*4+x+1)*4); - } else { - pixel = [0, 0xff, 0, 255]; - } - large_checked_data.set(pixel, (y*16+x)*4); - } - } - - display.startTile(0, 0, 16, 16, [0, 0xff, 0]); - display.subTile(0, 0, 2, 2, [0xff, 0, 0]); - display.subTile(2, 2, 2, 2, [0xff, 0, 0]); - display.finishTile(); - display.flip(); - expect(display).to.have.displayed(large_checked_data); - }); - - it('should support drawing BGRX blit images with true color via #blitImage', function () { - const data = []; - for (let i = 0; i < 16; i++) { - data[i * 4] = checked_data[i * 4 + 2]; - data[i * 4 + 1] = checked_data[i * 4 + 1]; - data[i * 4 + 2] = checked_data[i * 4]; - data[i * 4 + 3] = checked_data[i * 4 + 3]; - } - display.blitImage(0, 0, 4, 4, data, 0); - display.flip(); - expect(display).to.have.displayed(checked_data); - }); - - it('should support drawing RGB blit images with true color via #blitRgbImage', function () { - const data = []; - for (let i = 0; i < 16; i++) { - data[i * 3] = checked_data[i * 4]; - data[i * 3 + 1] = checked_data[i * 4 + 1]; - data[i * 3 + 2] = checked_data[i * 4 + 2]; - } - display.blitRgbImage(0, 0, 4, 4, data, 0); - display.flip(); - expect(display).to.have.displayed(checked_data); - }); - - it('should support drawing an image object via #drawImage', function () { - const img = make_image_canvas(checked_data); - display.drawImage(img, 0, 0); - display.flip(); - expect(display).to.have.displayed(checked_data); - }); - }); - - describe('the render queue processor', function () { - let display; - beforeEach(function () { - display = new Display(document.createElement('canvas')); - display.resize(4, 4); - sinon.spy(display, '_scan_renderQ'); - }); - - afterEach(function () { - window.requestAnimationFrame = this.old_requestAnimationFrame; - }); - - it('should try to process an item when it is pushed on, if nothing else is on the queue', function () { - display._renderQ_push({ type: 'noop' }); // does nothing - expect(display._scan_renderQ).to.have.been.calledOnce; - }); - - it('should not try to process an item when it is pushed on if we are waiting for other items', function () { - display._renderQ.length = 2; - display._renderQ_push({ type: 'noop' }); - expect(display._scan_renderQ).to.not.have.been.called; - }); - - it('should wait until an image is loaded to attempt to draw it and the rest of the queue', function () { - const img = { complete: false, addEventListener: sinon.spy() }; - display._renderQ = [{ type: 'img', x: 3, y: 4, img: img }, - { type: 'fill', x: 1, y: 2, width: 3, height: 4, color: 5 }]; - display.drawImage = sinon.spy(); - display.fillRect = sinon.spy(); - - display._scan_renderQ(); - expect(display.drawImage).to.not.have.been.called; - expect(display.fillRect).to.not.have.been.called; - expect(img.addEventListener).to.have.been.calledOnce; - - display._renderQ[0].img.complete = true; - display._scan_renderQ(); - expect(display.drawImage).to.have.been.calledOnce; - expect(display.fillRect).to.have.been.calledOnce; - expect(img.addEventListener).to.have.been.calledOnce; - }); - - it('should call callback when queue is flushed', function () { - display.onflush = sinon.spy(); - display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - expect(display.onflush).to.not.have.been.called; - display.flush(); - expect(display.onflush).to.have.been.calledOnce; - }); - - it('should draw a blit image on type "blit"', function () { - display.blitImage = sinon.spy(); - display._renderQ_push({ type: 'blit', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); - expect(display.blitImage).to.have.been.calledOnce; - expect(display.blitImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0); - }); - - it('should draw a blit RGB image on type "blitRgb"', function () { - display.blitRgbImage = sinon.spy(); - display._renderQ_push({ type: 'blitRgb', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); - expect(display.blitRgbImage).to.have.been.calledOnce; - expect(display.blitRgbImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0); - }); - - it('should copy a region on type "copy"', function () { - display.copyImage = sinon.spy(); - display._renderQ_push({ type: 'copy', x: 3, y: 4, width: 5, height: 6, old_x: 7, old_y: 8 }); - expect(display.copyImage).to.have.been.calledOnce; - expect(display.copyImage).to.have.been.calledWith(7, 8, 3, 4, 5, 6); - }); - - it('should fill a rect with a given color on type "fill"', function () { - display.fillRect = sinon.spy(); - display._renderQ_push({ type: 'fill', x: 3, y: 4, width: 5, height: 6, color: [7, 8, 9]}); - expect(display.fillRect).to.have.been.calledOnce; - expect(display.fillRect).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9]); - }); - - it('should draw an image from an image object on type "img" (if complete)', function () { - display.drawImage = sinon.spy(); - display._renderQ_push({ type: 'img', x: 3, y: 4, img: { complete: true } }); - expect(display.drawImage).to.have.been.calledOnce; - expect(display.drawImage).to.have.been.calledWith({ complete: true }, 3, 4); - }); - }); -}); diff --git a/kasmweb/tests/test.helper.js b/kasmweb/tests/test.helper.js deleted file mode 100644 index d44bab0..0000000 --- a/kasmweb/tests/test.helper.js +++ /dev/null @@ -1,223 +0,0 @@ -const expect = chai.expect; - -import keysyms from '../core/input/keysymdef.js'; -import * as KeyboardUtil from "../core/input/util.js"; -import * as browser from '../core/util/browser.js'; - -describe('Helpers', function () { - "use strict"; - - describe('keysyms.lookup', function () { - it('should map ASCII characters to keysyms', function () { - expect(keysyms.lookup('a'.charCodeAt())).to.be.equal(0x61); - expect(keysyms.lookup('A'.charCodeAt())).to.be.equal(0x41); - }); - it('should map Latin-1 characters to keysyms', function () { - expect(keysyms.lookup('ø'.charCodeAt())).to.be.equal(0xf8); - - expect(keysyms.lookup('é'.charCodeAt())).to.be.equal(0xe9); - }); - it('should map characters that are in Windows-1252 but not in Latin-1 to keysyms', function () { - expect(keysyms.lookup('Š'.charCodeAt())).to.be.equal(0x01a9); - }); - it('should map characters which aren\'t in Latin1 *or* Windows-1252 to keysyms', function () { - expect(keysyms.lookup('ũ'.charCodeAt())).to.be.equal(0x03fd); - }); - it('should map unknown codepoints to the Unicode range', function () { - expect(keysyms.lookup('\n'.charCodeAt())).to.be.equal(0x100000a); - expect(keysyms.lookup('\u262D'.charCodeAt())).to.be.equal(0x100262d); - }); - // This requires very recent versions of most browsers... skipping for now - it.skip('should map UCS-4 codepoints to the Unicode range', function () { - //expect(keysyms.lookup('\u{1F686}'.codePointAt())).to.be.equal(0x101f686); - }); - }); - - describe('getKeycode', function () { - it('should pass through proper code', function () { - expect(KeyboardUtil.getKeycode({code: 'Semicolon'})).to.be.equal('Semicolon'); - }); - it('should map legacy values', function () { - expect(KeyboardUtil.getKeycode({code: ''})).to.be.equal('Unidentified'); - expect(KeyboardUtil.getKeycode({code: 'OSLeft'})).to.be.equal('MetaLeft'); - }); - it('should map keyCode to code when possible', function () { - expect(KeyboardUtil.getKeycode({keyCode: 0x14})).to.be.equal('CapsLock'); - expect(KeyboardUtil.getKeycode({keyCode: 0x5b})).to.be.equal('MetaLeft'); - expect(KeyboardUtil.getKeycode({keyCode: 0x35})).to.be.equal('Digit5'); - expect(KeyboardUtil.getKeycode({keyCode: 0x65})).to.be.equal('Numpad5'); - }); - it('should map keyCode left/right side', function () { - expect(KeyboardUtil.getKeycode({keyCode: 0x10, location: 1})).to.be.equal('ShiftLeft'); - expect(KeyboardUtil.getKeycode({keyCode: 0x10, location: 2})).to.be.equal('ShiftRight'); - expect(KeyboardUtil.getKeycode({keyCode: 0x11, location: 1})).to.be.equal('ControlLeft'); - expect(KeyboardUtil.getKeycode({keyCode: 0x11, location: 2})).to.be.equal('ControlRight'); - }); - it('should map keyCode on numpad', function () { - expect(KeyboardUtil.getKeycode({keyCode: 0x0d, location: 0})).to.be.equal('Enter'); - expect(KeyboardUtil.getKeycode({keyCode: 0x0d, location: 3})).to.be.equal('NumpadEnter'); - expect(KeyboardUtil.getKeycode({keyCode: 0x23, location: 0})).to.be.equal('End'); - expect(KeyboardUtil.getKeycode({keyCode: 0x23, location: 3})).to.be.equal('Numpad1'); - }); - it('should return Unidentified when it cannot map the keyCode', function () { - expect(KeyboardUtil.getKeycode({keycode: 0x42})).to.be.equal('Unidentified'); - }); - - describe('Fix Meta on macOS', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.platform = "Mac x86_64"; - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should respect ContextMenu on modern browser', function () { - expect(KeyboardUtil.getKeycode({code: 'ContextMenu', keyCode: 0x5d})).to.be.equal('ContextMenu'); - }); - it('should translate legacy ContextMenu to MetaRight', function () { - expect(KeyboardUtil.getKeycode({keyCode: 0x5d})).to.be.equal('MetaRight'); - }); - }); - }); - - describe('getKey', function () { - it('should prefer key', function () { - if (browser.isIE() || browser.isEdge()) this.skip(); - expect(KeyboardUtil.getKey({key: 'a', charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.be.equal('a'); - }); - it('should map legacy values', function () { - expect(KeyboardUtil.getKey({key: 'Spacebar'})).to.be.equal(' '); - expect(KeyboardUtil.getKey({key: 'Left'})).to.be.equal('ArrowLeft'); - expect(KeyboardUtil.getKey({key: 'OS'})).to.be.equal('Meta'); - expect(KeyboardUtil.getKey({key: 'Win'})).to.be.equal('Meta'); - expect(KeyboardUtil.getKey({key: 'UIKeyInputLeftArrow'})).to.be.equal('ArrowLeft'); - }); - it('should use code if no key', function () { - expect(KeyboardUtil.getKey({code: 'NumpadBackspace'})).to.be.equal('Backspace'); - }); - it('should not use code fallback for character keys', function () { - expect(KeyboardUtil.getKey({code: 'KeyA'})).to.be.equal('Unidentified'); - expect(KeyboardUtil.getKey({code: 'Digit1'})).to.be.equal('Unidentified'); - expect(KeyboardUtil.getKey({code: 'Period'})).to.be.equal('Unidentified'); - expect(KeyboardUtil.getKey({code: 'Numpad1'})).to.be.equal('Unidentified'); - }); - it('should use charCode if no key', function () { - expect(KeyboardUtil.getKey({charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.be.equal('Š'); - }); - it('should return Unidentified when it cannot map the key', function () { - expect(KeyboardUtil.getKey({keycode: 0x42})).to.be.equal('Unidentified'); - }); - - describe('Broken key AltGraph on IE/Edge', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should ignore printable character key on IE', function () { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; - expect(KeyboardUtil.getKey({key: 'a'})).to.be.equal('Unidentified'); - }); - it('should ignore printable character key on Edge', function () { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; - expect(KeyboardUtil.getKey({key: 'a'})).to.be.equal('Unidentified'); - }); - it('should allow non-printable character key on IE', function () { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; - expect(KeyboardUtil.getKey({key: 'Shift'})).to.be.equal('Shift'); - }); - it('should allow non-printable character key on Edge', function () { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; - expect(KeyboardUtil.getKey({key: 'Shift'})).to.be.equal('Shift'); - }); - }); - }); - - describe('getKeysym', function () { - describe('Non-character keys', function () { - it('should recognize the right keys', function () { - expect(KeyboardUtil.getKeysym({key: 'Enter'})).to.be.equal(0xFF0D); - expect(KeyboardUtil.getKeysym({key: 'Backspace'})).to.be.equal(0xFF08); - expect(KeyboardUtil.getKeysym({key: 'Tab'})).to.be.equal(0xFF09); - expect(KeyboardUtil.getKeysym({key: 'Shift'})).to.be.equal(0xFFE1); - expect(KeyboardUtil.getKeysym({key: 'Control'})).to.be.equal(0xFFE3); - expect(KeyboardUtil.getKeysym({key: 'Alt'})).to.be.equal(0xFFE9); - expect(KeyboardUtil.getKeysym({key: 'Meta'})).to.be.equal(0xFFEB); - expect(KeyboardUtil.getKeysym({key: 'Escape'})).to.be.equal(0xFF1B); - expect(KeyboardUtil.getKeysym({key: 'ArrowUp'})).to.be.equal(0xFF52); - }); - it('should map left/right side', function () { - expect(KeyboardUtil.getKeysym({key: 'Shift', location: 1})).to.be.equal(0xFFE1); - expect(KeyboardUtil.getKeysym({key: 'Shift', location: 2})).to.be.equal(0xFFE2); - expect(KeyboardUtil.getKeysym({key: 'Control', location: 1})).to.be.equal(0xFFE3); - expect(KeyboardUtil.getKeysym({key: 'Control', location: 2})).to.be.equal(0xFFE4); - }); - it('should handle AltGraph', function () { - expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'Alt', location: 2})).to.be.equal(0xFFEA); - expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'AltGraph', location: 2})).to.be.equal(0xFE03); - }); - it('should return null for unknown keys', function () { - expect(KeyboardUtil.getKeysym({key: 'Semicolon'})).to.be.null; - expect(KeyboardUtil.getKeysym({key: 'BracketRight'})).to.be.null; - }); - it('should handle remappings', function () { - expect(KeyboardUtil.getKeysym({code: 'ControlLeft', key: 'Tab'})).to.be.equal(0xFF09); - }); - }); - - describe('Numpad', function () { - it('should handle Numpad numbers', function () { - if (browser.isIE() || browser.isEdge()) this.skip(); - expect(KeyboardUtil.getKeysym({code: 'Digit5', key: '5', location: 0})).to.be.equal(0x0035); - expect(KeyboardUtil.getKeysym({code: 'Numpad5', key: '5', location: 3})).to.be.equal(0xFFB5); - }); - it('should handle Numpad non-character keys', function () { - expect(KeyboardUtil.getKeysym({code: 'Home', key: 'Home', location: 0})).to.be.equal(0xFF50); - expect(KeyboardUtil.getKeysym({code: 'Numpad5', key: 'Home', location: 3})).to.be.equal(0xFF95); - expect(KeyboardUtil.getKeysym({code: 'Delete', key: 'Delete', location: 0})).to.be.equal(0xFFFF); - expect(KeyboardUtil.getKeysym({code: 'NumpadDecimal', key: 'Delete', location: 3})).to.be.equal(0xFF9F); - }); - it('should handle Numpad Decimal key', function () { - if (browser.isIE() || browser.isEdge()) this.skip(); - expect(KeyboardUtil.getKeysym({code: 'NumpadDecimal', key: '.', location: 3})).to.be.equal(0xFFAE); - expect(KeyboardUtil.getKeysym({code: 'NumpadDecimal', key: ',', location: 3})).to.be.equal(0xFFAC); - }); - }); - }); -}); diff --git a/kasmweb/tests/test.keyboard.js b/kasmweb/tests/test.keyboard.js deleted file mode 100644 index 77fe3f6..0000000 --- a/kasmweb/tests/test.keyboard.js +++ /dev/null @@ -1,510 +0,0 @@ -const expect = chai.expect; - -import Keyboard from '../core/input/keyboard.js'; -import * as browser from '../core/util/browser.js'; - -describe('Key Event Handling', function () { - "use strict"; - - // The real KeyboardEvent constructor might not work everywhere we - // want to run these tests - function keyevent(typeArg, KeyboardEventInit) { - const e = { type: typeArg }; - for (let key in KeyboardEventInit) { - e[key] = KeyboardEventInit[key]; - } - e.stopPropagation = sinon.spy(); - e.preventDefault = sinon.spy(); - return e; - } - - describe('Decode Keyboard Events', function () { - it('should decode keydown events', function (done) { - if (browser.isIE() || browser.isEdge()) this.skip(); - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - }); - it('should decode keyup events', function (done) { - if (browser.isIE() || browser.isEdge()) this.skip(); - let calls = 0; - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - if (calls++ === 1) { - expect(down).to.be.equal(false); - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); - }); - - describe('Legacy keypress Events', function () { - it('should wait for keypress when needed', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - it('should decode keypress events', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - kbd._handleKeyPress(keyevent('keypress', {code: 'KeyA', charCode: 0x61})); - }); - it('should ignore keypress with different code', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - kbd._handleKeyPress(keyevent('keypress', {code: 'KeyB', charCode: 0x61})); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - it('should handle keypress with missing code', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - kbd._handleKeyPress(keyevent('keypress', {charCode: 0x61})); - }); - it('should guess key if no keypress and numeric key', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x32); - expect(code).to.be.equal('Digit2'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'Digit2', keyCode: 0x32})); - }); - it('should guess key if no keypress and alpha key', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41, shiftKey: false})); - }); - it('should guess key if no keypress and alpha key (with shift)', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x41); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41, shiftKey: true})); - }); - it('should not guess key if no keypress and unknown key', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x09})); - }); - }); - - describe('suppress the right events at the right time', function () { - beforeEach(function () { - if (browser.isIE() || browser.isEdge()) this.skip(); - }); - it('should suppress anything with a valid key', function () { - const kbd = new Keyboard(document, {}); - const evt1 = keyevent('keydown', {code: 'KeyA', key: 'a'}); - kbd._handleKeyDown(evt1); - expect(evt1.preventDefault).to.have.been.called; - const evt2 = keyevent('keyup', {code: 'KeyA', key: 'a'}); - kbd._handleKeyUp(evt2); - expect(evt2.preventDefault).to.have.been.called; - }); - it('should not suppress keys without key', function () { - const kbd = new Keyboard(document, {}); - const evt = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); - kbd._handleKeyDown(evt); - expect(evt.preventDefault).to.not.have.been.called; - }); - it('should suppress the following keypress event', function () { - const kbd = new Keyboard(document, {}); - const evt1 = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); - kbd._handleKeyDown(evt1); - const evt2 = keyevent('keypress', {code: 'KeyA', charCode: 0x41}); - kbd._handleKeyPress(evt2); - expect(evt2.preventDefault).to.have.been.called; - }); - }); - }); - - describe('Fake keyup', function () { - it('should fake keyup events for virtual keyboards', function (done) { - if (browser.isIE() || browser.isEdge()) this.skip(); - let count = 0; - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - switch (count++) { - case 0: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('Unidentified'); - expect(down).to.be.equal(true); - break; - case 1: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('Unidentified'); - expect(down).to.be.equal(false); - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'Unidentified', key: 'a'})); - }); - - describe('iOS', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.platform = "iPhone 9.0"; - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should fake keyup events on iOS', function (done) { - if (browser.isIE() || browser.isEdge()) this.skip(); - let count = 0; - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - switch (count++) { - case 0: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - break; - case 1: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(false); - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - }); - }); - }); - - describe('Track Key State', function () { - beforeEach(function () { - if (browser.isIE() || browser.isEdge()) this.skip(); - }); - it('should send release using the same keysym as the press', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - if (!down) { - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'b'})); - }); - it('should send the same keysym for multiple presses', function () { - let count = 0; - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - count++; - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'b'})); - expect(count).to.be.equal(2); - }); - it('should do nothing on keyup events if no keys are down', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - - describe('Legacy Events', function () { - it('should track keys using keyCode if no code', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('Platform65'); - if (!down) { - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {keyCode: 65, key: 'a'})); - kbd._handleKeyUp(keyevent('keyup', {keyCode: 65, key: 'b'})); - }); - it('should ignore compositing code', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('Unidentified'); - }; - kbd._handleKeyDown(keyevent('keydown', {keyCode: 229, key: 'a'})); - }); - it('should track keys using keyIdentifier if no code', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('Platform65'); - if (!down) { - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {keyIdentifier: 'U+0041', key: 'a'})); - kbd._handleKeyUp(keyevent('keyup', {keyIdentifier: 'U+0041', key: 'b'})); - }); - }); - }); - - describe('Shuffle modifiers on macOS', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.platform = "Mac x86_64"; - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should change Alt to AltGraph', function () { - let count = 0; - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - switch (count++) { - case 0: - expect(keysym).to.be.equal(0xFF7E); - expect(code).to.be.equal('AltLeft'); - break; - case 1: - expect(keysym).to.be.equal(0xFE03); - expect(code).to.be.equal('AltRight'); - break; - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'AltLeft', key: 'Alt', location: 1})); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); - expect(count).to.be.equal(2); - }); - it('should change left Super to Alt', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0xFFE9); - expect(code).to.be.equal('MetaLeft'); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'MetaLeft', key: 'Meta', location: 1})); - }); - it('should change right Super to left Super', function (done) { - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - expect(keysym).to.be.equal(0xFFEB); - expect(code).to.be.equal('MetaRight'); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'MetaRight', key: 'Meta', location: 2})); - }); - }); - - describe('Escape AltGraph on Windows', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.platform = "Windows x86_64"; - - this.clock = sinon.useFakeTimers(); - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - this.clock.restore(); - }); - - it('should supress ControlLeft until it knows if it is AltGr', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - - it('should not trigger on repeating ControlLeft', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - expect(kbd.onkeyevent).to.have.been.calledTwice; - expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); - expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); - }); - - it('should not supress ControlRight', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlRight', key: 'Control', location: 2})); - expect(kbd.onkeyevent).to.have.been.calledOnce; - expect(kbd.onkeyevent).to.have.been.calledWith(0xffe4, "ControlRight", true); - }); - - it('should release ControlLeft after 100 ms', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - expect(kbd.onkeyevent).to.not.have.been.called; - this.clock.tick(100); - expect(kbd.onkeyevent).to.have.been.calledOnce; - expect(kbd.onkeyevent).to.have.been.calledWith(0xffe3, "ControlLeft", true); - }); - - it('should release ControlLeft on other key press', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - expect(kbd.onkeyevent).to.not.have.been.called; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - expect(kbd.onkeyevent).to.have.been.calledTwice; - expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); - expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0x61, "KeyA", true); - - // Check that the timer is properly dead - kbd.onkeyevent.reset(); - this.clock.tick(100); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - - it('should release ControlLeft on other key release', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - expect(kbd.onkeyevent).to.have.been.calledOnce; - expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0x61, "KeyA", true); - kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); - expect(kbd.onkeyevent).to.have.been.calledThrice; - expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); - expect(kbd.onkeyevent.thirdCall).to.have.been.calledWith(0x61, "KeyA", false); - - // Check that the timer is properly dead - kbd.onkeyevent.reset(); - this.clock.tick(100); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - - it('should generate AltGraph for quick Ctrl+Alt sequence', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1, timeStamp: Date.now()})); - this.clock.tick(20); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2, timeStamp: Date.now()})); - expect(kbd.onkeyevent).to.have.been.calledOnce; - expect(kbd.onkeyevent).to.have.been.calledWith(0xfe03, 'AltRight', true); - - // Check that the timer is properly dead - kbd.onkeyevent.reset(); - this.clock.tick(100); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - - it('should generate Ctrl, Alt for slow Ctrl+Alt sequence', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1, timeStamp: Date.now()})); - this.clock.tick(60); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2, timeStamp: Date.now()})); - expect(kbd.onkeyevent).to.have.been.calledTwice; - expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); - expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffea, "AltRight", true); - - // Check that the timer is properly dead - kbd.onkeyevent.reset(); - this.clock.tick(100); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - - it('should pass through single Alt', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); - expect(kbd.onkeyevent).to.have.been.calledOnce; - expect(kbd.onkeyevent).to.have.been.calledWith(0xffea, 'AltRight', true); - }); - - it('should pass through single AltGr', function () { - const kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'AltGraph', location: 2})); - expect(kbd.onkeyevent).to.have.been.calledOnce; - expect(kbd.onkeyevent).to.have.been.calledWith(0xfe03, 'AltRight', true); - }); - }); -}); diff --git a/kasmweb/tests/test.localization.js b/kasmweb/tests/test.localization.js deleted file mode 100644 index 9570c17..0000000 --- a/kasmweb/tests/test.localization.js +++ /dev/null @@ -1,72 +0,0 @@ -const expect = chai.expect; -import { l10n } from '../app/localization.js'; - -describe('Localization', function () { - "use strict"; - - describe('language selection', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.languages !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.languages = []; - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should use English by default', function () { - expect(l10n.language).to.equal('en'); - }); - it('should use English if no user language matches', function () { - window.navigator.languages = ["nl", "de"]; - l10n.setup(["es", "fr"]); - expect(l10n.language).to.equal('en'); - }); - it('should use the most preferred user language', function () { - window.navigator.languages = ["nl", "de", "fr"]; - l10n.setup(["es", "fr", "de"]); - expect(l10n.language).to.equal('de'); - }); - it('should prefer sub-languages languages', function () { - window.navigator.languages = ["pt-BR"]; - l10n.setup(["pt", "pt-BR"]); - expect(l10n.language).to.equal('pt-BR'); - }); - it('should fall back to language "parents"', function () { - window.navigator.languages = ["pt-BR"]; - l10n.setup(["fr", "pt", "de"]); - expect(l10n.language).to.equal('pt'); - }); - it('should not use specific language when user asks for a generic language', function () { - window.navigator.languages = ["pt", "de"]; - l10n.setup(["fr", "pt-BR", "de"]); - expect(l10n.language).to.equal('de'); - }); - it('should handle underscore as a separator', function () { - window.navigator.languages = ["pt-BR"]; - l10n.setup(["pt_BR"]); - expect(l10n.language).to.equal('pt_BR'); - }); - it('should handle difference in case', function () { - window.navigator.languages = ["pt-br"]; - l10n.setup(["pt-BR"]); - expect(l10n.language).to.equal('pt-BR'); - }); - }); -}); diff --git a/kasmweb/tests/test.mouse.js b/kasmweb/tests/test.mouse.js deleted file mode 100644 index 78c74f1..0000000 --- a/kasmweb/tests/test.mouse.js +++ /dev/null @@ -1,304 +0,0 @@ -const expect = chai.expect; - -import Mouse from '../core/input/mouse.js'; - -describe('Mouse Event Handling', function () { - "use strict"; - - let target; - - beforeEach(function () { - // For these tests we can assume that the canvas is 100x100 - // located at coordinates 10x10 - target = document.createElement('canvas'); - target.style.position = "absolute"; - target.style.top = "10px"; - target.style.left = "10px"; - target.style.width = "100px"; - target.style.height = "100px"; - document.body.appendChild(target); - }); - afterEach(function () { - document.body.removeChild(target); - target = null; - }); - - // The real constructors might not work everywhere we - // want to run these tests - const mouseevent = (typeArg, MouseEventInit) => { - const e = { type: typeArg }; - for (let key in MouseEventInit) { - e[key] = MouseEventInit[key]; - } - e.stopPropagation = sinon.spy(); - e.preventDefault = sinon.spy(); - return e; - }; - const touchevent = mouseevent; - - describe('Decode Mouse Events', function () { - it('should decode mousedown events', function (done) { - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - expect(bmask).to.be.equal(0x01); - expect(down).to.be.equal(1); - done(); - }; - mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); - }); - it('should decode mouseup events', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - expect(bmask).to.be.equal(0x01); - if (calls++ === 1) { - expect(down).to.not.be.equal(1); - done(); - } - }; - mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); - mouse._handleMouseUp(mouseevent('mouseup', { button: '0x01' })); - }); - it('should decode mousemove events', function (done) { - const mouse = new Mouse(target); - mouse.onmousemove = (x, y) => { - // Note that target relative coordinates are sent - expect(x).to.be.equal(40); - expect(y).to.be.equal(10); - done(); - }; - mouse._handleMouseMove(mouseevent('mousemove', - { clientX: 50, clientY: 20 })); - }); - it('should decode mousewheel events', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - expect(bmask).to.be.equal(1<<6); - if (calls === 1) { - expect(down).to.be.equal(1); - } else if (calls === 2) { - expect(down).to.not.be.equal(1); - done(); - } - }; - mouse._handleMouseWheel(mouseevent('mousewheel', - { deltaX: 50, deltaY: 0, - deltaMode: 0})); - }); - }); - - describe('Double-click for Touch', function () { - - beforeEach(function () { this.clock = sinon.useFakeTimers(); }); - afterEach(function () { this.clock.restore(); }); - - it('should use same pos for 2nd tap if close enough', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - done(); - } - }; - // touch events are sent in an array of events - // with one item for each touch point - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(200); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 67, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 66, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if far apart', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(200); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 57, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 56, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if not soon enough', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(500); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 67, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 66, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if not touch', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(mouseevent( - 'mousedown', { button: '0x01', clientX: 78, clientY: 46 })); - this.clock.tick(10); - mouse._handleMouseUp(mouseevent( - 'mouseup', { button: '0x01', clientX: 79, clientY: 45 })); - this.clock.tick(200); - mouse._handleMouseDown(mouseevent( - 'mousedown', { button: '0x01', clientX: 67, clientY: 35 })); - this.clock.tick(10); - mouse._handleMouseUp(mouseevent( - 'mouseup', { button: '0x01', clientX: 66, clientY: 36 })); - }); - - }); - - describe('Accumulate mouse wheel events with small delta', function () { - - beforeEach(function () { this.clock = sinon.useFakeTimers(); }); - afterEach(function () { this.clock.restore(); }); - - it('should accumulate wheel events if small enough', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - - // threshold is 10 - expect(mouse._accumulatedWheelDeltaX).to.be.equal(8); - - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - - expect(mouse.onmousebutton).to.have.callCount(2); // mouse down and up - - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 9, deltaMode: 0 })); - - expect(mouse._accumulatedWheelDeltaX).to.be.equal(4); - expect(mouse._accumulatedWheelDeltaY).to.be.equal(9); - - expect(mouse.onmousebutton).to.have.callCount(2); // still - }); - - it('should not accumulate large wheel events', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 11, deltaY: 0, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 0, deltaY: 70, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 400, deltaY: 400, deltaMode: 0 })); - - expect(mouse.onmousebutton).to.have.callCount(8); // mouse down and up - }); - - it('should send even small wheel events after a timeout', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 1, deltaY: 0, deltaMode: 0 })); - this.clock.tick(51); // timeout on 50 ms - - expect(mouse.onmousebutton).to.have.callCount(2); // mouse down and up - }); - - it('should account for non-zero deltaMode', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 0, deltaY: 2, deltaMode: 1 })); - - this.clock.tick(10); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 1, deltaY: 0, deltaMode: 2 })); - - expect(mouse.onmousebutton).to.have.callCount(4); // mouse down and up - }); - }); - -}); diff --git a/kasmweb/tests/test.rfb.js b/kasmweb/tests/test.rfb.js deleted file mode 100644 index ca8a738..0000000 --- a/kasmweb/tests/test.rfb.js +++ /dev/null @@ -1,2389 +0,0 @@ -const expect = chai.expect; - -import RFB from '../core/rfb.js'; -import Websock from '../core/websock.js'; -import { encodings } from '../core/encodings.js'; - -import FakeWebSocket from './fake.websocket.js'; - -/* UIEvent constructor polyfill for IE */ -(() => { - if (typeof window.UIEvent === "function") return; - - function UIEvent( event, params ) { - params = params || { bubbles: false, cancelable: false, view: window, detail: undefined }; - const evt = document.createEvent( 'UIEvent' ); - evt.initUIEvent( event, params.bubbles, params.cancelable, params.view, params.detail ); - return evt; - } - - UIEvent.prototype = window.UIEvent.prototype; - - window.UIEvent = UIEvent; -})(); - -function push8(arr, num) { - "use strict"; - arr.push(num & 0xFF); -} - -function push16(arr, num) { - "use strict"; - arr.push((num >> 8) & 0xFF, - num & 0xFF); -} - -function push32(arr, num) { - "use strict"; - arr.push((num >> 24) & 0xFF, - (num >> 16) & 0xFF, - (num >> 8) & 0xFF, - num & 0xFF); -} - -describe('Remote Frame Buffer Protocol Client', function () { - let clock; - let raf; - - before(FakeWebSocket.replace); - after(FakeWebSocket.restore); - - before(function () { - this.clock = clock = sinon.useFakeTimers(); - // sinon doesn't support this yet - raf = window.requestAnimationFrame; - window.requestAnimationFrame = setTimeout; - // Use a single set of buffers instead of reallocating to - // speed up tests - const sock = new Websock(); - const _sQ = new Uint8Array(sock._sQbufferSize); - const rQ = new Uint8Array(sock._rQbufferSize); - - Websock.prototype._old_allocate_buffers = Websock.prototype._allocate_buffers; - Websock.prototype._allocate_buffers = function () { - this._sQ = _sQ; - this._rQ = rQ; - }; - - }); - - after(function () { - Websock.prototype._allocate_buffers = Websock.prototype._old_allocate_buffers; - this.clock.restore(); - window.requestAnimationFrame = raf; - }); - - let container; - let rfbs; - - beforeEach(function () { - // Create a container element for all RFB objects to attach to - container = document.createElement('div'); - container.style.width = "100%"; - container.style.height = "100%"; - document.body.appendChild(container); - - // And track all created RFB objects - rfbs = []; - }); - afterEach(function () { - // Make sure every created RFB object is properly cleaned up - // or they might affect subsequent tests - rfbs.forEach(function (rfb) { - rfb.disconnect(); - expect(rfb._disconnect).to.have.been.called; - }); - rfbs = []; - - document.body.removeChild(container); - container = null; - }); - - function make_rfb(url, options) { - url = url || 'wss://host:8675'; - const rfb = new RFB(container, url, options); - clock.tick(); - rfb._sock._websocket._open(); - rfb._rfb_connection_state = 'connected'; - sinon.spy(rfb, "_disconnect"); - rfbs.push(rfb); - return rfb; - } - - describe('Connecting/Disconnecting', function () { - describe('#RFB', function () { - it('should set the current state to "connecting"', function () { - const client = new RFB(document.createElement('div'), 'wss://host:8675'); - client._rfb_connection_state = ''; - this.clock.tick(); - expect(client._rfb_connection_state).to.equal('connecting'); - }); - - it('should actually connect to the websocket', function () { - const client = new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); - sinon.spy(client._sock, 'open'); - this.clock.tick(); - expect(client._sock.open).to.have.been.calledOnce; - expect(client._sock.open).to.have.been.calledWith('ws://HOST:8675/PATH'); - }); - }); - - describe('#disconnect', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - it('should go to state "disconnecting" before "disconnected"', function () { - sinon.spy(client, '_updateConnectionState'); - client.disconnect(); - expect(client._updateConnectionState).to.have.been.calledTwice; - expect(client._updateConnectionState.getCall(0).args[0]) - .to.equal('disconnecting'); - expect(client._updateConnectionState.getCall(1).args[0]) - .to.equal('disconnected'); - expect(client._rfb_connection_state).to.equal('disconnected'); - }); - - it('should unregister error event handler', function () { - sinon.spy(client._sock, 'off'); - client.disconnect(); - expect(client._sock.off).to.have.been.calledWith('error'); - }); - - it('should unregister message event handler', function () { - sinon.spy(client._sock, 'off'); - client.disconnect(); - expect(client._sock.off).to.have.been.calledWith('message'); - }); - - it('should unregister open event handler', function () { - sinon.spy(client._sock, 'off'); - client.disconnect(); - expect(client._sock.off).to.have.been.calledWith('open'); - }); - }); - - describe('#sendCredentials', function () { - let client; - beforeEach(function () { - client = make_rfb(); - client._rfb_connection_state = 'connecting'; - }); - - it('should set the rfb credentials properly"', function () { - client.sendCredentials({ password: 'pass' }); - expect(client._rfb_credentials).to.deep.equal({ password: 'pass' }); - }); - - it('should call init_msg "soon"', function () { - client._init_msg = sinon.spy(); - client.sendCredentials({ password: 'pass' }); - this.clock.tick(5); - expect(client._init_msg).to.have.been.calledOnce; - }); - }); - }); - - describe('Public API Basic Behavior', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - describe('#sendCtrlAlDel', function () { - it('should sent ctrl[down]-alt[down]-del[down] then del[up]-alt[up]-ctrl[up]', function () { - const expected = {_sQ: new Uint8Array(48), _sQlen: 0, flush: () => {}}; - RFB.messages.keyEvent(expected, 0xFFE3, 1); - RFB.messages.keyEvent(expected, 0xFFE9, 1); - RFB.messages.keyEvent(expected, 0xFFFF, 1); - RFB.messages.keyEvent(expected, 0xFFFF, 0); - RFB.messages.keyEvent(expected, 0xFFE9, 0); - RFB.messages.keyEvent(expected, 0xFFE3, 0); - - client.sendCtrlAltDel(); - expect(client._sock).to.have.sent(expected._sQ); - }); - - it('should not send the keys if we are not in a normal state', function () { - sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "connecting"; - client.sendCtrlAltDel(); - expect(client._sock.flush).to.not.have.been.called; - }); - - it('should not send the keys if we are set as view_only', function () { - sinon.spy(client._sock, 'flush'); - client._viewOnly = true; - client.sendCtrlAltDel(); - expect(client._sock.flush).to.not.have.been.called; - }); - }); - - describe('#sendKey', function () { - it('should send a single key with the given code and state (down = true)', function () { - const expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: () => {}}; - RFB.messages.keyEvent(expected, 123, 1); - client.sendKey(123, 'Key123', true); - expect(client._sock).to.have.sent(expected._sQ); - }); - - it('should send both a down and up event if the state is not specified', function () { - const expected = {_sQ: new Uint8Array(16), _sQlen: 0, flush: () => {}}; - RFB.messages.keyEvent(expected, 123, 1); - RFB.messages.keyEvent(expected, 123, 0); - client.sendKey(123, 'Key123'); - expect(client._sock).to.have.sent(expected._sQ); - }); - - it('should not send the key if we are not in a normal state', function () { - sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "connecting"; - client.sendKey(123, 'Key123'); - expect(client._sock.flush).to.not.have.been.called; - }); - - it('should not send the key if we are set as view_only', function () { - sinon.spy(client._sock, 'flush'); - client._viewOnly = true; - client.sendKey(123, 'Key123'); - expect(client._sock.flush).to.not.have.been.called; - }); - - it('should send QEMU extended events if supported', function () { - client._qemuExtKeyEventSupported = true; - const expected = {_sQ: new Uint8Array(12), _sQlen: 0, flush: () => {}}; - RFB.messages.QEMUExtendedKeyEvent(expected, 0x20, true, 0x0039); - client.sendKey(0x20, 'Space', true); - expect(client._sock).to.have.sent(expected._sQ); - }); - - it('should not send QEMU extended events if unknown key code', function () { - client._qemuExtKeyEventSupported = true; - const expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: () => {}}; - RFB.messages.keyEvent(expected, 123, 1); - client.sendKey(123, 'FooBar', true); - expect(client._sock).to.have.sent(expected._sQ); - }); - }); - - describe('#focus', function () { - it('should move focus to canvas object', function () { - client._canvas.focus = sinon.spy(); - client.focus(); - expect(client._canvas.focus).to.have.been.called.once; - }); - }); - - describe('#blur', function () { - it('should remove focus from canvas object', function () { - client._canvas.blur = sinon.spy(); - client.blur(); - expect(client._canvas.blur).to.have.been.called.once; - }); - }); - - describe('#clipboardPasteFrom', function () { - it('should send the given text in a paste event', function () { - const expected = {_sQ: new Uint8Array(11), _sQlen: 0, - _sQbufferSize: 11, flush: () => {}}; - RFB.messages.clientCutText(expected, 'abc'); - client.clipboardPasteFrom('abc'); - expect(client._sock).to.have.sent(expected._sQ); - }); - - it('should flush multiple times for large clipboards', function () { - sinon.spy(client._sock, 'flush'); - let long_text = ""; - for (let i = 0; i < client._sock._sQbufferSize + 100; i++) { - long_text += 'a'; - } - client.clipboardPasteFrom(long_text); - expect(client._sock.flush).to.have.been.calledTwice; - }); - - it('should not send the text if we are not in a normal state', function () { - sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "connecting"; - client.clipboardPasteFrom('abc'); - expect(client._sock.flush).to.not.have.been.called; - }); - }); - - describe("XVP operations", function () { - beforeEach(function () { - client._rfb_xvp_ver = 1; - }); - - it('should send the shutdown signal on #machineShutdown', function () { - client.machineShutdown(); - expect(client._sock).to.have.sent(new Uint8Array([0xFA, 0x00, 0x01, 0x02])); - }); - - it('should send the reboot signal on #machineReboot', function () { - client.machineReboot(); - expect(client._sock).to.have.sent(new Uint8Array([0xFA, 0x00, 0x01, 0x03])); - }); - - it('should send the reset signal on #machineReset', function () { - client.machineReset(); - expect(client._sock).to.have.sent(new Uint8Array([0xFA, 0x00, 0x01, 0x04])); - }); - - it('should not send XVP operations with higher versions than we support', function () { - sinon.spy(client._sock, 'flush'); - client._xvpOp(2, 7); - expect(client._sock.flush).to.not.have.been.called; - }); - }); - }); - - describe('Clipping', function () { - let client; - beforeEach(function () { - client = make_rfb(); - container.style.width = '70px'; - container.style.height = '80px'; - client.clipViewport = true; - }); - - it('should update display clip state when changing the property', function () { - const spy = sinon.spy(client._display, "clipViewport", ["set"]); - - client.clipViewport = false; - expect(spy.set).to.have.been.calledOnce; - expect(spy.set).to.have.been.calledWith(false); - spy.set.reset(); - - client.clipViewport = true; - expect(spy.set).to.have.been.calledOnce; - expect(spy.set).to.have.been.calledWith(true); - }); - - it('should update the viewport when the container size changes', function () { - sinon.spy(client._display, "viewportChangeSize"); - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(); - - expect(client._display.viewportChangeSize).to.have.been.calledOnce; - expect(client._display.viewportChangeSize).to.have.been.calledWith(40, 50); - }); - - it('should update the viewport when the remote session resizes', function () { - // Simple ExtendedDesktopSize FBU message - const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xcc, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, - 0x00, 0x00, 0x00, 0x00 ]; - - sinon.spy(client._display, "viewportChangeSize"); - - client._sock._websocket._receive_data(new Uint8Array(incoming)); - - // FIXME: Display implicitly calls viewportChangeSize() when - // resizing the framebuffer, hence calledTwice. - expect(client._display.viewportChangeSize).to.have.been.calledTwice; - expect(client._display.viewportChangeSize).to.have.been.calledWith(70, 80); - }); - - it('should not update the viewport if not clipping', function () { - client.clipViewport = false; - sinon.spy(client._display, "viewportChangeSize"); - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(); - - expect(client._display.viewportChangeSize).to.not.have.been.called; - }); - - it('should not update the viewport if scaling', function () { - client.scaleViewport = true; - sinon.spy(client._display, "viewportChangeSize"); - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(); - - expect(client._display.viewportChangeSize).to.not.have.been.called; - }); - - describe('Dragging', function () { - beforeEach(function () { - client.dragViewport = true; - sinon.spy(RFB.messages, "pointerEvent"); - }); - - afterEach(function () { - RFB.messages.pointerEvent.restore(); - }); - - it('should not send button messages when initiating viewport dragging', function () { - client._handleMouseButton(13, 9, 0x001); - expect(RFB.messages.pointerEvent).to.not.have.been.called; - }); - - it('should send button messages when release without movement', function () { - // Just up and down - client._handleMouseButton(13, 9, 0x001); - client._handleMouseButton(13, 9, 0x000); - expect(RFB.messages.pointerEvent).to.have.been.calledTwice; - - RFB.messages.pointerEvent.reset(); - - // Small movement - client._handleMouseButton(13, 9, 0x001); - client._handleMouseMove(15, 14); - client._handleMouseButton(15, 14, 0x000); - expect(RFB.messages.pointerEvent).to.have.been.calledTwice; - }); - - it('should send button message directly when drag is disabled', function () { - client.dragViewport = false; - client._handleMouseButton(13, 9, 0x001); - expect(RFB.messages.pointerEvent).to.have.been.calledOnce; - }); - - it('should be initiate viewport dragging on sufficient movement', function () { - sinon.spy(client._display, "viewportChangePos"); - - // Too small movement - - client._handleMouseButton(13, 9, 0x001); - client._handleMouseMove(18, 9); - - expect(RFB.messages.pointerEvent).to.not.have.been.called; - expect(client._display.viewportChangePos).to.not.have.been.called; - - // Sufficient movement - - client._handleMouseMove(43, 9); - - expect(RFB.messages.pointerEvent).to.not.have.been.called; - expect(client._display.viewportChangePos).to.have.been.calledOnce; - expect(client._display.viewportChangePos).to.have.been.calledWith(-30, 0); - - client._display.viewportChangePos.reset(); - - // Now a small movement should move right away - - client._handleMouseMove(43, 14); - - expect(RFB.messages.pointerEvent).to.not.have.been.called; - expect(client._display.viewportChangePos).to.have.been.calledOnce; - expect(client._display.viewportChangePos).to.have.been.calledWith(0, -5); - }); - - it('should not send button messages when dragging ends', function () { - // First the movement - - client._handleMouseButton(13, 9, 0x001); - client._handleMouseMove(43, 9); - client._handleMouseButton(43, 9, 0x000); - - expect(RFB.messages.pointerEvent).to.not.have.been.called; - }); - - it('should terminate viewport dragging on a button up event', function () { - // First the dragging movement - - client._handleMouseButton(13, 9, 0x001); - client._handleMouseMove(43, 9); - client._handleMouseButton(43, 9, 0x000); - - // Another movement now should not move the viewport - - sinon.spy(client._display, "viewportChangePos"); - - client._handleMouseMove(43, 59); - - expect(client._display.viewportChangePos).to.not.have.been.called; - }); - }); - }); - - describe('Scaling', function () { - let client; - beforeEach(function () { - client = make_rfb(); - container.style.width = '70px'; - container.style.height = '80px'; - client.scaleViewport = true; - }); - - it('should update display scale factor when changing the property', function () { - const spy = sinon.spy(client._display, "scale", ["set"]); - sinon.spy(client._display, "autoscale"); - - client.scaleViewport = false; - expect(spy.set).to.have.been.calledOnce; - expect(spy.set).to.have.been.calledWith(1.0); - expect(client._display.autoscale).to.not.have.been.called; - - client.scaleViewport = true; - expect(client._display.autoscale).to.have.been.calledOnce; - expect(client._display.autoscale).to.have.been.calledWith(70, 80); - }); - - it('should update the clipping setting when changing the property', function () { - client.clipViewport = true; - - const spy = sinon.spy(client._display, "clipViewport", ["set"]); - - client.scaleViewport = false; - expect(spy.set).to.have.been.calledOnce; - expect(spy.set).to.have.been.calledWith(true); - - spy.set.reset(); - - client.scaleViewport = true; - expect(spy.set).to.have.been.calledOnce; - expect(spy.set).to.have.been.calledWith(false); - }); - - it('should update the scaling when the container size changes', function () { - sinon.spy(client._display, "autoscale"); - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(); - - expect(client._display.autoscale).to.have.been.calledOnce; - expect(client._display.autoscale).to.have.been.calledWith(40, 50); - }); - - it('should update the scaling when the remote session resizes', function () { - // Simple ExtendedDesktopSize FBU message - const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xcc, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, - 0x00, 0x00, 0x00, 0x00 ]; - - sinon.spy(client._display, "autoscale"); - - client._sock._websocket._receive_data(new Uint8Array(incoming)); - - expect(client._display.autoscale).to.have.been.calledOnce; - expect(client._display.autoscale).to.have.been.calledWith(70, 80); - }); - - it('should not update the display scale factor if not scaling', function () { - client.scaleViewport = false; - - sinon.spy(client._display, "autoscale"); - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(); - - expect(client._display.autoscale).to.not.have.been.called; - }); - }); - - describe('Remote resize', function () { - let client; - beforeEach(function () { - client = make_rfb(); - client._supportsSetDesktopSize = true; - client.resizeSession = true; - container.style.width = '70px'; - container.style.height = '80px'; - sinon.spy(RFB.messages, "setDesktopSize"); - }); - - afterEach(function () { - RFB.messages.setDesktopSize.restore(); - }); - - it('should only request a resize when turned on', function () { - client.resizeSession = false; - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - client.resizeSession = true; - expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; - }); - - it('should request a resize when initially connecting', function () { - // Simple ExtendedDesktopSize FBU message - const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x04, 0xff, 0xff, 0xfe, 0xcc, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00 ]; - - // First message should trigger a resize - - client._supportsSetDesktopSize = false; - - client._sock._websocket._receive_data(new Uint8Array(incoming)); - - expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; - expect(RFB.messages.setDesktopSize).to.have.been.calledWith(sinon.match.object, 70, 80, 0, 0); - - RFB.messages.setDesktopSize.reset(); - - // Second message should not trigger a resize - - client._sock._websocket._receive_data(new Uint8Array(incoming)); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - }); - - it('should request a resize when the container resizes', function () { - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(1000); - - expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; - expect(RFB.messages.setDesktopSize).to.have.been.calledWith(sinon.match.object, 40, 50, 0, 0); - }); - - it('should not resize until the container size is stable', function () { - container.style.width = '20px'; - container.style.height = '30px'; - const event1 = new UIEvent('resize'); - window.dispatchEvent(event1); - clock.tick(400); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - - container.style.width = '40px'; - container.style.height = '50px'; - const event2 = new UIEvent('resize'); - window.dispatchEvent(event2); - clock.tick(400); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - - clock.tick(200); - - expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; - expect(RFB.messages.setDesktopSize).to.have.been.calledWith(sinon.match.object, 40, 50, 0, 0); - }); - - it('should not resize when resize is disabled', function () { - client._resizeSession = false; - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(1000); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - }); - - it('should not resize when resize is not supported', function () { - client._supportsSetDesktopSize = false; - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(1000); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - }); - - it('should not resize when in view only mode', function () { - client._viewOnly = true; - - container.style.width = '40px'; - container.style.height = '50px'; - const event = new UIEvent('resize'); - window.dispatchEvent(event); - clock.tick(1000); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - }); - - it('should not try to override a server resize', function () { - // Simple ExtendedDesktopSize FBU message - const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x04, 0xff, 0xff, 0xfe, 0xcc, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00 ]; - - client._sock._websocket._receive_data(new Uint8Array(incoming)); - - expect(RFB.messages.setDesktopSize).to.not.have.been.called; - }); - }); - - describe('Misc Internals', function () { - describe('#_updateConnectionState', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - it('should clear the disconnect timer if the state is not "disconnecting"', function () { - const spy = sinon.spy(); - client._disconnTimer = setTimeout(spy, 50); - client._rfb_connection_state = 'connecting'; - client._updateConnectionState('connected'); - this.clock.tick(51); - expect(spy).to.not.have.been.called; - expect(client._disconnTimer).to.be.null; - }); - - it('should set the rfb_connection_state', function () { - client._rfb_connection_state = 'connecting'; - client._updateConnectionState('connected'); - expect(client._rfb_connection_state).to.equal('connected'); - }); - - it('should not change the state when we are disconnected', function () { - client.disconnect(); - expect(client._rfb_connection_state).to.equal('disconnected'); - client._updateConnectionState('connecting'); - expect(client._rfb_connection_state).to.not.equal('connecting'); - }); - - it('should ignore state changes to the same state', function () { - const connectSpy = sinon.spy(); - client.addEventListener("connect", connectSpy); - - expect(client._rfb_connection_state).to.equal('connected'); - client._updateConnectionState('connected'); - expect(connectSpy).to.not.have.been.called; - - client.disconnect(); - - const disconnectSpy = sinon.spy(); - client.addEventListener("disconnect", disconnectSpy); - - expect(client._rfb_connection_state).to.equal('disconnected'); - client._updateConnectionState('disconnected'); - expect(disconnectSpy).to.not.have.been.called; - }); - - it('should ignore illegal state changes', function () { - const spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._updateConnectionState('disconnected'); - expect(client._rfb_connection_state).to.not.equal('disconnected'); - expect(spy).to.not.have.been.called; - }); - }); - - describe('#_fail', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - it('should close the WebSocket connection', function () { - sinon.spy(client._sock, 'close'); - client._fail(); - expect(client._sock.close).to.have.been.calledOnce; - }); - - it('should transition to disconnected', function () { - sinon.spy(client, '_updateConnectionState'); - client._fail(); - this.clock.tick(2000); - expect(client._updateConnectionState).to.have.been.called; - expect(client._rfb_connection_state).to.equal('disconnected'); - }); - - it('should set clean_disconnect variable', function () { - client._rfb_clean_disconnect = true; - client._rfb_connection_state = 'connected'; - client._fail(); - expect(client._rfb_clean_disconnect).to.be.false; - }); - - it('should result in disconnect event with clean set to false', function () { - client._rfb_connection_state = 'connected'; - const spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._fail(); - this.clock.tick(2000); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.clean).to.be.false; - }); - - }); - }); - - describe('Connection States', function () { - describe('connecting', function () { - it('should open the websocket connection', function () { - const client = new RFB(document.createElement('div'), - 'ws://HOST:8675/PATH'); - sinon.spy(client._sock, 'open'); - this.clock.tick(); - expect(client._sock.open).to.have.been.calledOnce; - }); - }); - - describe('connected', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - it('should result in a connect event if state becomes connected', function () { - const spy = sinon.spy(); - client.addEventListener("connect", spy); - client._rfb_connection_state = 'connecting'; - client._updateConnectionState('connected'); - expect(spy).to.have.been.calledOnce; - }); - - it('should not result in a connect event if the state is not "connected"', function () { - const spy = sinon.spy(); - client.addEventListener("connect", spy); - client._sock._websocket.open = () => {}; // explicitly don't call onopen - client._updateConnectionState('connecting'); - expect(spy).to.not.have.been.called; - }); - }); - - describe('disconnecting', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - it('should force disconnect if we do not call Websock.onclose within the disconnection timeout', function () { - sinon.spy(client, '_updateConnectionState'); - client._sock._websocket.close = () => {}; // explicitly don't call onclose - client._updateConnectionState('disconnecting'); - this.clock.tick(3 * 1000); - expect(client._updateConnectionState).to.have.been.calledTwice; - expect(client._rfb_disconnect_reason).to.not.equal(""); - expect(client._rfb_connection_state).to.equal("disconnected"); - }); - - it('should not fail if Websock.onclose gets called within the disconnection timeout', function () { - client._updateConnectionState('disconnecting'); - this.clock.tick(3 * 1000 / 2); - client._sock._websocket.close(); - this.clock.tick(3 * 1000 / 2 + 1); - expect(client._rfb_connection_state).to.equal('disconnected'); - }); - - it('should close the WebSocket connection', function () { - sinon.spy(client._sock, 'close'); - client._updateConnectionState('disconnecting'); - expect(client._sock.close).to.have.been.calledOnce; - }); - - it('should not result in a disconnect event', function () { - const spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._sock._websocket.close = () => {}; // explicitly don't call onclose - client._updateConnectionState('disconnecting'); - expect(spy).to.not.have.been.called; - }); - }); - - describe('disconnected', function () { - let client; - beforeEach(function () { - client = new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); - }); - - it('should result in a disconnect event if state becomes "disconnected"', function () { - const spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'disconnecting'; - client._updateConnectionState('disconnected'); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.clean).to.be.true; - }); - - it('should result in a disconnect event without msg when no reason given', function () { - const spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'disconnecting'; - client._rfb_disconnect_reason = ""; - client._updateConnectionState('disconnected'); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0].length).to.equal(1); - }); - }); - }); - - describe('Protocol Initialization States', function () { - let client; - beforeEach(function () { - client = make_rfb(); - client._rfb_connection_state = 'connecting'; - }); - - describe('ProtocolVersion', function () { - function send_ver(ver, client) { - const arr = new Uint8Array(12); - for (let i = 0; i < ver.length; i++) { - arr[i+4] = ver.charCodeAt(i); - } - arr[0] = 'R'; arr[1] = 'F'; arr[2] = 'B'; arr[3] = ' '; - arr[11] = '\n'; - client._sock._websocket._receive_data(arr); - } - - describe('version parsing', function () { - it('should interpret version 003.003 as version 3.3', function () { - send_ver('003.003', client); - expect(client._rfb_version).to.equal(3.3); - }); - - it('should interpret version 003.006 as version 3.3', function () { - send_ver('003.006', client); - expect(client._rfb_version).to.equal(3.3); - }); - - it('should interpret version 003.889 as version 3.3', function () { - send_ver('003.889', client); - expect(client._rfb_version).to.equal(3.3); - }); - - it('should interpret version 003.007 as version 3.7', function () { - send_ver('003.007', client); - expect(client._rfb_version).to.equal(3.7); - }); - - it('should interpret version 003.008 as version 3.8', function () { - send_ver('003.008', client); - expect(client._rfb_version).to.equal(3.8); - }); - - it('should interpret version 004.000 as version 3.8', function () { - send_ver('004.000', client); - expect(client._rfb_version).to.equal(3.8); - }); - - it('should interpret version 004.001 as version 3.8', function () { - send_ver('004.001', client); - expect(client._rfb_version).to.equal(3.8); - }); - - it('should interpret version 005.000 as version 3.8', function () { - send_ver('005.000', client); - expect(client._rfb_version).to.equal(3.8); - }); - - it('should fail on an invalid version', function () { - sinon.spy(client, "_fail"); - send_ver('002.000', client); - expect(client._fail).to.have.been.calledOnce; - }); - }); - - it('should send back the interpreted version', function () { - send_ver('004.000', client); - - const expected_str = 'RFB 003.008\n'; - const expected = []; - for (let i = 0; i < expected_str.length; i++) { - expected[i] = expected_str.charCodeAt(i); - } - - expect(client._sock).to.have.sent(new Uint8Array(expected)); - }); - - it('should transition to the Security state on successful negotiation', function () { - send_ver('003.008', client); - expect(client._rfb_init_state).to.equal('Security'); - }); - - describe('Repeater', function () { - beforeEach(function () { - client = make_rfb('wss://host:8675', { repeaterID: "12345" }); - client._rfb_connection_state = 'connecting'; - }); - - it('should interpret version 000.000 as a repeater', function () { - send_ver('000.000', client); - expect(client._rfb_version).to.equal(0); - - const sent_data = client._sock._websocket._get_sent_data(); - expect(new Uint8Array(sent_data.buffer, 0, 9)).to.array.equal(new Uint8Array([73, 68, 58, 49, 50, 51, 52, 53, 0])); - expect(sent_data).to.have.length(250); - }); - - it('should handle two step repeater negotiation', function () { - send_ver('000.000', client); - send_ver('003.008', client); - expect(client._rfb_version).to.equal(3.8); - }); - }); - }); - - describe('Security', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - }); - - it('should simply receive the auth scheme when for versions < 3.7', function () { - client._rfb_version = 3.6; - const auth_scheme_raw = [1, 2, 3, 4]; - const auth_scheme = (auth_scheme_raw[0] << 24) + (auth_scheme_raw[1] << 16) + - (auth_scheme_raw[2] << 8) + auth_scheme_raw[3]; - client._sock._websocket._receive_data(auth_scheme_raw); - expect(client._rfb_auth_scheme).to.equal(auth_scheme); - }); - - it('should prefer no authentication is possible', function () { - client._rfb_version = 3.7; - const auth_schemes = [2, 1, 3]; - client._sock._websocket._receive_data(auth_schemes); - expect(client._rfb_auth_scheme).to.equal(1); - expect(client._sock).to.have.sent(new Uint8Array([1, 1])); - }); - - it('should choose for the most prefered scheme possible for versions >= 3.7', function () { - client._rfb_version = 3.7; - const auth_schemes = [2, 22, 16]; - client._sock._websocket._receive_data(auth_schemes); - expect(client._rfb_auth_scheme).to.equal(22); - expect(client._sock).to.have.sent(new Uint8Array([22])); - }); - - it('should fail if there are no supported schemes for versions >= 3.7', function () { - sinon.spy(client, "_fail"); - client._rfb_version = 3.7; - const auth_schemes = [1, 32]; - client._sock._websocket._receive_data(auth_schemes); - expect(client._fail).to.have.been.calledOnce; - }); - - it('should fail with the appropriate message if no types are sent for versions >= 3.7', function () { - client._rfb_version = 3.7; - const failure_data = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; - sinon.spy(client, '_fail'); - client._sock._websocket._receive_data(failure_data); - - expect(client._fail).to.have.been.calledOnce; - expect(client._fail).to.have.been.calledWith( - 'Security negotiation failed on no security types (reason: whoops)'); - }); - - it('should transition to the Authentication state and continue on successful negotiation', function () { - client._rfb_version = 3.7; - const auth_schemes = [1, 1]; - client._negotiate_authentication = sinon.spy(); - client._sock._websocket._receive_data(auth_schemes); - expect(client._rfb_init_state).to.equal('Authentication'); - expect(client._negotiate_authentication).to.have.been.calledOnce; - }); - }); - - describe('Authentication', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - }); - - function send_security(type, cl) { - cl._sock._websocket._receive_data(new Uint8Array([1, type])); - } - - it('should fail on auth scheme 0 (pre 3.7) with the given message', function () { - client._rfb_version = 3.6; - const err_msg = "Whoopsies"; - const data = [0, 0, 0, 0]; - const err_len = err_msg.length; - push32(data, err_len); - for (let i = 0; i < err_len; i++) { - data.push(err_msg.charCodeAt(i)); - } - - sinon.spy(client, '_fail'); - client._sock._websocket._receive_data(new Uint8Array(data)); - expect(client._fail).to.have.been.calledWith( - 'Security negotiation failed on authentication scheme (reason: Whoopsies)'); - }); - - it('should transition straight to SecurityResult on "no auth" (1) for versions >= 3.8', function () { - client._rfb_version = 3.8; - send_security(1, client); - expect(client._rfb_init_state).to.equal('SecurityResult'); - }); - - it('should transition straight to ServerInitialisation on "no auth" for versions < 3.8', function () { - client._rfb_version = 3.7; - send_security(1, client); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); - }); - - it('should fail on an unknown auth scheme', function () { - sinon.spy(client, "_fail"); - client._rfb_version = 3.8; - send_security(57, client); - expect(client._fail).to.have.been.calledOnce; - }); - - describe('VNC Authentication (type 2) Handler', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; - }); - - it('should fire the credentialsrequired event if missing a password', function () { - const spy = sinon.spy(); - client.addEventListener("credentialsrequired", spy); - send_security(2, client); - - const challenge = []; - for (let i = 0; i < 16; i++) { challenge[i] = i; } - client._sock._websocket._receive_data(new Uint8Array(challenge)); - - expect(client._rfb_credentials).to.be.empty; - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.types).to.have.members(["password"]); - }); - - it('should encrypt the password with DES and then send it back', function () { - client._rfb_credentials = { password: 'passwd' }; - send_security(2, client); - client._sock._websocket._get_sent_data(); // skip the choice of auth reply - - const challenge = []; - for (let i = 0; i < 16; i++) { challenge[i] = i; } - client._sock._websocket._receive_data(new Uint8Array(challenge)); - - const des_pass = RFB.genDES('passwd', challenge); - expect(client._sock).to.have.sent(new Uint8Array(des_pass)); - }); - - it('should transition to SecurityResult immediately after sending the password', function () { - client._rfb_credentials = { password: 'passwd' }; - send_security(2, client); - - const challenge = []; - for (let i = 0; i < 16; i++) { challenge[i] = i; } - client._sock._websocket._receive_data(new Uint8Array(challenge)); - - expect(client._rfb_init_state).to.equal('SecurityResult'); - }); - }); - - describe('XVP Authentication (type 22) Handler', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; - }); - - it('should fall through to standard VNC authentication upon completion', function () { - client._rfb_credentials = { username: 'user', - target: 'target', - password: 'password' }; - client._negotiate_std_vnc_auth = sinon.spy(); - send_security(22, client); - expect(client._negotiate_std_vnc_auth).to.have.been.calledOnce; - }); - - it('should fire the credentialsrequired event if all credentials are missing', function () { - const spy = sinon.spy(); - client.addEventListener("credentialsrequired", spy); - client._rfb_credentials = {}; - send_security(22, client); - - expect(client._rfb_credentials).to.be.empty; - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.types).to.have.members(["username", "password", "target"]); - }); - - it('should fire the credentialsrequired event if some credentials are missing', function () { - const spy = sinon.spy(); - client.addEventListener("credentialsrequired", spy); - client._rfb_credentials = { username: 'user', - target: 'target' }; - send_security(22, client); - - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.types).to.have.members(["username", "password", "target"]); - }); - - it('should send user and target separately', function () { - client._rfb_credentials = { username: 'user', - target: 'target', - password: 'password' }; - client._negotiate_std_vnc_auth = sinon.spy(); - - send_security(22, client); - - const expected = [22, 4, 6]; // auth selection, len user, len target - for (let i = 0; i < 10; i++) { expected[i+3] = 'usertarget'.charCodeAt(i); } - - expect(client._sock).to.have.sent(new Uint8Array(expected)); - }); - }); - - describe('TightVNC Authentication (type 16) Handler', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; - send_security(16, client); - client._sock._websocket._get_sent_data(); // skip the security reply - }); - - function send_num_str_pairs(pairs, client) { - const data = []; - push32(data, pairs.length); - - for (let i = 0; i < pairs.length; i++) { - push32(data, pairs[i][0]); - for (let j = 0; j < 4; j++) { - data.push(pairs[i][1].charCodeAt(j)); - } - for (let j = 0; j < 8; j++) { - data.push(pairs[i][2].charCodeAt(j)); - } - } - - client._sock._websocket._receive_data(new Uint8Array(data)); - } - - it('should skip tunnel negotiation if no tunnels are requested', function () { - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_tightvnc).to.be.true; - }); - - it('should fail if no supported tunnels are listed', function () { - sinon.spy(client, "_fail"); - send_num_str_pairs([[123, 'OTHR', 'SOMETHNG']], client); - expect(client._fail).to.have.been.calledOnce; - }); - - it('should choose the notunnel tunnel type', function () { - send_num_str_pairs([[0, 'TGHT', 'NOTUNNEL'], [123, 'OTHR', 'SOMETHNG']], client); - expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 0])); - }); - - it('should choose the notunnel tunnel type for Siemens devices', function () { - send_num_str_pairs([[1, 'SICR', 'SCHANNEL'], [2, 'SICR', 'SCHANLPW']], client); - expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 0])); - }); - - it('should continue to sub-auth negotiation after tunnel negotiation', function () { - send_num_str_pairs([[0, 'TGHT', 'NOTUNNEL']], client); - client._sock._websocket._get_sent_data(); // skip the tunnel choice here - send_num_str_pairs([[1, 'STDV', 'NOAUTH__']], client); - expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 1])); - expect(client._rfb_init_state).to.equal('SecurityResult'); - }); - - /*it('should attempt to use VNC auth over no auth when possible', function () { - client._rfb_tightvnc = true; - client._negotiate_std_vnc_auth = sinon.spy(); - send_num_str_pairs([[1, 'STDV', 'NOAUTH__'], [2, 'STDV', 'VNCAUTH_']], client); - expect(client._sock).to.have.sent([0, 0, 0, 1]); - expect(client._negotiate_std_vnc_auth).to.have.been.calledOnce; - expect(client._rfb_auth_scheme).to.equal(2); - });*/ // while this would make sense, the original code doesn't actually do this - - it('should accept the "no auth" auth type and transition to SecurityResult', function () { - client._rfb_tightvnc = true; - send_num_str_pairs([[1, 'STDV', 'NOAUTH__']], client); - expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 1])); - expect(client._rfb_init_state).to.equal('SecurityResult'); - }); - - it('should accept VNC authentication and transition to that', function () { - client._rfb_tightvnc = true; - client._negotiate_std_vnc_auth = sinon.spy(); - send_num_str_pairs([[2, 'STDV', 'VNCAUTH__']], client); - expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 2])); - expect(client._negotiate_std_vnc_auth).to.have.been.calledOnce; - expect(client._rfb_auth_scheme).to.equal(2); - }); - - it('should fail if there are no supported auth types', function () { - sinon.spy(client, "_fail"); - client._rfb_tightvnc = true; - send_num_str_pairs([[23, 'stdv', 'badval__']], client); - expect(client._fail).to.have.been.calledOnce; - }); - }); - }); - - describe('SecurityResult', function () { - beforeEach(function () { - client._rfb_init_state = 'SecurityResult'; - }); - - it('should fall through to ServerInitialisation on a response code of 0', function () { - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); - }); - - it('should fail on an error code of 1 with the given message for versions >= 3.8', function () { - client._rfb_version = 3.8; - sinon.spy(client, '_fail'); - const failure_data = [0, 0, 0, 1, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); - expect(client._fail).to.have.been.calledWith( - 'Security negotiation failed on security result (reason: whoops)'); - }); - - it('should fail on an error code of 1 with a standard message for version < 3.8', function () { - sinon.spy(client, '_fail'); - client._rfb_version = 3.7; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 1])); - expect(client._fail).to.have.been.calledWith( - 'Security handshake failed'); - }); - - it('should result in securityfailure event when receiving a non zero status', function () { - const spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.status).to.equal(2); - }); - - it('should include reason when provided in securityfailure event', function () { - client._rfb_version = 3.8; - const spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - const failure_data = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, - 32, 102, 97, 105, 108, 117, 114, 101]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); - expect(spy.args[0][0].detail.status).to.equal(1); - expect(spy.args[0][0].detail.reason).to.equal('such failure'); - }); - - it('should not include reason when length is zero in securityfailure event', function () { - client._rfb_version = 3.9; - const spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - const failure_data = [0, 0, 0, 1, 0, 0, 0, 0]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); - expect(spy.args[0][0].detail.status).to.equal(1); - expect('reason' in spy.args[0][0].detail).to.be.false; - }); - - it('should not include reason in securityfailure event for version < 3.8', function () { - client._rfb_version = 3.6; - const spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); - expect(spy.args[0][0].detail.status).to.equal(2); - expect('reason' in spy.args[0][0].detail).to.be.false; - }); - }); - - describe('ClientInitialisation', function () { - it('should transition to the ServerInitialisation state', function () { - const client = make_rfb(); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); - }); - - it('should send 1 if we are in shared mode', function () { - const client = make_rfb('wss://host:8675', { shared: true }); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._sock).to.have.sent(new Uint8Array([1])); - }); - - it('should send 0 if we are not in shared mode', function () { - const client = make_rfb('wss://host:8675', { shared: false }); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._sock).to.have.sent(new Uint8Array([0])); - }); - }); - - describe('ServerInitialisation', function () { - beforeEach(function () { - client._rfb_init_state = 'ServerInitialisation'; - }); - - function send_server_init(opts, client) { - const full_opts = { width: 10, height: 12, bpp: 24, depth: 24, big_endian: 0, - true_color: 1, red_max: 255, green_max: 255, blue_max: 255, - red_shift: 16, green_shift: 8, blue_shift: 0, name: 'a name' }; - for (let opt in opts) { - full_opts[opt] = opts[opt]; - } - const data = []; - - push16(data, full_opts.width); - push16(data, full_opts.height); - - data.push(full_opts.bpp); - data.push(full_opts.depth); - data.push(full_opts.big_endian); - data.push(full_opts.true_color); - - push16(data, full_opts.red_max); - push16(data, full_opts.green_max); - push16(data, full_opts.blue_max); - push8(data, full_opts.red_shift); - push8(data, full_opts.green_shift); - push8(data, full_opts.blue_shift); - - // padding - push8(data, 0); - push8(data, 0); - push8(data, 0); - - client._sock._websocket._receive_data(new Uint8Array(data)); - - const name_data = []; - push32(name_data, full_opts.name.length); - for (let i = 0; i < full_opts.name.length; i++) { - name_data.push(full_opts.name.charCodeAt(i)); - } - client._sock._websocket._receive_data(new Uint8Array(name_data)); - } - - it('should set the framebuffer width and height', function () { - send_server_init({ width: 32, height: 84 }, client); - expect(client._fb_width).to.equal(32); - expect(client._fb_height).to.equal(84); - }); - - // NB(sross): we just warn, not fail, for endian-ness and shifts, so we don't test them - - it('should set the framebuffer name and call the callback', function () { - const spy = sinon.spy(); - client.addEventListener("desktopname", spy); - send_server_init({ name: 'some name' }, client); - - expect(client._fb_name).to.equal('some name'); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.name).to.equal('some name'); - }); - - it('should handle the extended init message of the tight encoding', function () { - // NB(sross): we don't actually do anything with it, so just test that we can - // read it w/o throwing an error - client._rfb_tightvnc = true; - send_server_init({}, client); - - const tight_data = []; - push16(tight_data, 1); - push16(tight_data, 2); - push16(tight_data, 3); - push16(tight_data, 0); - for (let i = 0; i < 16 + 32 + 48; i++) { - tight_data.push(i); - } - client._sock._websocket._receive_data(tight_data); - - expect(client._rfb_connection_state).to.equal('connected'); - }); - - it('should resize the display', function () { - sinon.spy(client._display, 'resize'); - send_server_init({ width: 27, height: 32 }, client); - - expect(client._display.resize).to.have.been.calledOnce; - expect(client._display.resize).to.have.been.calledWith(27, 32); - }); - - it('should grab the mouse and keyboard', function () { - sinon.spy(client._keyboard, 'grab'); - sinon.spy(client._mouse, 'grab'); - send_server_init({}, client); - expect(client._keyboard.grab).to.have.been.calledOnce; - expect(client._mouse.grab).to.have.been.calledOnce; - }); - - describe('Initial Update Request', function () { - beforeEach(function () { - sinon.spy(RFB.messages, "pixelFormat"); - sinon.spy(RFB.messages, "clientEncodings"); - sinon.spy(RFB.messages, "fbUpdateRequest"); - }); - - afterEach(function () { - RFB.messages.pixelFormat.restore(); - RFB.messages.clientEncodings.restore(); - RFB.messages.fbUpdateRequest.restore(); - }); - - // TODO(directxman12): test the various options in this configuration matrix - it('should reply with the pixel format, client encodings, and initial update request', function () { - send_server_init({ width: 27, height: 32 }, client); - - expect(RFB.messages.pixelFormat).to.have.been.calledOnce; - expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 24, true); - expect(RFB.messages.pixelFormat).to.have.been.calledBefore(RFB.messages.clientEncodings); - expect(RFB.messages.clientEncodings).to.have.been.calledOnce; - expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.encodingTight); - expect(RFB.messages.clientEncodings).to.have.been.calledBefore(RFB.messages.fbUpdateRequest); - expect(RFB.messages.fbUpdateRequest).to.have.been.calledOnce; - expect(RFB.messages.fbUpdateRequest).to.have.been.calledWith(client._sock, false, 0, 0, 27, 32); - }); - - it('should reply with restricted settings for Intel AMT servers', function () { - send_server_init({ width: 27, height: 32, name: "Intel(r) AMT KVM"}, client); - - expect(RFB.messages.pixelFormat).to.have.been.calledOnce; - expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 8, true); - expect(RFB.messages.pixelFormat).to.have.been.calledBefore(RFB.messages.clientEncodings); - expect(RFB.messages.clientEncodings).to.have.been.calledOnce; - expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.not.include(encodings.encodingTight); - expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.not.include(encodings.encodingHextile); - expect(RFB.messages.clientEncodings).to.have.been.calledBefore(RFB.messages.fbUpdateRequest); - expect(RFB.messages.fbUpdateRequest).to.have.been.calledOnce; - expect(RFB.messages.fbUpdateRequest).to.have.been.calledWith(client._sock, false, 0, 0, 27, 32); - }); - }); - - it('should transition to the "connected" state', function () { - send_server_init({}, client); - expect(client._rfb_connection_state).to.equal('connected'); - }); - }); - }); - - describe('Protocol Message Processing After Completing Initialization', function () { - let client; - - beforeEach(function () { - client = make_rfb(); - client._fb_name = 'some device'; - client._fb_width = 640; - client._fb_height = 20; - }); - - describe('Framebuffer Update Handling', function () { - const target_data_arr = [ - 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255, - 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255 - ]; - let target_data; - - const target_data_check_arr = [ - 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, - 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, - 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 - ]; - let target_data_check; - - before(function () { - // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray - target_data = new Uint8Array(target_data_arr); - target_data_check = new Uint8Array(target_data_check_arr); - }); - - function send_fbu_msg(rect_info, rect_data, client, rect_cnt) { - let data = []; - - if (!rect_cnt || rect_cnt > -1) { - // header - data.push(0); // msg type - data.push(0); // padding - push16(data, rect_cnt || rect_data.length); - } - - for (let i = 0; i < rect_data.length; i++) { - if (rect_info[i]) { - push16(data, rect_info[i].x); - push16(data, rect_info[i].y); - push16(data, rect_info[i].width); - push16(data, rect_info[i].height); - push32(data, rect_info[i].encoding); - } - data = data.concat(rect_data[i]); - } - - client._sock._websocket._receive_data(new Uint8Array(data)); - } - - it('should send an update request if there is sufficient data', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); - - client._framebufferUpdate = () => true; - client._sock._websocket._receive_data(new Uint8Array([0])); - - expect(client._sock).to.have.sent(expected_msg._sQ); - }); - - it('should not send an update request if we need more data', function () { - client._sock._websocket._receive_data(new Uint8Array([0])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); - }); - - it('should resume receiving an update if we previously did not have enough data', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); - - // just enough to set FBU.rects - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 3])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); - - client._framebufferUpdate = function () { this._sock.rQskipBytes(1); return true; }; // we magically have enough data - // 247 should *not* be used as the message type here - client._sock._websocket._receive_data(new Uint8Array([247])); - expect(client._sock).to.have.sent(expected_msg._sQ); - }); - - it('should not send a request in continuous updates mode', function () { - client._enabledContinuousUpdates = true; - client._framebufferUpdate = () => true; - client._sock._websocket._receive_data(new Uint8Array([0])); - - expect(client._sock._websocket._get_sent_data()).to.have.length(0); - }); - - it('should fail on an unsupported encoding', function () { - sinon.spy(client, "_fail"); - const rect_info = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; - send_fbu_msg([rect_info], [[]], client); - expect(client._fail).to.have.been.calledOnce; - }); - - it('should be able to pause and resume receiving rects if not enought data', function () { - // seed some initial data to copy - client._fb_width = 4; - client._fb_height = 4; - client._display.resize(4, 4); - client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); - - const info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, - { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; - // data says [{ old_x: 2, old_y: 0 }, { old_x: 0, old_y: 0 }] - const rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; - send_fbu_msg([info[0]], [rects[0]], client, 2); - send_fbu_msg([info[1]], [rects[1]], client, -1); - expect(client._display).to.have.displayed(target_data_check); - }); - - describe('Message Encoding Handlers', function () { - beforeEach(function () { - // a really small frame - client._fb_width = 4; - client._fb_height = 4; - client._fb_depth = 24; - client._display.resize(4, 4); - }); - - it('should handle the RAW encoding', function () { - const info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 2, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 0, y: 2, width: 4, height: 1, encoding: 0x00 }, - { x: 0, y: 3, width: 4, height: 1, encoding: 0x00 }]; - // data is in bgrx - const rects = [ - [0x00, 0x00, 0xff, 0, 0x00, 0xff, 0x00, 0, 0x00, 0xff, 0x00, 0, 0x00, 0x00, 0xff, 0], - [0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0], - [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0], - [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0]]; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data); - }); - - it('should handle the RAW encoding in low colour mode', function () { - const info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 2, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 0, y: 2, width: 4, height: 1, encoding: 0x00 }, - { x: 0, y: 3, width: 4, height: 1, encoding: 0x00 }]; - const rects = [ - [0x03, 0x03, 0x03, 0x03], - [0x0c, 0x0c, 0x0c, 0x0c], - [0x0c, 0x0c, 0x03, 0x03], - [0x0c, 0x0c, 0x03, 0x03]]; - client._fb_depth = 8; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data_check); - }); - - it('should handle the COPYRECT encoding', function () { - // seed some initial data to copy - client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); - - const info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, - { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; - // data says [{ old_x: 0, old_y: 0 }, { old_x: 0, old_y: 0 }] - const rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data_check); - }); - - // TODO(directxman12): for encodings with subrects, test resuming on partial send? - // TODO(directxman12): test rre_chunk_sz (related to above about subrects)? - - it('should handle the RRE encoding', function () { - const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x02 }]; - const rect = []; - push32(rect, 2); // 2 subrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(0xff); // becomes ff0000ff --> #0000FF color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - push16(rect, 0); // x: 0 - push16(rect, 0); // y: 0 - push16(rect, 2); // width: 2 - push16(rect, 2); // height: 2 - rect.push(0xff); // becomes ff0000ff --> #0000FF color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - push16(rect, 2); // x: 2 - push16(rect, 2); // y: 2 - push16(rect, 2); // width: 2 - push16(rect, 2); // height: 2 - - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); - }); - - describe('the HEXTILE encoding handler', function () { - it('should handle a tile with fg, bg specified, normal subrects', function () { - const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - const rect = []; - rect.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(2); // 2 subrects - rect.push(0); // x: 0, y: 0 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - rect.push(2 | (2 << 4)); // x: 2, y: 2 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); - }); - - it('should handle a raw tile', function () { - const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - const rect = []; - rect.push(0x01); // raw - for (let i = 0; i < target_data.length; i += 4) { - rect.push(target_data[i + 2]); - rect.push(target_data[i + 1]); - rect.push(target_data[i]); - rect.push(target_data[i + 3]); - } - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data); - }); - - it('should handle a tile with only bg specified (solid bg)', function () { - const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - const rect = []; - rect.push(0x02); - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - send_fbu_msg(info, [rect], client); - - const expected = []; - for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } - expect(client._display).to.have.displayed(new Uint8Array(expected)); - }); - - it('should handle a tile with only bg specified and an empty frame afterwards', function () { - // set the width so we can have two tiles - client._fb_width = 8; - client._display.resize(8, 4); - - const info = [{ x: 0, y: 0, width: 32, height: 4, encoding: 0x05 }]; - - const rect = []; - - // send a bg frame - rect.push(0x02); - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - - // send an empty frame - rect.push(0x00); - - send_fbu_msg(info, [rect], client); - - const expected = []; - for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 1: solid - for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 2: same bkground color - expect(client._display).to.have.displayed(new Uint8Array(expected)); - }); - - it('should handle a tile with bg and coloured subrects', function () { - const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - const rect = []; - rect.push(0x02 | 0x08 | 0x10); // bg spec, anysubrects, colouredsubrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(2); // 2 subrects - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(0); // x: 0, y: 0 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(2 | (2 << 4)); // x: 2, y: 2 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); - }); - - it('should carry over fg and bg colors from the previous tile if not specified', function () { - client._fb_width = 4; - client._fb_height = 17; - client._display.resize(4, 17); - - const info = [{ x: 0, y: 0, width: 4, height: 17, encoding: 0x05}]; - const rect = []; - rect.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(8); // 8 subrects - for (let i = 0; i < 4; i++) { - rect.push((0 << 4) | (i * 4)); // x: 0, y: i*4 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - rect.push((2 << 4) | (i * 4 + 2)); // x: 2, y: i * 4 + 2 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - } - rect.push(0x08); // anysubrects - rect.push(1); // 1 subrect - rect.push(0); // x: 0, y: 0 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - - let expected = []; - for (let i = 0; i < 4; i++) { expected = expected.concat(target_data_check_arr); } - expected = expected.concat(target_data_check_arr.slice(0, 16)); - expect(client._display).to.have.displayed(new Uint8Array(expected)); - }); - - it('should fail on an invalid subencoding', function () { - sinon.spy(client, "_fail"); - const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - const rects = [[45]]; // an invalid subencoding - send_fbu_msg(info, rects, client); - expect(client._fail).to.have.been.calledOnce; - }); - }); - - it.skip('should handle the TIGHT encoding', function () { - // TODO(directxman12): test this - }); - - it.skip('should handle the TIGHT_PNG encoding', function () { - // TODO(directxman12): test this - }); - - it('should handle the DesktopSize pseduo-encoding', function () { - sinon.spy(client._display, 'resize'); - send_fbu_msg([{ x: 0, y: 0, width: 20, height: 50, encoding: -223 }], [[]], client); - - expect(client._fb_width).to.equal(20); - expect(client._fb_height).to.equal(50); - - expect(client._display.resize).to.have.been.calledOnce; - expect(client._display.resize).to.have.been.calledWith(20, 50); - }); - - describe('the ExtendedDesktopSize pseudo-encoding handler', function () { - beforeEach(function () { - // a really small frame - client._fb_width = 4; - client._fb_height = 4; - client._display.resize(4, 4); - sinon.spy(client._display, 'resize'); - }); - - function make_screen_data(nr_of_screens) { - const data = []; - push8(data, nr_of_screens); // number-of-screens - push8(data, 0); // padding - push16(data, 0); // padding - for (let i=0; i {}}; - const incoming_msg = {_sQ: new Uint8Array(16), _sQlen: 0, flush: () => {}}; - - const payload = "foo\x00ab9"; - - // ClientFence and ServerFence are identical in structure - RFB.messages.clientFence(expected_msg, (1<<0) | (1<<1), payload); - RFB.messages.clientFence(incoming_msg, 0xffffffff, payload); - - client._sock._websocket._receive_data(incoming_msg._sQ); - - expect(client._sock).to.have.sent(expected_msg._sQ); - - expected_msg._sQlen = 0; - incoming_msg._sQlen = 0; - - RFB.messages.clientFence(expected_msg, (1<<0), payload); - RFB.messages.clientFence(incoming_msg, (1<<0) | (1<<31), payload); - - client._sock._websocket._receive_data(incoming_msg._sQ); - - expect(client._sock).to.have.sent(expected_msg._sQ); - }); - - it('should enable continuous updates on first EndOfContinousUpdates', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - - RFB.messages.enableContinuousUpdates(expected_msg, true, 0, 0, 640, 20); - - expect(client._enabledContinuousUpdates).to.be.false; - - client._sock._websocket._receive_data(new Uint8Array([150])); - - expect(client._enabledContinuousUpdates).to.be.true; - expect(client._sock).to.have.sent(expected_msg._sQ); - }); - - it('should disable continuous updates on subsequent EndOfContinousUpdates', function () { - client._enabledContinuousUpdates = true; - client._supportsContinuousUpdates = true; - - client._sock._websocket._receive_data(new Uint8Array([150])); - - expect(client._enabledContinuousUpdates).to.be.false; - }); - - it('should update continuous updates on resize', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.enableContinuousUpdates(expected_msg, true, 0, 0, 90, 700); - - client._resize(450, 160); - - expect(client._sock._websocket._get_sent_data()).to.have.length(0); - - client._enabledContinuousUpdates = true; - - client._resize(90, 700); - - expect(client._sock).to.have.sent(expected_msg._sQ); - }); - - it('should fail on an unknown message type', function () { - sinon.spy(client, "_fail"); - client._sock._websocket._receive_data(new Uint8Array([87])); - expect(client._fail).to.have.been.calledOnce; - }); - }); - - describe('Asynchronous Events', function () { - let client; - beforeEach(function () { - client = make_rfb(); - }); - - describe('Mouse event handlers', function () { - it('should not send button messages in view-only mode', function () { - client._viewOnly = true; - sinon.spy(client._sock, 'flush'); - client._handleMouseButton(0, 0, 1, 0x001); - expect(client._sock.flush).to.not.have.been.called; - }); - - it('should not send movement messages in view-only mode', function () { - client._viewOnly = true; - sinon.spy(client._sock, 'flush'); - client._handleMouseMove(0, 0); - expect(client._sock.flush).to.not.have.been.called; - }); - - it('should send a pointer event on mouse button presses', function () { - client._handleMouseButton(10, 12, 1, 0x001); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x001); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); - - it('should send a mask of 1 on mousedown', function () { - client._handleMouseButton(10, 12, 1, 0x001); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x001); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); - - it('should send a mask of 0 on mouseup', function () { - client._mouse_buttonMask = 0x001; - client._handleMouseButton(10, 12, 0, 0x001); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x000); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); - - it('should send a pointer event on mouse movement', function () { - client._handleMouseMove(10, 12); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x000); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); - - it('should set the button mask so that future mouse movements use it', function () { - client._handleMouseButton(10, 12, 1, 0x010); - client._handleMouseMove(13, 9); - const pointer_msg = {_sQ: new Uint8Array(12), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x010); - RFB.messages.pointerEvent(pointer_msg, 13, 9, 0x010); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); - }); - - describe('Keyboard Event Handlers', function () { - it('should send a key message on a key press', function () { - client._handleKeyEvent(0x41, 'KeyA', true); - const key_msg = {_sQ: new Uint8Array(8), _sQlen: 0, flush: () => {}}; - RFB.messages.keyEvent(key_msg, 0x41, 1); - expect(client._sock).to.have.sent(key_msg._sQ); - }); - - it('should not send messages in view-only mode', function () { - client._viewOnly = true; - sinon.spy(client._sock, 'flush'); - client._handleKeyEvent('a', 'KeyA', true); - expect(client._sock.flush).to.not.have.been.called; - }); - }); - - describe('WebSocket event handlers', function () { - // message events - it('should do nothing if we receive an empty message and have nothing in the queue', function () { - client._normal_msg = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array([])); - expect(client._normal_msg).to.not.have.been.called; - }); - - it('should handle a message in the connected state as a normal message', function () { - client._normal_msg = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array([1, 2, 3])); - expect(client._normal_msg).to.have.been.calledOnce; - }); - - it('should handle a message in any non-disconnected/failed state like an init message', function () { - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'ProtocolVersion'; - client._init_msg = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array([1, 2, 3])); - expect(client._init_msg).to.have.been.calledOnce; - }); - - it('should process all normal messages directly', function () { - const spy = sinon.spy(); - client.addEventListener("bell", spy); - client._sock._websocket._receive_data(new Uint8Array([0x02, 0x02])); - expect(spy).to.have.been.calledTwice; - }); - - // open events - it('should update the state to ProtocolVersion on open (if the state is "connecting")', function () { - client = new RFB(document.createElement('div'), 'wss://host:8675'); - this.clock.tick(); - client._sock._websocket._open(); - expect(client._rfb_init_state).to.equal('ProtocolVersion'); - }); - - it('should fail if we are not currently ready to connect and we get an "open" event', function () { - sinon.spy(client, "_fail"); - client._rfb_connection_state = 'connected'; - client._sock._websocket._open(); - expect(client._fail).to.have.been.calledOnce; - }); - - // close events - it('should transition to "disconnected" from "disconnecting" on a close event', function () { - const real = client._sock._websocket.close; - client._sock._websocket.close = () => {}; - client.disconnect(); - expect(client._rfb_connection_state).to.equal('disconnecting'); - client._sock._websocket.close = real; - client._sock._websocket.close(); - expect(client._rfb_connection_state).to.equal('disconnected'); - }); - - it('should fail if we get a close event while connecting', function () { - sinon.spy(client, "_fail"); - client._rfb_connection_state = 'connecting'; - client._sock._websocket.close(); - expect(client._fail).to.have.been.calledOnce; - }); - - it('should unregister close event handler', function () { - sinon.spy(client._sock, 'off'); - client.disconnect(); - client._sock._websocket.close(); - expect(client._sock.off).to.have.been.calledWith('close'); - }); - - // error events do nothing - }); - }); -}); diff --git a/kasmweb/tests/test.util.js b/kasmweb/tests/test.util.js deleted file mode 100644 index 201acc8..0000000 --- a/kasmweb/tests/test.util.js +++ /dev/null @@ -1,69 +0,0 @@ -/* eslint-disable no-console */ -const expect = chai.expect; - -import * as Log from '../core/util/logging.js'; - -describe('Utils', function () { - "use strict"; - - describe('logging functions', function () { - beforeEach(function () { - sinon.spy(console, 'log'); - sinon.spy(console, 'debug'); - sinon.spy(console, 'warn'); - sinon.spy(console, 'error'); - sinon.spy(console, 'info'); - }); - - afterEach(function () { - console.log.restore(); - console.debug.restore(); - console.warn.restore(); - console.error.restore(); - console.info.restore(); - Log.init_logging(); - }); - - it('should use noop for levels lower than the min level', function () { - Log.init_logging('warn'); - Log.Debug('hi'); - Log.Info('hello'); - expect(console.log).to.not.have.been.called; - }); - - it('should use console.debug for Debug', function () { - Log.init_logging('debug'); - Log.Debug('dbg'); - expect(console.debug).to.have.been.calledWith('dbg'); - }); - - it('should use console.info for Info', function () { - Log.init_logging('debug'); - Log.Info('inf'); - expect(console.info).to.have.been.calledWith('inf'); - }); - - it('should use console.warn for Warn', function () { - Log.init_logging('warn'); - Log.Warn('wrn'); - expect(console.warn).to.have.been.called; - expect(console.warn).to.have.been.calledWith('wrn'); - }); - - it('should use console.error for Error', function () { - Log.init_logging('error'); - Log.Error('err'); - expect(console.error).to.have.been.called; - expect(console.error).to.have.been.calledWith('err'); - }); - }); - - // TODO(directxman12): test the conf_default and conf_defaults methods - // TODO(directxman12): test decodeUTF8 - // TODO(directxman12): test the event methods (addEvent, removeEvent, stopEvent) - // TODO(directxman12): figure out a good way to test getPosition and getEventPosition - // TODO(directxman12): figure out how to test the browser detection functions properly - // (we can't really test them against the browsers, except for Gecko - // via PhantomJS, the default test driver) -}); -/* eslint-enable no-console */ diff --git a/kasmweb/tests/test.websock.js b/kasmweb/tests/test.websock.js deleted file mode 100644 index 30e19e9..0000000 --- a/kasmweb/tests/test.websock.js +++ /dev/null @@ -1,441 +0,0 @@ -const expect = chai.expect; - -import Websock from '../core/websock.js'; -import FakeWebSocket from './fake.websocket.js'; - -describe('Websock', function () { - "use strict"; - - describe('Queue methods', function () { - let sock; - const RQ_TEMPLATE = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - - beforeEach(function () { - sock = new Websock(); - // skip init - sock._allocate_buffers(); - sock._rQ.set(RQ_TEMPLATE); - sock._rQlen = RQ_TEMPLATE.length; - }); - describe('rQlen', function () { - it('should return the length of the receive queue', function () { - sock.rQi = 0; - - expect(sock.rQlen).to.equal(RQ_TEMPLATE.length); - }); - - it("should return the proper length if we read some from the receive queue", function () { - sock.rQi = 1; - - expect(sock.rQlen).to.equal(RQ_TEMPLATE.length - 1); - }); - }); - - describe('rQpeek8', function () { - it('should peek at the next byte without poping it off the queue', function () { - const bef_len = sock.rQlen; - const peek = sock.rQpeek8(); - expect(sock.rQpeek8()).to.equal(peek); - expect(sock.rQlen).to.equal(bef_len); - }); - }); - - describe('rQshift8()', function () { - it('should pop a single byte from the receive queue', function () { - const peek = sock.rQpeek8(); - const bef_len = sock.rQlen; - expect(sock.rQshift8()).to.equal(peek); - expect(sock.rQlen).to.equal(bef_len - 1); - }); - }); - - describe('rQshift16()', function () { - it('should pop two bytes from the receive queue and return a single number', function () { - const bef_len = sock.rQlen; - const expected = (RQ_TEMPLATE[0] << 8) + RQ_TEMPLATE[1]; - expect(sock.rQshift16()).to.equal(expected); - expect(sock.rQlen).to.equal(bef_len - 2); - }); - }); - - describe('rQshift32()', function () { - it('should pop four bytes from the receive queue and return a single number', function () { - const bef_len = sock.rQlen; - const expected = (RQ_TEMPLATE[0] << 24) + - (RQ_TEMPLATE[1] << 16) + - (RQ_TEMPLATE[2] << 8) + - RQ_TEMPLATE[3]; - expect(sock.rQshift32()).to.equal(expected); - expect(sock.rQlen).to.equal(bef_len - 4); - }); - }); - - describe('rQshiftStr', function () { - it('should shift the given number of bytes off of the receive queue and return a string', function () { - const bef_len = sock.rQlen; - const bef_rQi = sock.rQi; - const shifted = sock.rQshiftStr(3); - expect(shifted).to.be.a('string'); - expect(shifted).to.equal(String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3)))); - expect(sock.rQlen).to.equal(bef_len - 3); - }); - - it('should shift the entire rest of the queue off if no length is given', function () { - sock.rQshiftStr(); - expect(sock.rQlen).to.equal(0); - }); - - it('should be able to handle very large strings', function () { - const BIG_LEN = 500000; - const RQ_BIG = new Uint8Array(BIG_LEN); - let expected = ""; - let letterCode = 'a'.charCodeAt(0); - for (let i = 0; i < BIG_LEN; i++) { - RQ_BIG[i] = letterCode; - expected += String.fromCharCode(letterCode); - - if (letterCode < 'z'.charCodeAt(0)) { - letterCode++; - } else { - letterCode = 'a'.charCodeAt(0); - } - } - sock._rQ.set(RQ_BIG); - sock._rQlen = RQ_BIG.length; - - const shifted = sock.rQshiftStr(); - - expect(shifted).to.be.equal(expected); - expect(sock.rQlen).to.equal(0); - }); - }); - - describe('rQshiftBytes', function () { - it('should shift the given number of bytes of the receive queue and return an array', function () { - const bef_len = sock.rQlen; - const bef_rQi = sock.rQi; - const shifted = sock.rQshiftBytes(3); - expect(shifted).to.be.an.instanceof(Uint8Array); - expect(shifted).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3)); - expect(sock.rQlen).to.equal(bef_len - 3); - }); - - it('should shift the entire rest of the queue off if no length is given', function () { - sock.rQshiftBytes(); - expect(sock.rQlen).to.equal(0); - }); - }); - - describe('rQslice', function () { - beforeEach(function () { - sock.rQi = 0; - }); - - it('should not modify the receive queue', function () { - const bef_len = sock.rQlen; - sock.rQslice(0, 2); - expect(sock.rQlen).to.equal(bef_len); - }); - - it('should return an array containing the given slice of the receive queue', function () { - const sl = sock.rQslice(0, 2); - expect(sl).to.be.an.instanceof(Uint8Array); - expect(sl).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 0, 2)); - }); - - it('should use the rest of the receive queue if no end is given', function () { - const sl = sock.rQslice(1); - expect(sl).to.have.length(RQ_TEMPLATE.length - 1); - expect(sl).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 1)); - }); - - it('should take the current rQi in to account', function () { - sock.rQi = 1; - expect(sock.rQslice(0, 2)).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 1, 2)); - }); - }); - - describe('rQwait', function () { - beforeEach(function () { - sock.rQi = 0; - }); - - it('should return true if there are not enough bytes in the receive queue', function () { - expect(sock.rQwait('hi', RQ_TEMPLATE.length + 1)).to.be.true; - }); - - it('should return false if there are enough bytes in the receive queue', function () { - expect(sock.rQwait('hi', RQ_TEMPLATE.length)).to.be.false; - }); - - it('should return true and reduce rQi by "goback" if there are not enough bytes', function () { - sock.rQi = 5; - expect(sock.rQwait('hi', RQ_TEMPLATE.length, 4)).to.be.true; - expect(sock.rQi).to.equal(1); - }); - - it('should raise an error if we try to go back more than possible', function () { - sock.rQi = 5; - expect(() => sock.rQwait('hi', RQ_TEMPLATE.length, 6)).to.throw(Error); - }); - - it('should not reduce rQi if there are enough bytes', function () { - sock.rQi = 5; - sock.rQwait('hi', 1, 6); - expect(sock.rQi).to.equal(5); - }); - }); - - describe('flush', function () { - beforeEach(function () { - sock._websocket = { - send: sinon.spy() - }; - }); - - it('should actually send on the websocket', function () { - sock._websocket.bufferedAmount = 8; - sock._websocket.readyState = WebSocket.OPEN; - sock._sQ = new Uint8Array([1, 2, 3]); - sock._sQlen = 3; - const encoded = sock._encode_message(); - - sock.flush(); - expect(sock._websocket.send).to.have.been.calledOnce; - expect(sock._websocket.send).to.have.been.calledWith(encoded); - }); - - it('should not call send if we do not have anything queued up', function () { - sock._sQlen = 0; - sock._websocket.bufferedAmount = 8; - - sock.flush(); - - expect(sock._websocket.send).not.to.have.been.called; - }); - }); - - describe('send', function () { - beforeEach(function () { - sock.flush = sinon.spy(); - }); - - it('should add to the send queue', function () { - sock.send([1, 2, 3]); - const sq = sock.sQ; - expect(new Uint8Array(sq.buffer, sock._sQlen - 3, 3)).to.array.equal(new Uint8Array([1, 2, 3])); - }); - - it('should call flush', function () { - sock.send([1, 2, 3]); - expect(sock.flush).to.have.been.calledOnce; - }); - }); - - describe('send_string', function () { - beforeEach(function () { - sock.send = sinon.spy(); - }); - - it('should call send after converting the string to an array', function () { - sock.send_string("\x01\x02\x03"); - expect(sock.send).to.have.been.calledWith([1, 2, 3]); - }); - }); - }); - - describe('lifecycle methods', function () { - let old_WS; - before(function () { - old_WS = WebSocket; - }); - - let sock; - beforeEach(function () { - sock = new Websock(); - // eslint-disable-next-line no-global-assign - WebSocket = sinon.spy(); - WebSocket.OPEN = old_WS.OPEN; - WebSocket.CONNECTING = old_WS.CONNECTING; - WebSocket.CLOSING = old_WS.CLOSING; - WebSocket.CLOSED = old_WS.CLOSED; - - WebSocket.prototype.binaryType = 'arraybuffer'; - }); - - describe('opening', function () { - it('should pick the correct protocols if none are given', function () { - - }); - - it('should open the actual websocket', function () { - sock.open('ws://localhost:8675', 'binary'); - expect(WebSocket).to.have.been.calledWith('ws://localhost:8675', 'binary'); - }); - - // it('should initialize the event handlers')? - }); - - describe('closing', function () { - beforeEach(function () { - sock.open('ws://'); - sock._websocket.close = sinon.spy(); - }); - - it('should close the actual websocket if it is open', function () { - sock._websocket.readyState = WebSocket.OPEN; - sock.close(); - expect(sock._websocket.close).to.have.been.calledOnce; - }); - - it('should close the actual websocket if it is connecting', function () { - sock._websocket.readyState = WebSocket.CONNECTING; - sock.close(); - expect(sock._websocket.close).to.have.been.calledOnce; - }); - - it('should not try to close the actual websocket if closing', function () { - sock._websocket.readyState = WebSocket.CLOSING; - sock.close(); - expect(sock._websocket.close).not.to.have.been.called; - }); - - it('should not try to close the actual websocket if closed', function () { - sock._websocket.readyState = WebSocket.CLOSED; - sock.close(); - expect(sock._websocket.close).not.to.have.been.called; - }); - - it('should reset onmessage to not call _recv_message', function () { - sinon.spy(sock, '_recv_message'); - sock.close(); - sock._websocket.onmessage(null); - try { - expect(sock._recv_message).not.to.have.been.called; - } finally { - sock._recv_message.restore(); - } - }); - }); - - describe('event handlers', function () { - beforeEach(function () { - sock._recv_message = sinon.spy(); - sock.on('open', sinon.spy()); - sock.on('close', sinon.spy()); - sock.on('error', sinon.spy()); - sock.open('ws://'); - }); - - it('should call _recv_message on a message', function () { - sock._websocket.onmessage(null); - expect(sock._recv_message).to.have.been.calledOnce; - }); - - it('should call the open event handler on opening', function () { - sock._websocket.onopen(); - expect(sock._eventHandlers.open).to.have.been.calledOnce; - }); - - it('should call the close event handler on closing', function () { - sock._websocket.onclose(); - expect(sock._eventHandlers.close).to.have.been.calledOnce; - }); - - it('should call the error event handler on error', function () { - sock._websocket.onerror(); - expect(sock._eventHandlers.error).to.have.been.calledOnce; - }); - }); - - after(function () { - // eslint-disable-next-line no-global-assign - WebSocket = old_WS; - }); - }); - - describe('WebSocket Receiving', function () { - let sock; - beforeEach(function () { - sock = new Websock(); - sock._allocate_buffers(); - }); - - it('should support adding binary Uint8Array data to the receive queue', function () { - const msg = { data: new Uint8Array([1, 2, 3]) }; - sock._mode = 'binary'; - sock._recv_message(msg); - expect(sock.rQshiftStr(3)).to.equal('\x01\x02\x03'); - }); - - it('should call the message event handler if present', function () { - sock._eventHandlers.message = sinon.spy(); - const msg = { data: new Uint8Array([1, 2, 3]).buffer }; - sock._mode = 'binary'; - sock._recv_message(msg); - expect(sock._eventHandlers.message).to.have.been.calledOnce; - }); - - it('should not call the message event handler if there is nothing in the receive queue', function () { - sock._eventHandlers.message = sinon.spy(); - const msg = { data: new Uint8Array([]).buffer }; - sock._mode = 'binary'; - sock._recv_message(msg); - expect(sock._eventHandlers.message).not.to.have.been.called; - }); - - it('should compact the receive queue', function () { - // NB(sross): while this is an internal implementation detail, it's important to - // test, otherwise the receive queue could become very large very quickly - sock._rQ = new Uint8Array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0]); - sock._rQlen = 6; - sock.rQi = 6; - sock._rQmax = 3; - const msg = { data: new Uint8Array([1, 2, 3]).buffer }; - sock._mode = 'binary'; - sock._recv_message(msg); - expect(sock._rQlen).to.equal(3); - expect(sock.rQi).to.equal(0); - }); - - it('should automatically resize the receive queue if the incoming message is too large', function () { - sock._rQ = new Uint8Array(20); - sock._rQlen = 0; - sock.rQi = 0; - sock._rQbufferSize = 20; - sock._rQmax = 2; - const msg = { data: new Uint8Array(30).buffer }; - sock._mode = 'binary'; - sock._recv_message(msg); - expect(sock._rQlen).to.equal(30); - expect(sock.rQi).to.equal(0); - expect(sock._rQ.length).to.equal(240); // keep the invariant that rQbufferSize / 8 >= rQlen - }); - }); - - describe('Data encoding', function () { - before(function () { FakeWebSocket.replace(); }); - after(function () { FakeWebSocket.restore(); }); - - describe('as binary data', function () { - let sock; - beforeEach(function () { - sock = new Websock(); - sock.open('ws://', 'binary'); - sock._websocket._open(); - }); - - it('should only send the send queue up to the send queue length', function () { - sock._sQ = new Uint8Array([1, 2, 3, 4, 5]); - sock._sQlen = 3; - const res = sock._encode_message(); - expect(res).to.array.equal(new Uint8Array([1, 2, 3])); - }); - - it('should properly pass the encoded data off to the actual WebSocket', function () { - sock.send([1, 2, 3]); - expect(sock._websocket._get_sent_data()).to.array.equal(new Uint8Array([1, 2, 3])); - }); - }); - }); -}); diff --git a/kasmweb/tests/test.webutil.js b/kasmweb/tests/test.webutil.js deleted file mode 100644 index 2739704..0000000 --- a/kasmweb/tests/test.webutil.js +++ /dev/null @@ -1,184 +0,0 @@ -/* jshint expr: true */ - -const expect = chai.expect; - -import * as WebUtil from '../app/webutil.js'; - -describe('WebUtil', function () { - "use strict"; - - describe('settings', function () { - - describe('localStorage', function () { - let chrome = window.chrome; - before(function () { - chrome = window.chrome; - window.chrome = null; - }); - after(function () { - window.chrome = chrome; - }); - - let origLocalStorage; - beforeEach(function () { - origLocalStorage = Object.getOwnPropertyDescriptor(window, "localStorage"); - if (origLocalStorage === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "localStorage", {value: {}}); - if (window.localStorage.setItem !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.localStorage.setItem = sinon.stub(); - window.localStorage.getItem = sinon.stub(); - window.localStorage.removeItem = sinon.stub(); - - WebUtil.initSettings(); - }); - afterEach(function () { - Object.defineProperty(window, "localStorage", origLocalStorage); - }); - - describe('writeSetting', function () { - it('should save the setting value to local storage', function () { - WebUtil.writeSetting('test', 'value'); - expect(window.localStorage.setItem).to.have.been.calledWithExactly('test', 'value'); - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - }); - - describe('setSetting', function () { - it('should update the setting but not save to local storage', function () { - WebUtil.setSetting('test', 'value'); - expect(window.localStorage.setItem).to.not.have.been.called; - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - }); - - describe('readSetting', function () { - it('should read the setting value from local storage', function () { - localStorage.getItem.returns('value'); - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - - it('should return the default value when not in local storage', function () { - expect(WebUtil.readSetting('test', 'default')).to.equal('default'); - }); - - it('should return the cached value even if local storage changed', function () { - localStorage.getItem.returns('value'); - expect(WebUtil.readSetting('test')).to.equal('value'); - localStorage.getItem.returns('something else'); - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - - it('should cache the value even if it is not initially in local storage', function () { - expect(WebUtil.readSetting('test')).to.be.null; - localStorage.getItem.returns('value'); - expect(WebUtil.readSetting('test')).to.be.null; - }); - - it('should return the default value always if the first read was not in local storage', function () { - expect(WebUtil.readSetting('test', 'default')).to.equal('default'); - localStorage.getItem.returns('value'); - expect(WebUtil.readSetting('test', 'another default')).to.equal('another default'); - }); - - it('should return the last local written value', function () { - localStorage.getItem.returns('value'); - expect(WebUtil.readSetting('test')).to.equal('value'); - WebUtil.writeSetting('test', 'something else'); - expect(WebUtil.readSetting('test')).to.equal('something else'); - }); - }); - - // this doesn't appear to be used anywhere - describe('eraseSetting', function () { - it('should remove the setting from local storage', function () { - WebUtil.eraseSetting('test'); - expect(window.localStorage.removeItem).to.have.been.calledWithExactly('test'); - }); - }); - }); - - describe('chrome.storage', function () { - let chrome = window.chrome; - let settings = {}; - before(function () { - chrome = window.chrome; - window.chrome = { - storage: { - sync: { - get(cb) { cb(settings); }, - set() {}, - remove() {} - } - } - }; - }); - after(function () { - window.chrome = chrome; - }); - - const csSandbox = sinon.createSandbox(); - - beforeEach(function () { - settings = {}; - csSandbox.spy(window.chrome.storage.sync, 'set'); - csSandbox.spy(window.chrome.storage.sync, 'remove'); - WebUtil.initSettings(); - }); - afterEach(function () { - csSandbox.restore(); - }); - - describe('writeSetting', function () { - it('should save the setting value to chrome storage', function () { - WebUtil.writeSetting('test', 'value'); - expect(window.chrome.storage.sync.set).to.have.been.calledWithExactly(sinon.match({ test: 'value' })); - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - }); - - describe('setSetting', function () { - it('should update the setting but not save to chrome storage', function () { - WebUtil.setSetting('test', 'value'); - expect(window.chrome.storage.sync.set).to.not.have.been.called; - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - }); - - describe('readSetting', function () { - it('should read the setting value from chrome storage', function () { - settings.test = 'value'; - expect(WebUtil.readSetting('test')).to.equal('value'); - }); - - it('should return the default value when not in chrome storage', function () { - expect(WebUtil.readSetting('test', 'default')).to.equal('default'); - }); - - it('should return the last local written value', function () { - settings.test = 'value'; - expect(WebUtil.readSetting('test')).to.equal('value'); - WebUtil.writeSetting('test', 'something else'); - expect(WebUtil.readSetting('test')).to.equal('something else'); - }); - }); - - // this doesn't appear to be used anywhere - describe('eraseSetting', function () { - it('should remove the setting from chrome storage', function () { - WebUtil.eraseSetting('test'); - expect(window.chrome.storage.sync.remove).to.have.been.calledWithExactly('test'); - }); - }); - }); - }); -}); diff --git a/kasmweb/tests/vnc_playback.html b/kasmweb/tests/vnc_playback.html deleted file mode 100644 index 353f03d..0000000 --- a/kasmweb/tests/vnc_playback.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - VNC Playback - - - - - - - - - - - Iterations:   - Perftest:  - Realtime:   - -   - -

- - Results:
- - -

- -
-
- - -
Loading
-
-
- - - - \n`; - } - } else { - // Otherwise detect if it's a modern browser and select - // variant accordingly - new_script += `\ - \n\ - \n`; - - // Original, ES6 modules - new_script += ' \n'; - } - - contents = contents.slice(0, start_ind) + `${new_script}\n` + contents.slice(end_ind); - - return contents; - }) - .then((contents) => { - console.log(`Writing ${out_html_path}`); - return writeFile(out_html_path, contents); - }); -} - -function make_lib_files(import_format, source_maps, with_app_dir, only_legacy) { - if (!import_format) { - throw new Error("you must specify an import format to generate compiled noVNC libraries"); - } else if (!SUPPORTED_FORMATS.has(import_format)) { - throw new Error(`unsupported output format "${import_format}" for import/export -- only ${Array.from(SUPPORTED_FORMATS)} are supported`); - } - - // NB: we need to make a copy of babel_opts, since babel sets some defaults on it - const babel_opts = () => ({ - plugins: [`transform-es2015-modules-${import_format}`], - presets: ['es2015'], - ast: false, - sourceMaps: source_maps, - }); - - // No point in duplicate files without the app, so force only converted files - if (!with_app_dir) { - only_legacy = true; - } - - let in_path; - let out_path_base; - if (with_app_dir) { - out_path_base = paths.out_dir_base; - in_path = paths.main; - } else { - out_path_base = paths.lib_dir_base; - } - const legacy_path_base = only_legacy ? out_path_base : path.join(out_path_base, 'legacy'); - - fse.ensureDirSync(out_path_base); - - const helpers = require('./use_require_helpers'); - const helper = helpers[import_format]; - - const outFiles = []; - - const handleDir = (js_only, vendor_rewrite, in_path_base, filename) => Promise.resolve() - .then(() => { - if (no_copy_files.has(filename)) return; - - const out_path = path.join(out_path_base, path.relative(in_path_base, filename)); - const legacy_path = path.join(legacy_path_base, path.relative(in_path_base, filename)); - - if (path.extname(filename) !== '.js') { - if (!js_only) { - console.log(`Writing ${out_path}`); - return copy(filename, out_path); - } - return; // skip non-javascript files - } - - return Promise.resolve() - .then(() => { - if (only_legacy && !no_transform_files.has(filename)) { - return; - } - return ensureDir(path.dirname(out_path)) - .then(() => { - console.log(`Writing ${out_path}`); - return copy(filename, out_path); - }); - }) - .then(() => ensureDir(path.dirname(legacy_path))) - .then(() => { - if (no_transform_files.has(filename)) { - return; - } - - const opts = babel_opts(); - if (helper && helpers.optionsOverride) { - helper.optionsOverride(opts); - } - // Adjust for the fact that we move the core files relative - // to the vendor directory - if (vendor_rewrite) { - opts.plugins.push(["import-redirect", - {"root": legacy_path_base, - "redirect": { "vendor/(.+)": "./vendor/$1"}}]); - } - - return babelTransformFile(filename, opts) - .then((res) => { - console.log(`Writing ${legacy_path}`); - const {map} = res; - let {code} = res; - if (source_maps === true) { - // append URL for external source map - code += `\n//# sourceMappingURL=${path.basename(legacy_path)}.map\n`; - } - outFiles.push(`${legacy_path}`); - return writeFile(legacy_path, code) - .then(() => { - if (source_maps === true || source_maps === 'both') { - console.log(` and ${legacy_path}.map`); - outFiles.push(`${legacy_path}.map`); - return writeFile(`${legacy_path}.map`, JSON.stringify(map)); - } - }); - }); - }); - }); - - if (with_app_dir && helper && helper.noCopyOverride) { - helper.noCopyOverride(paths, no_copy_files); - } - - Promise.resolve() - .then(() => { - const handler = handleDir.bind(null, true, false, in_path || paths.main); - const filter = (filename, stats) => !no_copy_files.has(filename); - return walkDir(paths.vendor, handler, filter); - }) - .then(() => { - const handler = handleDir.bind(null, true, !in_path, in_path || paths.core); - const filter = (filename, stats) => !no_copy_files.has(filename); - return walkDir(paths.core, handler, filter); - }) - .then(() => { - if (!with_app_dir) return; - const handler = handleDir.bind(null, false, false, in_path); - const filter = (filename, stats) => !no_copy_files.has(filename); - return walkDir(paths.app, handler, filter); - }) - .then(() => { - if (!with_app_dir) return; - - if (!helper || !helper.appWriter) { - throw new Error(`Unable to generate app for the ${import_format} format!`); - } - - const out_app_path = path.join(legacy_path_base, 'app.js'); - console.log(`Writing ${out_app_path}`); - return helper.appWriter(out_path_base, legacy_path_base, out_app_path) - .then((extra_scripts) => { - const rel_app_path = path.relative(out_path_base, out_app_path); - const legacy_scripts = extra_scripts.concat([rel_app_path]); - transform_html(legacy_scripts, only_legacy); - }) - .then(() => { - if (!helper.removeModules) return; - console.log(`Cleaning up temporary files...`); - return Promise.all(outFiles.map((filepath) => { - unlink(filepath) - .then(() => { - // Try to clean up any empty directories if this - // was the last file in there - const rmdir_r = dir => - rmdir(dir) - .then(() => rmdir_r(path.dirname(dir))) - .catch(() => { - // Assume the error was ENOTEMPTY and ignore it - }); - return rmdir_r(path.dirname(filepath)); - }); - })); - }); - }) - .catch((err) => { - console.error(`Failure converting modules: ${err}`); - process.exit(1); - }); -} - -if (program.clean) { - console.log(`Removing ${paths.lib_dir_base}`); - fse.removeSync(paths.lib_dir_base); - - console.log(`Removing ${paths.out_dir_base}`); - fse.removeSync(paths.out_dir_base); -} - -make_lib_files(program.as, program.withSourceMaps, program.withApp, program.onlyLegacy); diff --git a/kasmweb/utils/use_require_helpers.js b/kasmweb/utils/use_require_helpers.js deleted file mode 100644 index a4f99c7..0000000 --- a/kasmweb/utils/use_require_helpers.js +++ /dev/null @@ -1,76 +0,0 @@ -// writes helpers require for vnc.html (they should output app.js) -const fs = require('fs'); -const path = require('path'); - -// util.promisify requires Node.js 8.x, so we have our own -function promisify(original) { - return function promise_wrap() { - const args = Array.prototype.slice.call(arguments); - return new Promise((resolve, reject) => { - original.apply(this, args.concat((err, value) => { - if (err) return reject(err); - resolve(value); - })); - }); - }; -} - -const writeFile = promisify(fs.writeFile); - -module.exports = { - 'amd': { - appWriter: (base_out_path, script_base_path, out_path) => { - // setup for requirejs - const ui_path = path.relative(base_out_path, - path.join(script_base_path, 'app', 'ui')); - return writeFile(out_path, `requirejs(["${ui_path}"], (ui) => {});`) - .then(() => { - console.log(`Please place RequireJS in ${path.join(script_base_path, 'require.js')}`); - const require_path = path.relative(base_out_path, - path.join(script_base_path, 'require.js')); - return [ require_path ]; - }); - }, - noCopyOverride: () => {}, - }, - 'commonjs': { - optionsOverride: (opts) => { - // CommonJS supports properly shifting the default export to work as normal - opts.plugins.unshift("add-module-exports"); - }, - appWriter: (base_out_path, script_base_path, out_path) => { - const browserify = require('browserify'); - const b = browserify(path.join(script_base_path, 'app/ui.js'), {}); - return promisify(b.bundle).call(b) - .then(buf => writeFile(out_path, buf)) - .then(() => []); - }, - noCopyOverride: () => {}, - removeModules: true, - }, - 'systemjs': { - appWriter: (base_out_path, script_base_path, out_path) => { - const ui_path = path.relative(base_out_path, - path.join(script_base_path, 'app', 'ui.js')); - return writeFile(out_path, `SystemJS.import("${ui_path}");`) - .then(() => { - console.log(`Please place SystemJS in ${path.join(script_base_path, 'system-production.js')}`); - // FIXME: Should probably be in the legacy directory - const promise_path = path.relative(base_out_path, - path.join(base_out_path, 'vendor', 'promise.js')); - const systemjs_path = path.relative(base_out_path, - path.join(script_base_path, 'system-production.js')); - return [ promise_path, systemjs_path ]; - }); - }, - noCopyOverride: (paths, no_copy_files) => { - no_copy_files.delete(path.join(paths.vendor, 'promise.js')); - }, - }, - 'umd': { - optionsOverride: (opts) => { - // umd supports properly shifting the default export to work as normal - opts.plugins.unshift("add-module-exports"); - }, - }, -}; diff --git a/kasmweb/vendor/browser-es-module-loader/README.md b/kasmweb/vendor/browser-es-module-loader/README.md deleted file mode 100644 index c26867f..0000000 --- a/kasmweb/vendor/browser-es-module-loader/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Custom Browser ES Module Loader -=============================== - -This is a module loader using babel and the ES Module Loader polyfill. -It's based heavily on -https://github.com/ModuleLoader/browser-es-module-loader, but uses -WebWorkers to compile the modules in the background. - -To generate, run `rollup -c` in this directory, and then run `browserify -src/babel-worker.js > dist/babel-worker.js`. - -LICENSE -------- - -MIT diff --git a/kasmweb/vendor/browser-es-module-loader/dist/babel-worker.js b/kasmweb/vendor/browser-es-module-loader/dist/babel-worker.js deleted file mode 100644 index 3f9d7e0..0000000 --- a/kasmweb/vendor/browser-es-module-loader/dist/babel-worker.js +++ /dev/null @@ -1,55799 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<]/g; -}; - -},{}],2:[function(require,module,exports){ -'use strict'; - -function assembleStyles () { - var styles = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39] - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49] - } - }; - - // fix humans - styles.colors.grey = styles.colors.gray; - - Object.keys(styles).forEach(function (groupName) { - var group = styles[groupName]; - - Object.keys(group).forEach(function (styleName) { - var style = group[styleName]; - - styles[styleName] = group[styleName] = { - open: '\u001b[' + style[0] + 'm', - close: '\u001b[' + style[1] + 'm' - }; - }); - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - }); - - return styles; -} - -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - -},{}],3:[function(require,module,exports){ -(function (global){ -'use strict'; - -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); -} - -// based on node assert, original notice: - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); -} -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; - } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; - -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; - - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; - - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } - } - - memos.actual.push(actual); - memos.expected.push(expected); - - return objEquiv(actual, expected, strict, memos); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } -} - - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } - - try { - if (actual instanceof expected) { - return true; - } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } - - if (Error.isPrototypeOf(expected)) { - return false; - } - - return expected.call({}, actual) === true; -} - -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } - - if (typeof expected === 'string') { - message = expected; - expected = null; - } - - actual = _tryBlock(block); - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; - - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; - -assert.ifError = function(err) { if (err) throw err; }; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":560}],4:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (rawLines, lineNumber, colNumber) { - var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - - colNumber = Math.max(colNumber, 0); - - var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor; - var chalk = _chalk2.default; - if (opts.forceColor) { - chalk = new _chalk2.default.constructor({ enabled: true }); - } - var maybeHighlight = function maybeHighlight(chalkFn, string) { - return highlighted ? chalkFn(string) : string; - }; - var defs = getDefs(chalk); - if (highlighted) rawLines = highlight(defs, rawLines); - - var linesAbove = opts.linesAbove || 2; - var linesBelow = opts.linesBelow || 3; - - var lines = rawLines.split(NEWLINE); - var start = Math.max(lineNumber - (linesAbove + 1), 0); - var end = Math.min(lines.length, lineNumber + linesBelow); - - if (!lineNumber && !colNumber) { - start = 0; - end = lines.length; - } - - var numberMaxWidth = String(end).length; - - var frame = lines.slice(start, end).map(function (line, index) { - var number = start + 1 + index; - var paddedNumber = (" " + number).slice(-numberMaxWidth); - var gutter = " " + paddedNumber + " | "; - if (number === lineNumber) { - var markerLine = ""; - if (colNumber) { - var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join(""); - } - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); - } else { - return " " + maybeHighlight(defs.gutter, gutter) + line; - } - }).join("\n"); - - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; - } -}; - -var _jsTokens = require("js-tokens"); - -var _jsTokens2 = _interopRequireDefault(_jsTokens); - -var _esutils = require("esutils"); - -var _esutils2 = _interopRequireDefault(_esutils); - -var _chalk = require("chalk"); - -var _chalk2 = _interopRequireDefault(_chalk); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getDefs(chalk) { - return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, - - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold, - gutter: chalk.grey, - marker: chalk.red.bold - }; -} - -var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - -var JSX_TAG = /^[a-z][\w-]*$/i; - -var BRACKET = /^[()\[\]{}]$/; - -function getTokenType(match) { - var _match$slice = match.slice(-2), - offset = _match$slice[0], - text = _match$slice[1]; - - var token = (0, _jsTokens.matchToToken)(match); - - if (token.type === "name") { - if (_esutils2.default.keyword.isReservedWordES6(token.value)) { - return "keyword"; - } - - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " 1 && arguments[1] !== undefined ? arguments[1] : {}; - - opts.filename = filename; - return transform(_fs2.default.readFileSync(filename, "utf8"), opts); -} -},{"../../package":32,"../helpers/resolve-plugin":12,"../helpers/resolve-preset":13,"../tools/build-external-helpers":16,"../transformation/file":17,"../transformation/file/options/config":21,"../transformation/file/options/option-manager":23,"../transformation/pipeline":28,"../util":31,"babel-messages":61,"babel-template":114,"babel-traverse":118,"babel-types":151,"fs":159}],7:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = getPossiblePluginNames; -function getPossiblePluginNames(pluginName) { - return ["babel-plugin-" + pluginName, pluginName]; -} -module.exports = exports["default"]; -},{}],8:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = getPossiblePresetNames; -function getPossiblePresetNames(presetName) { - var possibleNames = ["babel-preset-" + presetName, presetName]; - - var matches = presetName.match(/^(@[^/]+)\/(.+)$/); - if (matches) { - var orgName = matches[1], - presetPath = matches[2]; - - possibleNames.push(orgName + "/babel-preset-" + presetPath); - } - - return possibleNames; -} -module.exports = exports["default"]; -},{}],9:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (dest, src) { - if (!dest || !src) return; - - return (0, _mergeWith2.default)(dest, src, function (a, b) { - if (b && Array.isArray(a)) { - var newArray = b.slice(0); - - for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var item = _ref; - - if (newArray.indexOf(item) < 0) { - newArray.push(item); - } - } - - return newArray; - } - }); -}; - -var _mergeWith = require("lodash/mergeWith"); - -var _mergeWith2 = _interopRequireDefault(_mergeWith); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"lodash/mergeWith":502}],10:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (ast, comments, tokens) { - if (ast) { - if (ast.type === "Program") { - return t.file(ast, comments || [], tokens || []); - } else if (ast.type === "File") { - return ast; - } - } - - throw new Error("Not a valid ast?"); -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":151}],11:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = resolveFromPossibleNames; - -var _resolve = require("./resolve"); - -var _resolve2 = _interopRequireDefault(_resolve); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function resolveFromPossibleNames(possibleNames, dirname) { - return possibleNames.reduce(function (accum, curr) { - return accum || (0, _resolve2.default)(curr, dirname); - }, null); -} -module.exports = exports["default"]; -},{"./resolve":14}],12:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; -exports.default = resolvePlugin; - -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); - -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); - -var _getPossiblePluginNames = require("./get-possible-plugin-names"); - -var _getPossiblePluginNames2 = _interopRequireDefault(_getPossiblePluginNames); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function resolvePlugin(pluginName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); - - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePluginNames2.default)(pluginName), dirname); -} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-plugin-names":7,"./resolve-from-possible-names":11,"_process":525}],13:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; -exports.default = resolvePreset; - -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); - -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); - -var _getPossiblePresetNames = require("./get-possible-preset-names"); - -var _getPossiblePresetNames2 = _interopRequireDefault(_getPossiblePresetNames); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function resolvePreset(presetName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); - - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePresetNames2.default)(presetName), dirname); -} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-preset-names":8,"./resolve-from-possible-names":11,"_process":525}],14:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -exports.default = function (loc) { - var relative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); - - if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null; - - var relativeMod = relativeModules[relative]; - - if (!relativeMod) { - relativeMod = new _module2.default(); - - var filename = _path2.default.join(relative, ".babelrc"); - relativeMod.id = filename; - relativeMod.filename = filename; - - relativeMod.paths = _module2.default._nodeModulePaths(relative); - relativeModules[relative] = relativeMod; - } - - try { - return _module2.default._resolveFilename(loc, relativeMod); - } catch (err) { - return null; - } -}; - -var _module = require("module"); - -var _module2 = _interopRequireDefault(_module); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var relativeModules = {}; - -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"_process":525,"babel-runtime/helpers/typeof":113,"module":159,"path":522}],15:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Store = function (_Map) { - (0, _inherits3.default)(Store, _Map); - - function Store() { - (0, _classCallCheck3.default)(this, Store); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this)); - - _this.dynamicData = {}; - return _this; - } - - Store.prototype.setDynamic = function setDynamic(key, fn) { - this.dynamicData[key] = fn; - }; - - Store.prototype.get = function get(key) { - if (this.has(key)) { - return _Map.prototype.get.call(this, key); - } else { - if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) { - var val = this.dynamicData[key](); - this.set(key, val); - return val; - } - } - }; - - return Store; -}(_map2.default); - -exports.default = Store; -module.exports = exports["default"]; -},{"babel-runtime/core-js/map":97,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112}],16:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (whitelist) { - var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global"; - - var namespace = t.identifier("babelHelpers"); - - var builder = function builder(body) { - return buildHelpers(body, namespace, whitelist); - }; - - var tree = void 0; - - var build = { - global: buildGlobal, - umd: buildUmd, - var: buildVar - }[outputType]; - - if (build) { - tree = build(namespace, builder); - } else { - throw new Error(messages.get("unsupportedOutputType", outputType)); - } - - return (0, _babelGenerator2.default)(tree).code; -}; - -var _babelHelpers = require("babel-helpers"); - -var helpers = _interopRequireWildcard(_babelHelpers); - -var _babelGenerator = require("babel-generator"); - -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var buildUmdWrapper = (0, _babelTemplate2.default)("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n"); - -function buildGlobal(namespace, builder) { - var body = []; - var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); - var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); - - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))])); - - builder(body); - - return tree; -} - -function buildUmd(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))])); - - builder(body); - - return t.program([buildUmdWrapper({ - FACTORY_PARAMETERS: t.identifier("global"), - BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])), - COMMON_ARGUMENTS: t.identifier("exports"), - AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), - FACTORY_BODY: body, - UMD_ROOT: t.identifier("this") - })]); -} - -function buildVar(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))])); - builder(body); - body.push(t.expressionStatement(namespace)); - return t.program(body); -} - -function buildHelpers(body, namespace, whitelist) { - helpers.list.forEach(function (name) { - if (whitelist && whitelist.indexOf(name) < 0) return; - - var key = t.identifier(name); - body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name)))); - }); -} -module.exports = exports["default"]; -},{"babel-generator":44,"babel-helpers":60,"babel-messages":61,"babel-template":114,"babel-types":151}],17:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; -exports.File = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _babelHelpers = require("babel-helpers"); - -var _babelHelpers2 = _interopRequireDefault(_babelHelpers); - -var _metadata = require("./metadata"); - -var metadataVisitor = _interopRequireWildcard(_metadata); - -var _convertSourceMap = require("convert-source-map"); - -var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap); - -var _optionManager = require("./options/option-manager"); - -var _optionManager2 = _interopRequireDefault(_optionManager); - -var _pluginPass = require("../plugin-pass"); - -var _pluginPass2 = _interopRequireDefault(_pluginPass); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _sourceMap = require("source-map"); - -var _sourceMap2 = _interopRequireDefault(_sourceMap); - -var _babelGenerator = require("babel-generator"); - -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); - -var _babelCodeFrame = require("babel-code-frame"); - -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); - -var _defaults = require("lodash/defaults"); - -var _defaults2 = _interopRequireDefault(_defaults); - -var _logger = require("./logger"); - -var _logger2 = _interopRequireDefault(_logger); - -var _store = require("../../store"); - -var _store2 = _interopRequireDefault(_store); - -var _babylon = require("babylon"); - -var _util = require("../../util"); - -var util = _interopRequireWildcard(_util); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _resolve = require("../../helpers/resolve"); - -var _resolve2 = _interopRequireDefault(_resolve); - -var _blockHoist = require("../internal-plugins/block-hoist"); - -var _blockHoist2 = _interopRequireDefault(_blockHoist); - -var _shadowFunctions = require("../internal-plugins/shadow-functions"); - -var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var shebangRegex = /^#!.*/; - -var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]]; - -var errorVisitor = { - enter: function enter(path, state) { - var loc = path.node.loc; - if (loc) { - state.loc = loc; - path.stop(); - } - } -}; - -var File = function (_Store) { - (0, _inherits3.default)(File, _Store); - - function File() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var pipeline = arguments[1]; - (0, _classCallCheck3.default)(this, File); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.pipeline = pipeline; - - _this.log = new _logger2.default(_this, opts.filename || "unknown"); - _this.opts = _this.initOptions(opts); - - _this.parserOpts = { - sourceType: _this.opts.sourceType, - sourceFileName: _this.opts.filename, - plugins: [] - }; - - _this.pluginVisitors = []; - _this.pluginPasses = []; - - _this.buildPluginsForOptions(_this.opts); - - if (_this.opts.passPerPreset) { - _this.perPresetOpts = []; - _this.opts.presets.forEach(function (presetOpts) { - var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_this.opts), presetOpts); - _this.perPresetOpts.push(perPresetOpts); - _this.buildPluginsForOptions(perPresetOpts); - }); - } - - _this.metadata = { - usedHelpers: [], - marked: [], - modules: { - imports: [], - exports: { - exported: [], - specifiers: [] - } - } - }; - - _this.dynamicImportTypes = {}; - _this.dynamicImportIds = {}; - _this.dynamicImports = []; - _this.declarations = {}; - _this.usedHelpers = {}; - - _this.path = null; - _this.ast = {}; - - _this.code = ""; - _this.shebang = ""; - - _this.hub = new _babelTraverse.Hub(_this); - return _this; - } - - File.prototype.getMetadata = function getMetadata() { - var has = false; - for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var node = _ref; - - if (t.isModuleDeclaration(node)) { - has = true; - break; - } - } - if (has) { - this.path.traverse(metadataVisitor, this); - } - }; - - File.prototype.initOptions = function initOptions(opts) { - opts = new _optionManager2.default(this.log, this.pipeline).init(opts); - - if (opts.inputSourceMap) { - opts.sourceMaps = true; - } - - if (opts.moduleId) { - opts.moduleIds = true; - } - - opts.basename = _path2.default.basename(opts.filename, _path2.default.extname(opts.filename)); - - opts.ignore = util.arrayify(opts.ignore, util.regexify); - - if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); - - (0, _defaults2.default)(opts, { - moduleRoot: opts.sourceRoot - }); - - (0, _defaults2.default)(opts, { - sourceRoot: opts.moduleRoot - }); - - (0, _defaults2.default)(opts, { - filenameRelative: opts.filename - }); - - var basenameRelative = _path2.default.basename(opts.filenameRelative); - - (0, _defaults2.default)(opts, { - sourceFileName: basenameRelative, - sourceMapTarget: basenameRelative - }); - - return opts; - }; - - File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) { - if (!Array.isArray(opts.plugins)) { - return; - } - - var plugins = opts.plugins.concat(INTERNAL_PLUGINS); - var currentPluginVisitors = []; - var currentPluginPasses = []; - - for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var ref = _ref2; - var plugin = ref[0], - pluginOpts = ref[1]; - - - currentPluginVisitors.push(plugin.visitor); - currentPluginPasses.push(new _pluginPass2.default(this, plugin, pluginOpts)); - - if (plugin.manipulateOptions) { - plugin.manipulateOptions(opts, this.parserOpts, this); - } - } - - this.pluginVisitors.push(currentPluginVisitors); - this.pluginPasses.push(currentPluginPasses); - }; - - File.prototype.getModuleName = function getModuleName() { - var opts = this.opts; - if (!opts.moduleIds) { - return null; - } - - if (opts.moduleId != null && !opts.getModuleId) { - return opts.moduleId; - } - - var filenameRelative = opts.filenameRelative; - var moduleName = ""; - - if (opts.moduleRoot != null) { - moduleName = opts.moduleRoot + "/"; - } - - if (!opts.filenameRelative) { - return moduleName + opts.filename.replace(/^\//, ""); - } - - if (opts.sourceRoot != null) { - var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); - filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); - } - - filenameRelative = filenameRelative.replace(/\.(\w*?)$/, ""); - - moduleName += filenameRelative; - - moduleName = moduleName.replace(/\\/g, "/"); - - if (opts.getModuleId) { - return opts.getModuleId(moduleName) || moduleName; - } else { - return moduleName; - } - }; - - File.prototype.resolveModuleSource = function resolveModuleSource(source) { - var resolveModuleSource = this.opts.resolveModuleSource; - if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); - return source; - }; - - File.prototype.addImport = function addImport(source, imported) { - var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : imported; - - var alias = source + ":" + imported; - var id = this.dynamicImportIds[alias]; - - if (!id) { - source = this.resolveModuleSource(source); - id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name); - - var specifiers = []; - - if (imported === "*") { - specifiers.push(t.importNamespaceSpecifier(id)); - } else if (imported === "default") { - specifiers.push(t.importDefaultSpecifier(id)); - } else { - specifiers.push(t.importSpecifier(id, t.identifier(imported))); - } - - var declar = t.importDeclaration(specifiers, t.stringLiteral(source)); - declar._blockHoist = 3; - - this.path.unshiftContainer("body", declar); - } - - return id; - }; - - File.prototype.addHelper = function addHelper(name) { - var declar = this.declarations[name]; - if (declar) return declar; - - if (!this.usedHelpers[name]) { - this.metadata.usedHelpers.push(name); - this.usedHelpers[name] = true; - } - - var generator = this.get("helperGenerator"); - var runtime = this.get("helpersNamespace"); - if (generator) { - var res = generator(name); - if (res) return res; - } else if (runtime) { - return t.memberExpression(runtime, t.identifier(name)); - } - - var ref = (0, _babelHelpers2.default)(name); - var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); - - if (t.isFunctionExpression(ref) && !ref.id) { - ref.body._compact = true; - ref._generated = true; - ref.id = uid; - ref.type = "FunctionDeclaration"; - this.path.unshiftContainer("body", ref); - } else { - ref._compact = true; - this.scope.push({ - id: uid, - init: ref, - unique: true - }); - } - - return uid; - }; - - File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) { - var stringIds = raw.elements.map(function (string) { - return string.value; - }); - var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(","); - - var declar = this.declarations[name]; - if (declar) return declar; - - var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); - - var helperId = this.addHelper(helperName); - var init = t.callExpression(helperId, [strings, raw]); - init._compact = true; - this.scope.push({ - id: uid, - init: init, - _blockHoist: 1.9 }); - return uid; - }; - - File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) { - var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError; - - var loc = node && (node.loc || node._loc); - - var err = new Error(msg); - - if (loc) { - err.loc = loc.start; - } else { - (0, _babelTraverse2.default)(node, errorVisitor, this.scope, err); - - err.message += " (This is an error on an internal node. Probably an internal error"; - - if (err.loc) { - err.message += ". Location has been estimated."; - } - - err.message += ")"; - } - - return err; - }; - - File.prototype.mergeSourceMap = function mergeSourceMap(map) { - var inputMap = this.opts.inputSourceMap; - - if (inputMap) { - var inputMapConsumer = new _sourceMap2.default.SourceMapConsumer(inputMap); - var outputMapConsumer = new _sourceMap2.default.SourceMapConsumer(map); - - var mergedGenerator = new _sourceMap2.default.SourceMapGenerator({ - file: inputMapConsumer.file, - sourceRoot: inputMapConsumer.sourceRoot - }); - - var source = outputMapConsumer.sources[0]; - - inputMapConsumer.eachMapping(function (mapping) { - var generatedPosition = outputMapConsumer.generatedPositionFor({ - line: mapping.generatedLine, - column: mapping.generatedColumn, - source: source - }); - if (generatedPosition.column != null) { - mergedGenerator.addMapping({ - source: mapping.source, - - original: mapping.source == null ? null : { - line: mapping.originalLine, - column: mapping.originalColumn - }, - - generated: generatedPosition - }); - } - }); - - var mergedMap = mergedGenerator.toJSON(); - inputMap.mappings = mergedMap.mappings; - return inputMap; - } else { - return map; - } - }; - - File.prototype.parse = function parse(code) { - var parseCode = _babylon.parse; - var parserOpts = this.opts.parserOpts; - - if (parserOpts) { - parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts); - - if (parserOpts.parser) { - if (typeof parserOpts.parser === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var parser = (0, _resolve2.default)(parserOpts.parser, dirname); - if (parser) { - parseCode = require(parser).parse; - } else { - throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method " + ("relative to directory " + dirname)); - } - } else { - parseCode = parserOpts.parser; - } - - parserOpts.parser = { - parse: function parse(source) { - return (0, _babylon.parse)(source, parserOpts); - } - }; - } - } - - this.log.debug("Parse start"); - var ast = parseCode(code, parserOpts || this.parserOpts); - this.log.debug("Parse stop"); - return ast; - }; - - File.prototype._addAst = function _addAst(ast) { - this.path = _babelTraverse.NodePath.get({ - hub: this.hub, - parentPath: null, - parent: ast, - container: ast, - key: "program" - }).setContext(); - this.scope = this.path.scope; - this.ast = ast; - this.getMetadata(); - }; - - File.prototype.addAst = function addAst(ast) { - this.log.debug("Start set AST"); - this._addAst(ast); - this.log.debug("End set AST"); - }; - - File.prototype.transform = function transform() { - for (var i = 0; i < this.pluginPasses.length; i++) { - var pluginPasses = this.pluginPasses[i]; - this.call("pre", pluginPasses); - this.log.debug("Start transform traverse"); - - var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); - (0, _babelTraverse2.default)(this.ast, visitor, this.scope); - - this.log.debug("End transform traverse"); - this.call("post", pluginPasses); - } - - return this.generate(); - }; - - File.prototype.wrap = function wrap(code, callback) { - code = code + ""; - - try { - if (this.shouldIgnore()) { - return this.makeResult({ code: code, ignored: true }); - } else { - return callback(); - } - } catch (err) { - if (err._babel) { - throw err; - } else { - err._babel = true; - } - - var message = err.message = this.opts.filename + ": " + err.message; - - var loc = err.loc; - if (loc) { - err.codeFrame = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts); - message += "\n" + err.codeFrame; - } - - if (process.browser) { - err.message = message; - } - - if (err.stack) { - var newStack = err.stack.replace(err.message, message); - err.stack = newStack; - } - - throw err; - } - }; - - File.prototype.addCode = function addCode(code) { - code = (code || "") + ""; - code = this.parseInputSourceMap(code); - this.code = code; - }; - - File.prototype.parseCode = function parseCode() { - this.parseShebang(); - var ast = this.parse(this.code); - this.addAst(ast); - }; - - File.prototype.shouldIgnore = function shouldIgnore() { - var opts = this.opts; - return util.shouldIgnore(opts.filename, opts.ignore, opts.only); - }; - - File.prototype.call = function call(key, pluginPasses) { - for (var _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var pass = _ref3; - - var plugin = pass.plugin; - var fn = plugin[key]; - if (fn) fn.call(pass, this); - } - }; - - File.prototype.parseInputSourceMap = function parseInputSourceMap(code) { - var opts = this.opts; - - if (opts.inputSourceMap !== false) { - var inputMap = _convertSourceMap2.default.fromSource(code); - if (inputMap) { - opts.inputSourceMap = inputMap.toObject(); - code = _convertSourceMap2.default.removeComments(code); - } - } - - return code; - }; - - File.prototype.parseShebang = function parseShebang() { - var shebangMatch = shebangRegex.exec(this.code); - if (shebangMatch) { - this.shebang = shebangMatch[0]; - this.code = this.code.replace(shebangRegex, ""); - } - }; - - File.prototype.makeResult = function makeResult(_ref4) { - var code = _ref4.code, - map = _ref4.map, - ast = _ref4.ast, - ignored = _ref4.ignored; - - var result = { - metadata: null, - options: this.opts, - ignored: !!ignored, - code: null, - ast: null, - map: map || null - }; - - if (this.opts.code) { - result.code = code; - } - - if (this.opts.ast) { - result.ast = ast; - } - - if (this.opts.metadata) { - result.metadata = this.metadata; - } - - return result; - }; - - File.prototype.generate = function generate() { - var opts = this.opts; - var ast = this.ast; - - var result = { ast: ast }; - if (!opts.code) return this.makeResult(result); - - var gen = _babelGenerator2.default; - if (opts.generatorOpts.generator) { - gen = opts.generatorOpts.generator; - - if (typeof gen === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var generator = (0, _resolve2.default)(gen, dirname); - if (generator) { - gen = require(generator).print; - } else { - throw new Error("Couldn't find generator " + gen + " with \"print\" method relative " + ("to directory " + dirname)); - } - } - } - - this.log.debug("Generation start"); - - var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code); - result.code = _result.code; - result.map = _result.map; - - this.log.debug("Generation end"); - - if (this.shebang) { - result.code = this.shebang + "\n" + result.code; - } - - if (result.map) { - result.map = this.mergeSourceMap(result.map); - } - - if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { - result.code += "\n" + _convertSourceMap2.default.fromObject(result.map).toComment(); - } - - if (opts.sourceMaps === "inline") { - result.map = null; - } - - return this.makeResult(result); - }; - - return File; -}(_store2.default); - -exports.default = File; -exports.File = File; -}).call(this,require('_process')) -},{"../../helpers/resolve":14,"../../store":15,"../../util":31,"../internal-plugins/block-hoist":26,"../internal-plugins/shadow-functions":27,"../plugin-pass":29,"./logger":18,"./metadata":19,"./options/option-manager":23,"_process":525,"babel-code-frame":4,"babel-generator":44,"babel-helpers":60,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/assign":99,"babel-runtime/core-js/object/create":100,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"babel-traverse":118,"babel-types":151,"babylon":155,"convert-source-map":163,"lodash/defaults":470,"path":522,"source-map":552}],18:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _node = require("debug/node"); - -var _node2 = _interopRequireDefault(_node); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var verboseDebug = (0, _node2.default)("babel:verbose"); -var generalDebug = (0, _node2.default)("babel"); - -var seenDeprecatedMessages = []; - -var Logger = function () { - function Logger(file, filename) { - (0, _classCallCheck3.default)(this, Logger); - - this.filename = filename; - this.file = file; - } - - Logger.prototype._buildMessage = function _buildMessage(msg) { - var parts = "[BABEL] " + this.filename; - if (msg) parts += ": " + msg; - return parts; - }; - - Logger.prototype.warn = function warn(msg) { - console.warn(this._buildMessage(msg)); - }; - - Logger.prototype.error = function error(msg) { - var Constructor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error; - - throw new Constructor(this._buildMessage(msg)); - }; - - Logger.prototype.deprecate = function deprecate(msg) { - if (this.file.opts && this.file.opts.suppressDeprecationMessages) return; - - msg = this._buildMessage(msg); - - if (seenDeprecatedMessages.indexOf(msg) >= 0) return; - - seenDeprecatedMessages.push(msg); - - console.error(msg); - }; - - Logger.prototype.verbose = function verbose(msg) { - if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg)); - }; - - Logger.prototype.debug = function debug(msg) { - if (generalDebug.enabled) generalDebug(this._buildMessage(msg)); - }; - - Logger.prototype.deopt = function deopt(node, msg) { - this.debug(msg); - }; - - return Logger; -}(); - -exports.default = Logger; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109,"debug/node":278}],19:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ImportDeclaration = exports.ModuleDeclaration = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.ExportDeclaration = ExportDeclaration; -exports.Scope = Scope; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var ModuleDeclaration = exports.ModuleDeclaration = { - enter: function enter(path, file) { - var node = path.node; - - if (node.source) { - node.source.value = file.resolveModuleSource(node.source.value); - } - } -}; - -var ImportDeclaration = exports.ImportDeclaration = { - exit: function exit(path, file) { - var node = path.node; - - - var specifiers = []; - var imported = []; - file.metadata.modules.imports.push({ - source: node.source.value, - imported: imported, - specifiers: specifiers - }); - - for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var specifier = _ref; - - var local = specifier.node.local.name; - - if (specifier.isImportDefaultSpecifier()) { - imported.push("default"); - specifiers.push({ - kind: "named", - imported: "default", - local: local - }); - } - - if (specifier.isImportSpecifier()) { - var importedName = specifier.node.imported.name; - imported.push(importedName); - specifiers.push({ - kind: "named", - imported: importedName, - local: local - }); - } - - if (specifier.isImportNamespaceSpecifier()) { - imported.push("*"); - specifiers.push({ - kind: "namespace", - local: local - }); - } - } - } -}; - -function ExportDeclaration(path, file) { - var node = path.node; - - - var source = node.source ? node.source.value : null; - var exports = file.metadata.modules.exports; - - var declar = path.get("declaration"); - if (declar.isStatement()) { - var bindings = declar.getBindingIdentifiers(); - - for (var name in bindings) { - exports.exported.push(name); - exports.specifiers.push({ - kind: "local", - local: name, - exported: path.isExportDefaultDeclaration() ? "default" : name - }); - } - } - - if (path.isExportNamedDeclaration() && node.specifiers) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var specifier = _ref2; - - var exported = specifier.exported.name; - exports.exported.push(exported); - - if (t.isExportDefaultSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external", - local: exported, - exported: exported, - source: source - }); - } - - if (t.isExportNamespaceSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external-namespace", - exported: exported, - source: source - }); - } - - var local = specifier.local; - if (!local) continue; - - if (source) { - exports.specifiers.push({ - kind: "external", - local: local.name, - exported: exported, - source: source - }); - } - - if (!source) { - exports.specifiers.push({ - kind: "local", - local: local.name, - exported: exported - }); - } - } - } - - if (path.isExportAllDeclaration()) { - exports.specifiers.push({ - kind: "external-all", - source: source - }); - } -} - -function Scope(path) { - path.skip(); -} -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],20:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -exports.default = buildConfigChain; - -var _resolve = require("../../../helpers/resolve"); - -var _resolve2 = _interopRequireDefault(_resolve); - -var _json = require("json5"); - -var _json2 = _interopRequireDefault(_json); - -var _pathIsAbsolute = require("path-is-absolute"); - -var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -var _fs = require("fs"); - -var _fs2 = _interopRequireDefault(_fs); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var existsCache = {}; -var jsonCache = {}; - -var BABELIGNORE_FILENAME = ".babelignore"; -var BABELRC_FILENAME = ".babelrc"; -var PACKAGE_FILENAME = "package.json"; - -function exists(filename) { - var cached = existsCache[filename]; - if (cached == null) { - return existsCache[filename] = _fs2.default.existsSync(filename); - } else { - return cached; - } -} - -function buildConfigChain() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var log = arguments[1]; - - var filename = opts.filename; - var builder = new ConfigChainBuilder(log); - - if (opts.babelrc !== false) { - builder.findConfigs(filename); - } - - builder.mergeConfig({ - options: opts, - alias: "base", - dirname: filename && _path2.default.dirname(filename) - }); - - return builder.configs; -} - -var ConfigChainBuilder = function () { - function ConfigChainBuilder(log) { - (0, _classCallCheck3.default)(this, ConfigChainBuilder); - - this.resolvedConfigs = []; - this.configs = []; - this.log = log; - } - - ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) { - if (!loc) return; - - if (!(0, _pathIsAbsolute2.default)(loc)) { - loc = _path2.default.join(process.cwd(), loc); - } - - var foundConfig = false; - var foundIgnore = false; - - while (loc !== (loc = _path2.default.dirname(loc))) { - if (!foundConfig) { - var configLoc = _path2.default.join(loc, BABELRC_FILENAME); - if (exists(configLoc)) { - this.addConfig(configLoc); - foundConfig = true; - } - - var pkgLoc = _path2.default.join(loc, PACKAGE_FILENAME); - if (!foundConfig && exists(pkgLoc)) { - foundConfig = this.addConfig(pkgLoc, "babel", JSON); - } - } - - if (!foundIgnore) { - var ignoreLoc = _path2.default.join(loc, BABELIGNORE_FILENAME); - if (exists(ignoreLoc)) { - this.addIgnoreConfig(ignoreLoc); - foundIgnore = true; - } - } - - if (foundIgnore && foundConfig) return; - } - }; - - ConfigChainBuilder.prototype.addIgnoreConfig = function addIgnoreConfig(loc) { - var file = _fs2.default.readFileSync(loc, "utf8"); - var lines = file.split("\n"); - - lines = lines.map(function (line) { - return line.replace(/#(.*?)$/, "").trim(); - }).filter(function (line) { - return !!line; - }); - - if (lines.length) { - this.mergeConfig({ - options: { ignore: lines }, - alias: loc, - dirname: _path2.default.dirname(loc) - }); - } - }; - - ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) { - var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _json2.default; - - if (this.resolvedConfigs.indexOf(loc) >= 0) { - return false; - } - - this.resolvedConfigs.push(loc); - - var content = _fs2.default.readFileSync(loc, "utf8"); - var options = void 0; - - try { - options = jsonCache[content] = jsonCache[content] || json.parse(content); - if (key) options = options[key]; - } catch (err) { - err.message = loc + ": Error while parsing JSON - " + err.message; - throw err; - } - - this.mergeConfig({ - options: options, - alias: loc, - dirname: _path2.default.dirname(loc) - }); - - return !!options; - }; - - ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) { - var options = _ref.options, - alias = _ref.alias, - loc = _ref.loc, - dirname = _ref.dirname; - - if (!options) { - return false; - } - - options = (0, _assign2.default)({}, options); - - dirname = dirname || process.cwd(); - loc = loc || alias; - - if (options.extends) { - var extendsLoc = (0, _resolve2.default)(options.extends, dirname); - if (extendsLoc) { - this.addConfig(extendsLoc); - } else { - if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias); - } - delete options.extends; - } - - this.configs.push({ - options: options, - alias: alias, - loc: loc, - dirname: dirname - }); - - var envOpts = void 0; - var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; - if (options.env) { - envOpts = options.env[envKey]; - delete options.env; - } - - this.mergeConfig({ - options: envOpts, - alias: alias + ".env." + envKey, - dirname: dirname - }); - }; - - return ConfigChainBuilder; -}(); - -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../helpers/resolve":14,"_process":525,"babel-runtime/core-js/object/assign":99,"babel-runtime/helpers/classCallCheck":109,"fs":159,"json5":297,"path":522,"path-is-absolute":523}],21:[function(require,module,exports){ -"use strict"; - -module.exports = { - filename: { - type: "filename", - description: "filename to use when reading from stdin - this will be used in source-maps, errors etc", - default: "unknown", - shorthand: "f" - }, - - filenameRelative: { - hidden: true, - type: "string" - }, - - inputSourceMap: { - hidden: true - }, - - env: { - hidden: true, - default: {} - }, - - mode: { - description: "", - hidden: true - }, - - retainLines: { - type: "boolean", - default: false, - description: "retain line numbers - will result in really ugly code" - }, - - highlightCode: { - description: "enable/disable ANSI syntax highlighting of code frames (on by default)", - type: "boolean", - default: true - }, - - suppressDeprecationMessages: { - type: "boolean", - default: false, - hidden: true - }, - - presets: { - type: "list", - description: "", - default: [] - }, - - plugins: { - type: "list", - default: [], - description: "" - }, - - ignore: { - type: "list", - description: "list of glob paths to **not** compile", - default: [] - }, - - only: { - type: "list", - description: "list of glob paths to **only** compile" - }, - - code: { - hidden: true, - default: true, - type: "boolean" - }, - - metadata: { - hidden: true, - default: true, - type: "boolean" - }, - - ast: { - hidden: true, - default: true, - type: "boolean" - }, - - extends: { - type: "string", - hidden: true - }, - - comments: { - type: "boolean", - default: true, - description: "write comments to generated output (true by default)" - }, - - shouldPrintComment: { - hidden: true, - description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored" - }, - - wrapPluginVisitorMethod: { - hidden: true, - description: "optional callback to wrap all visitor methods" - }, - - compact: { - type: "booleanString", - default: "auto", - description: "do not include superfluous whitespace characters and line terminators [true|false|auto]" - }, - - minified: { - type: "boolean", - default: false, - description: "save as much bytes when printing [true|false]" - }, - - sourceMap: { - alias: "sourceMaps", - hidden: true - }, - - sourceMaps: { - type: "booleanString", - description: "[true|false|inline]", - default: false, - shorthand: "s" - }, - - sourceMapTarget: { - type: "string", - description: "set `file` on returned source map" - }, - - sourceFileName: { - type: "string", - description: "set `sources[0]` on returned source map" - }, - - sourceRoot: { - type: "filename", - description: "the root from which all sources are relative" - }, - - babelrc: { - description: "Whether or not to look up .babelrc and .babelignore files", - type: "boolean", - default: true - }, - - sourceType: { - description: "", - default: "module" - }, - - auxiliaryCommentBefore: { - type: "string", - description: "print a comment before any injected non-user code" - }, - - auxiliaryCommentAfter: { - type: "string", - description: "print a comment after any injected non-user code" - }, - - resolveModuleSource: { - hidden: true - }, - - getModuleId: { - hidden: true - }, - - moduleRoot: { - type: "filename", - description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions" - }, - - moduleIds: { - type: "boolean", - default: false, - shorthand: "M", - description: "insert an explicit id for modules" - }, - - moduleId: { - description: "specify a custom name for module ids", - type: "string" - }, - - passPerPreset: { - description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.", - type: "boolean", - default: false, - hidden: true - }, - - parserOpts: { - description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", - default: false - }, - - generatorOpts: { - description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", - default: false - } -}; -},{}],22:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.config = undefined; -exports.normaliseOptions = normaliseOptions; - -var _parsers = require("./parsers"); - -var parsers = _interopRequireWildcard(_parsers); - -var _config = require("./config"); - -var _config2 = _interopRequireDefault(_config); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -exports.config = _config2.default; -function normaliseOptions() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - for (var key in options) { - var val = options[key]; - if (val == null) continue; - - var opt = _config2.default[key]; - if (opt && opt.alias) opt = _config2.default[opt.alias]; - if (!opt) continue; - - var parser = parsers[opt.type]; - if (parser) val = parser(val); - - options[key] = val; - } - - return options; -} -},{"./config":21,"./parsers":24}],23:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties"); - -var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _node = require("../../../api/node"); - -var context = _interopRequireWildcard(_node); - -var _plugin2 = require("../../plugin"); - -var _plugin3 = _interopRequireDefault(_plugin2); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _index = require("./index"); - -var _resolvePlugin = require("../../../helpers/resolve-plugin"); - -var _resolvePlugin2 = _interopRequireDefault(_resolvePlugin); - -var _resolvePreset = require("../../../helpers/resolve-preset"); - -var _resolvePreset2 = _interopRequireDefault(_resolvePreset); - -var _cloneDeepWith = require("lodash/cloneDeepWith"); - -var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -var _merge = require("../../../helpers/merge"); - -var _merge2 = _interopRequireDefault(_merge); - -var _config2 = require("./config"); - -var _config3 = _interopRequireDefault(_config2); - -var _removed = require("./removed"); - -var _removed2 = _interopRequireDefault(_removed); - -var _buildConfigChain = require("./build-config-chain"); - -var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var OptionManager = function () { - function OptionManager(log) { - (0, _classCallCheck3.default)(this, OptionManager); - - this.resolvedConfigs = []; - this.options = OptionManager.createBareOptions(); - this.log = log; - } - - OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) { - for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var cache = _ref; - - if (cache.container === fn) return cache.plugin; - } - - var obj = void 0; - - if (typeof fn === "function") { - obj = fn(context); - } else { - obj = fn; - } - - if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === "object") { - var _plugin = new _plugin3.default(obj, alias); - OptionManager.memoisedPlugins.push({ - container: fn, - plugin: _plugin - }); - return _plugin; - } else { - throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i); - } - }; - - OptionManager.createBareOptions = function createBareOptions() { - var opts = {}; - - for (var _key in _config3.default) { - var opt = _config3.default[_key]; - opts[_key] = (0, _clone2.default)(opt.default); - } - - return opts; - }; - - OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) { - plugin = plugin.__esModule ? plugin.default : plugin; - - if (!(plugin instanceof _plugin3.default)) { - if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") { - plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias); - } else { - throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin))); - } - } - - plugin.init(loc, i); - - return plugin; - }; - - OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) { - return plugins.map(function (val, i) { - var plugin = void 0, - options = void 0; - - if (!val) { - throw new TypeError("Falsy value found in plugins"); - } - - if (Array.isArray(val)) { - plugin = val[0]; - options = val[1]; - } else { - plugin = val; - } - - var alias = typeof plugin === "string" ? plugin : loc + "$" + i; - - if (typeof plugin === "string") { - var pluginLoc = (0, _resolvePlugin2.default)(plugin, dirname); - if (pluginLoc) { - plugin = require(pluginLoc); - } else { - throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname)); - } - } - - plugin = OptionManager.normalisePlugin(plugin, loc, i, alias); - - return [plugin, options]; - }); - }; - - OptionManager.prototype.mergeOptions = function mergeOptions(_ref2) { - var _this = this; - - var rawOpts = _ref2.options, - extendingOpts = _ref2.extending, - alias = _ref2.alias, - loc = _ref2.loc, - dirname = _ref2.dirname; - - alias = alias || "foreign"; - if (!rawOpts) return; - - if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) { - this.log.error("Invalid options type for " + alias, TypeError); - } - - var opts = (0, _cloneDeepWith2.default)(rawOpts, function (val) { - if (val instanceof _plugin3.default) { - return val; - } - }); - - dirname = dirname || process.cwd(); - loc = loc || alias; - - for (var _key2 in opts) { - var option = _config3.default[_key2]; - - if (!option && this.log) { - if (_removed2.default[_key2]) { - this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2.default[_key2].message, ReferenceError); - } else { - var unknownOptErr = "Unknown option: " + alias + "." + _key2 + ". Check out http://babeljs.io/docs/usage/options/ for more information about options."; - var presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; - - - this.log.error(unknownOptErr + "\n\n" + presetConfigErr, ReferenceError); - } - } - } - - (0, _index.normaliseOptions)(opts); - - if (opts.plugins) { - opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins); - } - - if (opts.presets) { - if (opts.passPerPreset) { - opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) { - _this.mergeOptions({ - options: preset, - extending: preset, - alias: presetLoc, - loc: presetLoc, - dirname: dirname - }); - }); - } else { - this.mergePresets(opts.presets, dirname); - delete opts.presets; - } - } - - if (rawOpts === extendingOpts) { - (0, _assign2.default)(extendingOpts, opts); - } else { - (0, _merge2.default)(extendingOpts || this.options, opts); - } - }; - - OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) { - var _this2 = this; - - this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) { - _this2.mergeOptions({ - options: presetOpts, - alias: presetLoc, - loc: presetLoc, - dirname: _path2.default.dirname(presetLoc || "") - }); - }); - }; - - OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) { - return presets.map(function (val) { - var options = void 0; - if (Array.isArray(val)) { - if (val.length > 2) { - throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset."); - } - - var _val = val; - val = _val[0]; - options = _val[1]; - } - - var presetLoc = void 0; - try { - if (typeof val === "string") { - presetLoc = (0, _resolvePreset2.default)(val, dirname); - - if (!presetLoc) { - throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname)); - } - - val = require(presetLoc); - } - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) { - if (val.default) { - val = val.default; - } else { - var _val2 = val, - __esModule = _val2.__esModule, - rest = (0, _objectWithoutProperties3.default)(_val2, ["__esModule"]); - - val = rest; - } - } - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset; - - if (typeof val !== "function" && options !== undefined) { - throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options."); - } - - if (typeof val === "function") val = val(context, options, { dirname: dirname }); - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") { - throw new Error("Unsupported preset format: " + val + "."); - } - - onResolve && onResolve(val, presetLoc); - } catch (e) { - if (presetLoc) { - e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")"; - } - throw e; - } - return val; - }); - }; - - OptionManager.prototype.normaliseOptions = function normaliseOptions() { - var opts = this.options; - - for (var _key3 in _config3.default) { - var option = _config3.default[_key3]; - var val = opts[_key3]; - - if (!val && option.optional) continue; - - if (option.alias) { - opts[option.alias] = opts[option.alias] || val; - } else { - opts[_key3] = val; - } - } - }; - - OptionManager.prototype.init = function init() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - var _config = _ref3; - - this.mergeOptions(_config); - } - - this.normaliseOptions(opts); - - return this.options; - }; - - return OptionManager; -}(); - -exports.default = OptionManager; - - -OptionManager.memoisedPlugins = []; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../api/node":6,"../../../helpers/merge":9,"../../../helpers/resolve-plugin":12,"../../../helpers/resolve-preset":13,"../../plugin":30,"./build-config-chain":20,"./config":21,"./index":22,"./removed":25,"_process":525,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/object/assign":99,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/objectWithoutProperties":111,"babel-runtime/helpers/typeof":113,"lodash/clone":466,"lodash/cloneDeepWith":468,"path":522}],24:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.filename = undefined; -exports.boolean = boolean; -exports.booleanString = booleanString; -exports.list = list; - -var _slash = require("slash"); - -var _slash2 = _interopRequireDefault(_slash); - -var _util = require("../../../util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var filename = exports.filename = _slash2.default; - -function boolean(val) { - return !!val; -} - -function booleanString(val) { - return util.booleanify(val); -} - -function list(val) { - return util.list(val); -} -},{"../../../util":31,"slash":541}],25:[function(require,module,exports){ -"use strict"; - -module.exports = { - "auxiliaryComment": { - "message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" - }, - "blacklist": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "breakConfig": { - "message": "This is not a necessary option in Babel 6" - }, - "experimental": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "externalHelpers": { - "message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/" - }, - "extra": { - "message": "" - }, - "jsxPragma": { - "message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/" - }, - - "loose": { - "message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option." - }, - "metadataUsedHelpers": { - "message": "Not required anymore as this is enabled by default" - }, - "modules": { - "message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules" - }, - "nonStandard": { - "message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" - }, - "optional": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "sourceMapName": { - "message": "Use the `sourceMapTarget` option" - }, - "stage": { - "message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" - }, - "whitelist": { - "message": "Put the specific transforms you want in the `plugins` option" - } -}; -},{}],26:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _plugin = require("../plugin"); - -var _plugin2 = _interopRequireDefault(_plugin); - -var _sortBy = require("lodash/sortBy"); - -var _sortBy2 = _interopRequireDefault(_sortBy); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = new _plugin2.default({ - - name: "internal.blockHoist", - - visitor: { - Block: { - exit: function exit(_ref) { - var node = _ref.node; - - var hasChange = false; - for (var i = 0; i < node.body.length; i++) { - var bodyNode = node.body[i]; - if (bodyNode && bodyNode._blockHoist != null) { - hasChange = true; - break; - } - } - if (!hasChange) return; - - node.body = (0, _sortBy2.default)(node.body, function (bodyNode) { - var priority = bodyNode && bodyNode._blockHoist; - if (priority == null) priority = 1; - if (priority === true) priority = 2; - - return -1 * priority; - }); - } - } - } -}); -module.exports = exports["default"]; -},{"../plugin":30,"lodash/sortBy":508}],27:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _plugin = require("../plugin"); - -var _plugin2 = _interopRequireDefault(_plugin); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound"); - -var superVisitor = { - CallExpression: function CallExpression(path) { - if (!path.get("callee").isSuper()) return; - - var node = path.node; - - if (node[SUPER_THIS_BOUND]) return; - node[SUPER_THIS_BOUND] = true; - - path.replaceWith(t.assignmentExpression("=", this.id, node)); - } -}; - -exports.default = new _plugin2.default({ - name: "internal.shadowFunctions", - - visitor: { - ThisExpression: function ThisExpression(path) { - remap(path, "this"); - }, - ReferencedIdentifier: function ReferencedIdentifier(path) { - if (path.node.name === "arguments") { - remap(path, "arguments"); - } - } - } -}); - - -function shouldShadow(path, shadowPath) { - if (path.is("_forceShadow")) { - return true; - } else { - return shadowPath; - } -} - -function remap(path, key) { - var shadowPath = path.inShadow(key); - if (!shouldShadow(path, shadowPath)) return; - - var shadowFunction = path.node._shadowedFunctionLiteral; - - var currentFunction = void 0; - var passedShadowFunction = false; - - var fnPath = path.find(function (innerPath) { - if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") { - return true; - } - if (path === innerPath) return false; - if (innerPath.isProgram() || innerPath.isFunction()) { - currentFunction = currentFunction || innerPath; - } - - if (innerPath.isProgram()) { - passedShadowFunction = true; - - return true; - } else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) { - if (shadowFunction) { - if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true; - } else { - if (!innerPath.is("shadow")) return true; - } - - passedShadowFunction = true; - return false; - } - - return false; - }); - - if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) { - fnPath = path.findParent(function (p) { - return p.isProgram() || p.isFunction(); - }); - } - - if (fnPath === currentFunction) return; - - if (!passedShadowFunction) return; - - var cached = fnPath.getData(key); - if (cached) return path.replaceWith(cached); - - var id = path.scope.generateUidIdentifier(key); - - fnPath.setData(key, id); - - var classPath = fnPath.findParent(function (p) { - return p.isClass(); - }); - var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); - - if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) { - fnPath.scope.push({ id: id }); - - fnPath.traverse(superVisitor, { id: id }); - } else { - var init = key === "this" ? t.thisExpression() : t.identifier(key); - - if (shadowFunction) init._shadowedFunctionLiteral = shadowFunction; - - fnPath.scope.push({ id: id, init: init }); - } - - return path.replaceWith(id); -} -module.exports = exports["default"]; -},{"../plugin":30,"babel-runtime/core-js/symbol":104,"babel-types":151}],28:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _normalizeAst = require("../helpers/normalize-ast"); - -var _normalizeAst2 = _interopRequireDefault(_normalizeAst); - -var _plugin = require("./plugin"); - -var _plugin2 = _interopRequireDefault(_plugin); - -var _file = require("./file"); - -var _file2 = _interopRequireDefault(_file); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Pipeline = function () { - function Pipeline() { - (0, _classCallCheck3.default)(this, Pipeline); - } - - Pipeline.prototype.lint = function lint(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - opts.code = false; - opts.mode = "lint"; - return this.transform(code, opts); - }; - - Pipeline.prototype.pretransform = function pretransform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file; - }); - }; - - Pipeline.prototype.transform = function transform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file.transform(); - }); - }; - - Pipeline.prototype.analyse = function analyse(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var visitor = arguments[2]; - - opts.code = false; - if (visitor) { - opts.plugins = opts.plugins || []; - opts.plugins.push(new _plugin2.default({ visitor: visitor })); - } - return this.transform(code, opts).metadata; - }; - - Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) { - ast = (0, _normalizeAst2.default)(ast); - - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.addAst(ast); - return file.transform(); - }); - }; - - return Pipeline; -}(); - -exports.default = Pipeline; -module.exports = exports["default"]; -},{"../helpers/normalize-ast":10,"./file":17,"./plugin":30,"babel-runtime/helpers/classCallCheck":109}],29:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _store = require("../store"); - -var _store2 = _interopRequireDefault(_store); - -var _file5 = require("./file"); - -var _file6 = _interopRequireDefault(_file5); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var PluginPass = function (_Store) { - (0, _inherits3.default)(PluginPass, _Store); - - function PluginPass(file, plugin) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - (0, _classCallCheck3.default)(this, PluginPass); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.plugin = plugin; - _this.key = plugin.key; - _this.file = file; - _this.opts = options; - return _this; - } - - PluginPass.prototype.addHelper = function addHelper() { - var _file; - - return (_file = this.file).addHelper.apply(_file, arguments); - }; - - PluginPass.prototype.addImport = function addImport() { - var _file2; - - return (_file2 = this.file).addImport.apply(_file2, arguments); - }; - - PluginPass.prototype.getModuleName = function getModuleName() { - var _file3; - - return (_file3 = this.file).getModuleName.apply(_file3, arguments); - }; - - PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() { - var _file4; - - return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments); - }; - - return PluginPass; -}(_store2.default); - -exports.default = PluginPass; -module.exports = exports["default"]; -},{"../store":15,"./file":17,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112}],30:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _optionManager = require("./file/options/option-manager"); - -var _optionManager2 = _interopRequireDefault(_optionManager); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _store = require("../store"); - -var _store2 = _interopRequireDefault(_store); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _assign = require("lodash/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var GLOBAL_VISITOR_PROPS = ["enter", "exit"]; - -var Plugin = function (_Store) { - (0, _inherits3.default)(Plugin, _Store); - - function Plugin(plugin, key) { - (0, _classCallCheck3.default)(this, Plugin); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.initialized = false; - _this.raw = (0, _assign2.default)({}, plugin); - _this.key = _this.take("name") || key; - - _this.manipulateOptions = _this.take("manipulateOptions"); - _this.post = _this.take("post"); - _this.pre = _this.take("pre"); - _this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {}); - return _this; - } - - Plugin.prototype.take = function take(key) { - var val = this.raw[key]; - delete this.raw[key]; - return val; - }; - - Plugin.prototype.chain = function chain(target, key) { - if (!target[key]) return this[key]; - if (!this[key]) return target[key]; - - var fns = [target[key], this[key]]; - - return function () { - var val = void 0; - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var fn = _ref; - - if (fn) { - var ret = fn.apply(this, args); - if (ret != null) val = ret; - } - } - return val; - }; - }; - - Plugin.prototype.maybeInherit = function maybeInherit(loc) { - var inherits = this.take("inherits"); - if (!inherits) return; - - inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits"); - - this.manipulateOptions = this.chain(inherits, "manipulateOptions"); - this.post = this.chain(inherits, "post"); - this.pre = this.chain(inherits, "pre"); - this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]); - }; - - Plugin.prototype.init = function init(loc, i) { - if (this.initialized) return; - this.initialized = true; - - this.maybeInherit(loc); - - for (var key in this.raw) { - throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); - } - }; - - Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) { - for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var key = _ref2; - - if (visitor[key]) { - throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " + "Please target individual nodes."); - } - } - - _babelTraverse2.default.explode(visitor); - return visitor; - }; - - return Plugin; -}(_store2.default); - -exports.default = Plugin; -module.exports = exports["default"]; -},{"../store":15,"./file/options/option-manager":23,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"babel-traverse":118,"lodash/assign":463,"lodash/clone":466}],31:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.inspect = exports.inherits = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _util = require("util"); - -Object.defineProperty(exports, "inherits", { - enumerable: true, - get: function get() { - return _util.inherits; - } -}); -Object.defineProperty(exports, "inspect", { - enumerable: true, - get: function get() { - return _util.inspect; - } -}); -exports.canCompile = canCompile; -exports.list = list; -exports.regexify = regexify; -exports.arrayify = arrayify; -exports.booleanify = booleanify; -exports.shouldIgnore = shouldIgnore; - -var _escapeRegExp = require("lodash/escapeRegExp"); - -var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp); - -var _startsWith = require("lodash/startsWith"); - -var _startsWith2 = _interopRequireDefault(_startsWith); - -var _minimatch = require("minimatch"); - -var _minimatch2 = _interopRequireDefault(_minimatch); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _isRegExp = require("lodash/isRegExp"); - -var _isRegExp2 = _interopRequireDefault(_isRegExp); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -var _slash = require("slash"); - -var _slash2 = _interopRequireDefault(_slash); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function canCompile(filename, altExts) { - var exts = altExts || canCompile.EXTENSIONS; - var ext = _path2.default.extname(filename); - return (0, _includes2.default)(exts, ext); -} - -canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"]; - -function list(val) { - if (!val) { - return []; - } else if (Array.isArray(val)) { - return val; - } else if (typeof val === "string") { - return val.split(","); - } else { - return [val]; - } -} - -function regexify(val) { - if (!val) { - return new RegExp(/.^/); - } - - if (Array.isArray(val)) { - val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i"); - } - - if (typeof val === "string") { - val = (0, _slash2.default)(val); - - if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2); - if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3); - - var regex = _minimatch2.default.makeRe(val, { nocase: true }); - return new RegExp(regex.source.slice(1, -1), "i"); - } - - if ((0, _isRegExp2.default)(val)) { - return val; - } - - throw new TypeError("illegal type for regexify"); -} - -function arrayify(val, mapFn) { - if (!val) return []; - if (typeof val === "boolean") return arrayify([val], mapFn); - if (typeof val === "string") return arrayify(list(val), mapFn); - - if (Array.isArray(val)) { - if (mapFn) val = val.map(mapFn); - return val; - } - - return [val]; -} - -function booleanify(val) { - if (val === "true" || val == 1) { - return true; - } - - if (val === "false" || val == 0 || !val) { - return false; - } - - return val; -} - -function shouldIgnore(filename) { - var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var only = arguments[2]; - - filename = filename.replace(/\\/g, "/"); - - if (only) { - for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var pattern = _ref; - - if (_shouldIgnore(pattern, filename)) return false; - } - return true; - } else if (ignore.length) { - for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _pattern = _ref2; - - if (_shouldIgnore(_pattern, filename)) return true; - } - } - - return false; -} - -function _shouldIgnore(pattern, filename) { - if (typeof pattern === "function") { - return pattern(filename); - } else { - return pattern.test(filename); - } -} -},{"babel-runtime/core-js/get-iterator":95,"lodash/escapeRegExp":472,"lodash/includes":482,"lodash/isRegExp":494,"lodash/startsWith":509,"minimatch":519,"path":522,"slash":541,"util":560}],32:[function(require,module,exports){ -module.exports={ - "_from": "babel-core@^6.22.1", - "_id": "babel-core@6.26.0", - "_inBundle": false, - "_integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=", - "_location": "/babel-core", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "babel-core@^6.22.1", - "name": "babel-core", - "escapedName": "babel-core", - "rawSpec": "^6.22.1", - "saveSpec": null, - "fetchSpec": "^6.22.1" - }, - "_requiredBy": [ - "#DEV:/", - "/babel-register", - "/babelify", - "/karma-babel-preprocessor" - ], - "_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz", - "_shasum": "af32f78b31a6fcef119c87b0fd8d9753f03a0bb8", - "_spec": "babel-core@^6.22.1", - "_where": "/Users/juanjodiaz/Documents/code/OSS libs/noVNC", - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bundleDependencies": false, - "dependencies": { - "babel-code-frame": "^6.26.0", - "babel-generator": "^6.26.0", - "babel-helpers": "^6.24.1", - "babel-messages": "^6.23.0", - "babel-register": "^6.26.0", - "babel-runtime": "^6.26.0", - "babel-template": "^6.26.0", - "babel-traverse": "^6.26.0", - "babel-types": "^6.26.0", - "babylon": "^6.18.0", - "convert-source-map": "^1.5.0", - "debug": "^2.6.8", - "json5": "^0.5.1", - "lodash": "^4.17.4", - "minimatch": "^3.0.4", - "path-is-absolute": "^1.0.1", - "private": "^0.1.7", - "slash": "^1.0.0", - "source-map": "^0.5.6" - }, - "deprecated": false, - "description": "Babel compiler core.", - "devDependencies": { - "babel-helper-fixtures": "^6.26.0", - "babel-helper-transform-fixture-test-runner": "^6.26.0", - "babel-polyfill": "^6.26.0" - }, - "homepage": "https://babeljs.io/", - "keywords": [ - "6to5", - "babel", - "classes", - "const", - "es6", - "harmony", - "let", - "modules", - "transpile", - "transpiler", - "var", - "babel-core", - "compiler" - ], - "license": "MIT", - "name": "babel-core", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-core" - }, - "scripts": { - "bench": "make bench", - "test": "make test" - }, - "version": "6.26.0" -} - -},{}],33:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _trimRight = require("trim-right"); - -var _trimRight2 = _interopRequireDefault(_trimRight); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SPACES_RE = /^[ \t]+$/; - -var Buffer = function () { - function Buffer(map) { - (0, _classCallCheck3.default)(this, Buffer); - this._map = null; - this._buf = []; - this._last = ""; - this._queue = []; - this._position = { - line: 1, - column: 0 - }; - this._sourcePosition = { - identifierName: null, - line: null, - column: null, - filename: null - }; - - this._map = map; - } - - Buffer.prototype.get = function get() { - this._flush(); - - var map = this._map; - var result = { - code: (0, _trimRight2.default)(this._buf.join("")), - map: null, - rawMappings: map && map.getRawMappings() - }; - - if (map) { - Object.defineProperty(result, "map", { - configurable: true, - enumerable: true, - get: function get() { - return this.map = map.get(); - }, - set: function set(value) { - Object.defineProperty(this, "map", { value: value, writable: true }); - } - }); - } - - return result; - }; - - Buffer.prototype.append = function append(str) { - this._flush(); - var _sourcePosition = this._sourcePosition, - line = _sourcePosition.line, - column = _sourcePosition.column, - filename = _sourcePosition.filename, - identifierName = _sourcePosition.identifierName; - - this._append(str, line, column, identifierName, filename); - }; - - Buffer.prototype.queue = function queue(str) { - if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { - this._queue.shift(); - }var _sourcePosition2 = this._sourcePosition, - line = _sourcePosition2.line, - column = _sourcePosition2.column, - filename = _sourcePosition2.filename, - identifierName = _sourcePosition2.identifierName; - - this._queue.unshift([str, line, column, identifierName, filename]); - }; - - Buffer.prototype._flush = function _flush() { - var item = void 0; - while (item = this._queue.pop()) { - this._append.apply(this, item); - } - }; - - Buffer.prototype._append = function _append(str, line, column, identifierName, filename) { - if (this._map && str[0] !== "\n") { - this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename); - } - - this._buf.push(str); - this._last = str[str.length - 1]; - - for (var i = 0; i < str.length; i++) { - if (str[i] === "\n") { - this._position.line++; - this._position.column = 0; - } else { - this._position.column++; - } - } - }; - - Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() { - if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift(); - }; - - Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() { - if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift(); - }; - - Buffer.prototype.endsWith = function endsWith(suffix) { - if (suffix.length === 1) { - var last = void 0; - if (this._queue.length > 0) { - var str = this._queue[0][0]; - last = str[str.length - 1]; - } else { - last = this._last; - } - - return last === suffix; - } - - var end = this._last + this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - if (suffix.length <= end.length) { - return end.slice(-suffix.length) === suffix; - } - - return false; - }; - - Buffer.prototype.hasContent = function hasContent() { - return this._queue.length > 0 || !!this._last; - }; - - Buffer.prototype.source = function source(prop, loc) { - if (prop && !loc) return; - - var pos = loc ? loc[prop] : null; - - this._sourcePosition.identifierName = loc && loc.identifierName || null; - this._sourcePosition.line = pos ? pos.line : null; - this._sourcePosition.column = pos ? pos.column : null; - this._sourcePosition.filename = loc && loc.filename || null; - }; - - Buffer.prototype.withSource = function withSource(prop, loc, cb) { - if (!this._map) return cb(); - - var originalLine = this._sourcePosition.line; - var originalColumn = this._sourcePosition.column; - var originalFilename = this._sourcePosition.filename; - var originalIdentifierName = this._sourcePosition.identifierName; - - this.source(prop, loc); - - cb(); - - this._sourcePosition.line = originalLine; - this._sourcePosition.column = originalColumn; - this._sourcePosition.filename = originalFilename; - this._sourcePosition.identifierName = originalIdentifierName; - }; - - Buffer.prototype.getCurrentColumn = function getCurrentColumn() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - var lastIndex = extra.lastIndexOf("\n"); - - return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; - }; - - Buffer.prototype.getCurrentLine = function getCurrentLine() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - - var count = 0; - for (var i = 0; i < extra.length; i++) { - if (extra[i] === "\n") count++; - } - - return this._position.line + count; - }; - - return Buffer; -}(); - -exports.default = Buffer; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109,"trim-right":556}],34:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.File = File; -exports.Program = Program; -exports.BlockStatement = BlockStatement; -exports.Noop = Noop; -exports.Directive = Directive; - -var _types = require("./types"); - -Object.defineProperty(exports, "DirectiveLiteral", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -function File(node) { - this.print(node.program, node); -} - -function Program(node) { - this.printInnerComments(node, false); - - this.printSequence(node.directives, node); - if (node.directives && node.directives.length) this.newline(); - - this.printSequence(node.body, node); -} - -function BlockStatement(node) { - this.token("{"); - this.printInnerComments(node); - - var hasDirectives = node.directives && node.directives.length; - - if (node.body.length || hasDirectives) { - this.newline(); - - this.printSequence(node.directives, node, { indent: true }); - if (hasDirectives) this.newline(); - - this.printSequence(node.body, node, { indent: true }); - this.removeTrailingNewline(); - - this.source("end", node.loc); - - if (!this.endsWith("\n")) this.newline(); - - this.rightBrace(); - } else { - this.source("end", node.loc); - this.token("}"); - } -} - -function Noop() {} - -function Directive(node) { - this.print(node.value, node); - this.semicolon(); -} -},{"./types":43}],35:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ClassDeclaration = ClassDeclaration; -exports.ClassBody = ClassBody; -exports.ClassProperty = ClassProperty; -exports.ClassMethod = ClassMethod; -function ClassDeclaration(node) { - this.printJoin(node.decorators, node); - this.word("class"); - - if (node.id) { - this.space(); - this.print(node.id, node); - } - - this.print(node.typeParameters, node); - - if (node.superClass) { - this.space(); - this.word("extends"); - this.space(); - this.print(node.superClass, node); - this.print(node.superTypeParameters, node); - } - - if (node.implements) { - this.space(); - this.word("implements"); - this.space(); - this.printList(node.implements, node); - } - - this.space(); - this.print(node.body, node); -} - -exports.ClassExpression = ClassDeclaration; -function ClassBody(node) { - this.token("{"); - this.printInnerComments(node); - if (node.body.length === 0) { - this.token("}"); - } else { - this.newline(); - - this.indent(); - this.printSequence(node.body, node); - this.dedent(); - - if (!this.endsWith("\n")) this.newline(); - - this.rightBrace(); - } -} - -function ClassProperty(node) { - this.printJoin(node.decorators, node); - - if (node.static) { - this.word("static"); - this.space(); - } - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - this._variance(node); - this.print(node.key, node); - } - this.print(node.typeAnnotation, node); - if (node.value) { - this.space(); - this.token("="); - this.space(); - this.print(node.value, node); - } - this.semicolon(); -} - -function ClassMethod(node) { - this.printJoin(node.decorators, node); - - if (node.static) { - this.word("static"); - this.space(); - } - - if (node.kind === "constructorCall") { - this.word("call"); - this.space(); - } - - this._method(node); -} -},{}],36:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined; -exports.UnaryExpression = UnaryExpression; -exports.DoExpression = DoExpression; -exports.ParenthesizedExpression = ParenthesizedExpression; -exports.UpdateExpression = UpdateExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.NewExpression = NewExpression; -exports.SequenceExpression = SequenceExpression; -exports.ThisExpression = ThisExpression; -exports.Super = Super; -exports.Decorator = Decorator; -exports.CallExpression = CallExpression; -exports.Import = Import; -exports.EmptyStatement = EmptyStatement; -exports.ExpressionStatement = ExpressionStatement; -exports.AssignmentPattern = AssignmentPattern; -exports.AssignmentExpression = AssignmentExpression; -exports.BindExpression = BindExpression; -exports.MemberExpression = MemberExpression; -exports.MetaProperty = MetaProperty; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _node = require("../node"); - -var n = _interopRequireWildcard(_node); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function UnaryExpression(node) { - if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") { - this.word(node.operator); - this.space(); - } else { - this.token(node.operator); - } - - this.print(node.argument, node); -} - -function DoExpression(node) { - this.word("do"); - this.space(); - this.print(node.body, node); -} - -function ParenthesizedExpression(node) { - this.token("("); - this.print(node.expression, node); - this.token(")"); -} - -function UpdateExpression(node) { - if (node.prefix) { - this.token(node.operator); - this.print(node.argument, node); - } else { - this.print(node.argument, node); - this.token(node.operator); - } -} - -function ConditionalExpression(node) { - this.print(node.test, node); - this.space(); - this.token("?"); - this.space(); - this.print(node.consequent, node); - this.space(); - this.token(":"); - this.space(); - this.print(node.alternate, node); -} - -function NewExpression(node, parent) { - this.word("new"); - this.space(); - this.print(node.callee, node); - if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return; - - this.token("("); - this.printList(node.arguments, node); - this.token(")"); -} - -function SequenceExpression(node) { - this.printList(node.expressions, node); -} - -function ThisExpression() { - this.word("this"); -} - -function Super() { - this.word("super"); -} - -function Decorator(node) { - this.token("@"); - this.print(node.expression, node); - this.newline(); -} - -function commaSeparatorNewline() { - this.token(","); - this.newline(); - - if (!this.endsWith("\n")) this.space(); -} - -function CallExpression(node) { - this.print(node.callee, node); - - this.token("("); - - var isPrettyCall = node._prettyCall; - - var separator = void 0; - if (isPrettyCall) { - separator = commaSeparatorNewline; - this.newline(); - this.indent(); - } - - this.printList(node.arguments, node, { separator: separator }); - - if (isPrettyCall) { - this.newline(); - this.dedent(); - } - - this.token(")"); -} - -function Import() { - this.word("import"); -} - -function buildYieldAwait(keyword) { - return function (node) { - this.word(keyword); - - if (node.delegate) { - this.token("*"); - } - - if (node.argument) { - this.space(); - var terminatorState = this.startTerminatorless(); - this.print(node.argument, node); - this.endTerminatorless(terminatorState); - } - }; -} - -var YieldExpression = exports.YieldExpression = buildYieldAwait("yield"); -var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await"); - -function EmptyStatement() { - this.semicolon(true); -} - -function ExpressionStatement(node) { - this.print(node.expression, node); - this.semicolon(); -} - -function AssignmentPattern(node) { - this.print(node.left, node); - if (node.left.optional) this.token("?"); - this.print(node.left.typeAnnotation, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); -} - -function AssignmentExpression(node, parent) { - var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); - - if (parens) { - this.token("("); - } - - this.print(node.left, node); - - this.space(); - if (node.operator === "in" || node.operator === "instanceof") { - this.word(node.operator); - } else { - this.token(node.operator); - } - this.space(); - - this.print(node.right, node); - - if (parens) { - this.token(")"); - } -} - -function BindExpression(node) { - this.print(node.object, node); - this.token("::"); - this.print(node.callee, node); -} - -exports.BinaryExpression = AssignmentExpression; -exports.LogicalExpression = AssignmentExpression; -function MemberExpression(node) { - this.print(node.object, node); - - if (!node.computed && t.isMemberExpression(node.property)) { - throw new TypeError("Got a MemberExpression for MemberExpression property"); - } - - var computed = node.computed; - if (t.isLiteral(node.property) && typeof node.property.value === "number") { - computed = true; - } - - if (computed) { - this.token("["); - this.print(node.property, node); - this.token("]"); - } else { - this.token("."); - this.print(node.property, node); - } -} - -function MetaProperty(node) { - this.print(node.meta, node); - this.token("."); - this.print(node.property, node); -} -},{"../node":45,"babel-types":151}],37:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.TypeParameterDeclaration = exports.StringLiteralTypeAnnotation = exports.NumericLiteralTypeAnnotation = exports.GenericTypeAnnotation = exports.ClassImplements = undefined; -exports.AnyTypeAnnotation = AnyTypeAnnotation; -exports.ArrayTypeAnnotation = ArrayTypeAnnotation; -exports.BooleanTypeAnnotation = BooleanTypeAnnotation; -exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; -exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; -exports.DeclareClass = DeclareClass; -exports.DeclareFunction = DeclareFunction; -exports.DeclareInterface = DeclareInterface; -exports.DeclareModule = DeclareModule; -exports.DeclareModuleExports = DeclareModuleExports; -exports.DeclareTypeAlias = DeclareTypeAlias; -exports.DeclareOpaqueType = DeclareOpaqueType; -exports.DeclareVariable = DeclareVariable; -exports.DeclareExportDeclaration = DeclareExportDeclaration; -exports.ExistentialTypeParam = ExistentialTypeParam; -exports.FunctionTypeAnnotation = FunctionTypeAnnotation; -exports.FunctionTypeParam = FunctionTypeParam; -exports.InterfaceExtends = InterfaceExtends; -exports._interfaceish = _interfaceish; -exports._variance = _variance; -exports.InterfaceDeclaration = InterfaceDeclaration; -exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; -exports.MixedTypeAnnotation = MixedTypeAnnotation; -exports.EmptyTypeAnnotation = EmptyTypeAnnotation; -exports.NullableTypeAnnotation = NullableTypeAnnotation; - -var _types = require("./types"); - -Object.defineProperty(exports, "NumericLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.NumericLiteral; - } -}); -Object.defineProperty(exports, "StringLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -exports.NumberTypeAnnotation = NumberTypeAnnotation; -exports.StringTypeAnnotation = StringTypeAnnotation; -exports.ThisTypeAnnotation = ThisTypeAnnotation; -exports.TupleTypeAnnotation = TupleTypeAnnotation; -exports.TypeofTypeAnnotation = TypeofTypeAnnotation; -exports.TypeAlias = TypeAlias; -exports.OpaqueType = OpaqueType; -exports.TypeAnnotation = TypeAnnotation; -exports.TypeParameter = TypeParameter; -exports.TypeParameterInstantiation = TypeParameterInstantiation; -exports.ObjectTypeAnnotation = ObjectTypeAnnotation; -exports.ObjectTypeCallProperty = ObjectTypeCallProperty; -exports.ObjectTypeIndexer = ObjectTypeIndexer; -exports.ObjectTypeProperty = ObjectTypeProperty; -exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; -exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; -exports.UnionTypeAnnotation = UnionTypeAnnotation; -exports.TypeCastExpression = TypeCastExpression; -exports.VoidTypeAnnotation = VoidTypeAnnotation; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function AnyTypeAnnotation() { - this.word("any"); -} - -function ArrayTypeAnnotation(node) { - this.print(node.elementType, node); - this.token("["); - this.token("]"); -} - -function BooleanTypeAnnotation() { - this.word("boolean"); -} - -function BooleanLiteralTypeAnnotation(node) { - this.word(node.value ? "true" : "false"); -} - -function NullLiteralTypeAnnotation() { - this.word("null"); -} - -function DeclareClass(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.word("class"); - this.space(); - this._interfaceish(node); -} - -function DeclareFunction(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.word("function"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation.typeAnnotation, node); - this.semicolon(); -} - -function DeclareInterface(node) { - this.word("declare"); - this.space(); - this.InterfaceDeclaration(node); -} - -function DeclareModule(node) { - this.word("declare"); - this.space(); - this.word("module"); - this.space(); - this.print(node.id, node); - this.space(); - this.print(node.body, node); -} - -function DeclareModuleExports(node) { - this.word("declare"); - this.space(); - this.word("module"); - this.token("."); - this.word("exports"); - this.print(node.typeAnnotation, node); -} - -function DeclareTypeAlias(node) { - this.word("declare"); - this.space(); - this.TypeAlias(node); -} - -function DeclareOpaqueType(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.OpaqueType(node); -} - -function DeclareVariable(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.word("var"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - this.semicolon(); -} - -function DeclareExportDeclaration(node) { - this.word("declare"); - this.space(); - this.word("export"); - this.space(); - if (node.default) { - this.word("default"); - this.space(); - } - - FlowExportDeclaration.apply(this, arguments); -} - -function FlowExportDeclaration(node) { - if (node.declaration) { - var declar = node.declaration; - this.print(declar, node); - if (!t.isStatement(declar)) this.semicolon(); - } else { - this.token("{"); - if (node.specifiers.length) { - this.space(); - this.printList(node.specifiers, node); - this.space(); - } - this.token("}"); - - if (node.source) { - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); - } - - this.semicolon(); - } -} - -function ExistentialTypeParam() { - this.token("*"); -} - -function FunctionTypeAnnotation(node, parent) { - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node); - - if (node.rest) { - if (node.params.length) { - this.token(","); - this.space(); - } - this.token("..."); - this.print(node.rest, node); - } - - this.token(")"); - - if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { - this.token(":"); - } else { - this.space(); - this.token("=>"); - } - - this.space(); - this.print(node.returnType, node); -} - -function FunctionTypeParam(node) { - this.print(node.name, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.typeAnnotation, node); -} - -function InterfaceExtends(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); -} - -exports.ClassImplements = InterfaceExtends; -exports.GenericTypeAnnotation = InterfaceExtends; -function _interfaceish(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); - if (node.extends.length) { - this.space(); - this.word("extends"); - this.space(); - this.printList(node.extends, node); - } - if (node.mixins && node.mixins.length) { - this.space(); - this.word("mixins"); - this.space(); - this.printList(node.mixins, node); - } - this.space(); - this.print(node.body, node); -} - -function _variance(node) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } -} - -function InterfaceDeclaration(node) { - this.word("interface"); - this.space(); - this._interfaceish(node); -} - -function andSeparator() { - this.space(); - this.token("&"); - this.space(); -} - -function IntersectionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: andSeparator }); -} - -function MixedTypeAnnotation() { - this.word("mixed"); -} - -function EmptyTypeAnnotation() { - this.word("empty"); -} - -function NullableTypeAnnotation(node) { - this.token("?"); - this.print(node.typeAnnotation, node); -} - -function NumberTypeAnnotation() { - this.word("number"); -} - -function StringTypeAnnotation() { - this.word("string"); -} - -function ThisTypeAnnotation() { - this.word("this"); -} - -function TupleTypeAnnotation(node) { - this.token("["); - this.printList(node.types, node); - this.token("]"); -} - -function TypeofTypeAnnotation(node) { - this.word("typeof"); - this.space(); - this.print(node.argument, node); -} - -function TypeAlias(node) { - this.word("type"); - this.space(); - this.print(node.id, node); - this.print(node.typeParameters, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); - this.semicolon(); -} -function OpaqueType(node) { - this.word("opaque"); - this.space(); - this.word("type"); - this.space(); - this.print(node.id, node); - this.print(node.typeParameters, node); - if (node.supertype) { - this.token(":"); - this.space(); - this.print(node.supertype, node); - } - if (node.impltype) { - this.space(); - this.token("="); - this.space(); - this.print(node.impltype, node); - } - this.semicolon(); -} - -function TypeAnnotation(node) { - this.token(":"); - this.space(); - if (node.optional) this.token("?"); - this.print(node.typeAnnotation, node); -} - -function TypeParameter(node) { - this._variance(node); - - this.word(node.name); - - if (node.bound) { - this.print(node.bound, node); - } - - if (node.default) { - this.space(); - this.token("="); - this.space(); - this.print(node.default, node); - } -} - -function TypeParameterInstantiation(node) { - this.token("<"); - this.printList(node.params, node, {}); - this.token(">"); -} - -exports.TypeParameterDeclaration = TypeParameterInstantiation; -function ObjectTypeAnnotation(node) { - var _this = this; - - if (node.exact) { - this.token("{|"); - } else { - this.token("{"); - } - - var props = node.properties.concat(node.callProperties, node.indexers); - - if (props.length) { - this.space(); - - this.printJoin(props, node, { - addNewlines: function addNewlines(leading) { - if (leading && !props[0]) return 1; - }, - - indent: true, - statement: true, - iterator: function iterator() { - if (props.length !== 1) { - if (_this.format.flowCommaSeparator) { - _this.token(","); - } else { - _this.semicolon(); - } - _this.space(); - } - } - }); - - this.space(); - } - - if (node.exact) { - this.token("|}"); - } else { - this.token("}"); - } -} - -function ObjectTypeCallProperty(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this.print(node.value, node); -} - -function ObjectTypeIndexer(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this._variance(node); - this.token("["); - this.print(node.id, node); - this.token(":"); - this.space(); - this.print(node.key, node); - this.token("]"); - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ObjectTypeProperty(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this._variance(node); - this.print(node.key, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ObjectTypeSpreadProperty(node) { - this.token("..."); - this.print(node.argument, node); -} - -function QualifiedTypeIdentifier(node) { - this.print(node.qualification, node); - this.token("."); - this.print(node.id, node); -} - -function orSeparator() { - this.space(); - this.token("|"); - this.space(); -} - -function UnionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: orSeparator }); -} - -function TypeCastExpression(node) { - this.token("("); - this.print(node.expression, node); - this.print(node.typeAnnotation, node); - this.token(")"); -} - -function VoidTypeAnnotation() { - this.word("void"); -} -},{"./types":43,"babel-types":151}],38:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.JSXAttribute = JSXAttribute; -exports.JSXIdentifier = JSXIdentifier; -exports.JSXNamespacedName = JSXNamespacedName; -exports.JSXMemberExpression = JSXMemberExpression; -exports.JSXSpreadAttribute = JSXSpreadAttribute; -exports.JSXExpressionContainer = JSXExpressionContainer; -exports.JSXSpreadChild = JSXSpreadChild; -exports.JSXText = JSXText; -exports.JSXElement = JSXElement; -exports.JSXOpeningElement = JSXOpeningElement; -exports.JSXClosingElement = JSXClosingElement; -exports.JSXEmptyExpression = JSXEmptyExpression; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function JSXAttribute(node) { - this.print(node.name, node); - if (node.value) { - this.token("="); - this.print(node.value, node); - } -} - -function JSXIdentifier(node) { - this.word(node.name); -} - -function JSXNamespacedName(node) { - this.print(node.namespace, node); - this.token(":"); - this.print(node.name, node); -} - -function JSXMemberExpression(node) { - this.print(node.object, node); - this.token("."); - this.print(node.property, node); -} - -function JSXSpreadAttribute(node) { - this.token("{"); - this.token("..."); - this.print(node.argument, node); - this.token("}"); -} - -function JSXExpressionContainer(node) { - this.token("{"); - this.print(node.expression, node); - this.token("}"); -} - -function JSXSpreadChild(node) { - this.token("{"); - this.token("..."); - this.print(node.expression, node); - this.token("}"); -} - -function JSXText(node) { - this.token(node.value); -} - -function JSXElement(node) { - var open = node.openingElement; - this.print(open, node); - if (open.selfClosing) return; - - this.indent(); - for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var child = _ref; - - this.print(child, node); - } - this.dedent(); - - this.print(node.closingElement, node); -} - -function spaceSeparator() { - this.space(); -} - -function JSXOpeningElement(node) { - this.token("<"); - this.print(node.name, node); - if (node.attributes.length > 0) { - this.space(); - this.printJoin(node.attributes, node, { separator: spaceSeparator }); - } - if (node.selfClosing) { - this.space(); - this.token("/>"); - } else { - this.token(">"); - } -} - -function JSXClosingElement(node) { - this.token(""); -} - -function JSXEmptyExpression() {} -},{"babel-runtime/core-js/get-iterator":95}],39:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.FunctionDeclaration = undefined; -exports._params = _params; -exports._method = _method; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _params(node) { - var _this = this; - - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node, { - iterator: function iterator(node) { - if (node.optional) _this.token("?"); - _this.print(node.typeAnnotation, node); - } - }); - this.token(")"); - - if (node.returnType) { - this.print(node.returnType, node); - } -} - -function _method(node) { - var kind = node.kind; - var key = node.key; - - if (kind === "method" || kind === "init") { - if (node.generator) { - this.token("*"); - } - } - - if (kind === "get" || kind === "set") { - this.word(kind); - this.space(); - } - - if (node.async) { - this.word("async"); - this.space(); - } - - if (node.computed) { - this.token("["); - this.print(key, node); - this.token("]"); - } else { - this.print(key, node); - } - - this._params(node); - this.space(); - this.print(node.body, node); -} - -function FunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } - this.word("function"); - if (node.generator) this.token("*"); - - if (node.id) { - this.space(); - this.print(node.id, node); - } else { - this.space(); - } - - this._params(node); - this.space(); - this.print(node.body, node); -} - -exports.FunctionDeclaration = FunctionExpression; -function ArrowFunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } - - var firstParam = node.params[0]; - - if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { - this.print(firstParam, node); - } else { - this._params(node); - } - - this.space(); - this.token("=>"); - this.space(); - - this.print(node.body, node); -} - -function hasTypes(node, param) { - return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; -} -},{"babel-types":151}],40:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ImportSpecifier = ImportSpecifier; -exports.ImportDefaultSpecifier = ImportDefaultSpecifier; -exports.ExportDefaultSpecifier = ExportDefaultSpecifier; -exports.ExportSpecifier = ExportSpecifier; -exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; -exports.ExportAllDeclaration = ExportAllDeclaration; -exports.ExportNamedDeclaration = ExportNamedDeclaration; -exports.ExportDefaultDeclaration = ExportDefaultDeclaration; -exports.ImportDeclaration = ImportDeclaration; -exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function ImportSpecifier(node) { - if (node.importKind === "type" || node.importKind === "typeof") { - this.word(node.importKind); - this.space(); - } - - this.print(node.imported, node); - if (node.local && node.local.name !== node.imported.name) { - this.space(); - this.word("as"); - this.space(); - this.print(node.local, node); - } -} - -function ImportDefaultSpecifier(node) { - this.print(node.local, node); -} - -function ExportDefaultSpecifier(node) { - this.print(node.exported, node); -} - -function ExportSpecifier(node) { - this.print(node.local, node); - if (node.exported && node.local.name !== node.exported.name) { - this.space(); - this.word("as"); - this.space(); - this.print(node.exported, node); - } -} - -function ExportNamespaceSpecifier(node) { - this.token("*"); - this.space(); - this.word("as"); - this.space(); - this.print(node.exported, node); -} - -function ExportAllDeclaration(node) { - this.word("export"); - this.space(); - this.token("*"); - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); - this.semicolon(); -} - -function ExportNamedDeclaration() { - this.word("export"); - this.space(); - ExportDeclaration.apply(this, arguments); -} - -function ExportDefaultDeclaration() { - this.word("export"); - this.space(); - this.word("default"); - this.space(); - ExportDeclaration.apply(this, arguments); -} - -function ExportDeclaration(node) { - if (node.declaration) { - var declar = node.declaration; - this.print(declar, node); - if (!t.isStatement(declar)) this.semicolon(); - } else { - if (node.exportKind === "type") { - this.word("type"); - this.space(); - } - - var specifiers = node.specifiers.slice(0); - - var hasSpecial = false; - while (true) { - var first = specifiers[0]; - if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { - hasSpecial = true; - this.print(specifiers.shift(), node); - if (specifiers.length) { - this.token(","); - this.space(); - } - } else { - break; - } - } - - if (specifiers.length || !specifiers.length && !hasSpecial) { - this.token("{"); - if (specifiers.length) { - this.space(); - this.printList(specifiers, node); - this.space(); - } - this.token("}"); - } - - if (node.source) { - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); - } - - this.semicolon(); - } -} - -function ImportDeclaration(node) { - this.word("import"); - this.space(); - - if (node.importKind === "type" || node.importKind === "typeof") { - this.word(node.importKind); - this.space(); - } - - var specifiers = node.specifiers.slice(0); - if (specifiers && specifiers.length) { - while (true) { - var first = specifiers[0]; - if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { - this.print(specifiers.shift(), node); - if (specifiers.length) { - this.token(","); - this.space(); - } - } else { - break; - } - } - - if (specifiers.length) { - this.token("{"); - this.space(); - this.printList(specifiers, node); - this.space(); - this.token("}"); - } - - this.space(); - this.word("from"); - this.space(); - } - - this.print(node.source, node); - this.semicolon(); -} - -function ImportNamespaceSpecifier(node) { - this.token("*"); - this.space(); - this.word("as"); - this.space(); - this.print(node.local, node); -} -},{"babel-types":151}],41:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForAwaitStatement = exports.ForOfStatement = exports.ForInStatement = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.WithStatement = WithStatement; -exports.IfStatement = IfStatement; -exports.ForStatement = ForStatement; -exports.WhileStatement = WhileStatement; -exports.DoWhileStatement = DoWhileStatement; -exports.LabeledStatement = LabeledStatement; -exports.TryStatement = TryStatement; -exports.CatchClause = CatchClause; -exports.SwitchStatement = SwitchStatement; -exports.SwitchCase = SwitchCase; -exports.DebuggerStatement = DebuggerStatement; -exports.VariableDeclaration = VariableDeclaration; -exports.VariableDeclarator = VariableDeclarator; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function WithStatement(node) { - this.word("with"); - this.space(); - this.token("("); - this.print(node.object, node); - this.token(")"); - this.printBlock(node); -} - -function IfStatement(node) { - this.word("if"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.space(); - - var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); - if (needsBlock) { - this.token("{"); - this.newline(); - this.indent(); - } - - this.printAndIndentOnComments(node.consequent, node); - - if (needsBlock) { - this.dedent(); - this.newline(); - this.token("}"); - } - - if (node.alternate) { - if (this.endsWith("}")) this.space(); - this.word("else"); - this.space(); - this.printAndIndentOnComments(node.alternate, node); - } -} - -function getLastStatement(statement) { - if (!t.isStatement(statement.body)) return statement; - return getLastStatement(statement.body); -} - -function ForStatement(node) { - this.word("for"); - this.space(); - this.token("("); - - this.inForStatementInitCounter++; - this.print(node.init, node); - this.inForStatementInitCounter--; - this.token(";"); - - if (node.test) { - this.space(); - this.print(node.test, node); - } - this.token(";"); - - if (node.update) { - this.space(); - this.print(node.update, node); - } - - this.token(")"); - this.printBlock(node); -} - -function WhileStatement(node) { - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.printBlock(node); -} - -var buildForXStatement = function buildForXStatement(op) { - return function (node) { - this.word("for"); - this.space(); - if (op === "await") { - this.word("await"); - this.space(); - } - this.token("("); - - this.print(node.left, node); - this.space(); - this.word(op === "await" ? "of" : op); - this.space(); - this.print(node.right, node); - this.token(")"); - this.printBlock(node); - }; -}; - -var ForInStatement = exports.ForInStatement = buildForXStatement("in"); -var ForOfStatement = exports.ForOfStatement = buildForXStatement("of"); -var ForAwaitStatement = exports.ForAwaitStatement = buildForXStatement("await"); - -function DoWhileStatement(node) { - this.word("do"); - this.space(); - this.print(node.body, node); - this.space(); - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.semicolon(); -} - -function buildLabelStatement(prefix) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "label"; - - return function (node) { - this.word(prefix); - - var label = node[key]; - if (label) { - this.space(); - - var terminatorState = this.startTerminatorless(); - this.print(label, node); - this.endTerminatorless(terminatorState); - } - - this.semicolon(); - }; -} - -var ContinueStatement = exports.ContinueStatement = buildLabelStatement("continue"); -var ReturnStatement = exports.ReturnStatement = buildLabelStatement("return", "argument"); -var BreakStatement = exports.BreakStatement = buildLabelStatement("break"); -var ThrowStatement = exports.ThrowStatement = buildLabelStatement("throw", "argument"); - -function LabeledStatement(node) { - this.print(node.label, node); - this.token(":"); - this.space(); - this.print(node.body, node); -} - -function TryStatement(node) { - this.word("try"); - this.space(); - this.print(node.block, node); - this.space(); - - if (node.handlers) { - this.print(node.handlers[0], node); - } else { - this.print(node.handler, node); - } - - if (node.finalizer) { - this.space(); - this.word("finally"); - this.space(); - this.print(node.finalizer, node); - } -} - -function CatchClause(node) { - this.word("catch"); - this.space(); - this.token("("); - this.print(node.param, node); - this.token(")"); - this.space(); - this.print(node.body, node); -} - -function SwitchStatement(node) { - this.word("switch"); - this.space(); - this.token("("); - this.print(node.discriminant, node); - this.token(")"); - this.space(); - this.token("{"); - - this.printSequence(node.cases, node, { - indent: true, - addNewlines: function addNewlines(leading, cas) { - if (!leading && node.cases[node.cases.length - 1] === cas) return -1; - } - }); - - this.token("}"); -} - -function SwitchCase(node) { - if (node.test) { - this.word("case"); - this.space(); - this.print(node.test, node); - this.token(":"); - } else { - this.word("default"); - this.token(":"); - } - - if (node.consequent.length) { - this.newline(); - this.printSequence(node.consequent, node, { indent: true }); - } -} - -function DebuggerStatement() { - this.word("debugger"); - this.semicolon(); -} - -function variableDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { - this.space(true); - } -} - -function constDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { - this.space(true); - } -} - -function VariableDeclaration(node, parent) { - this.word(node.kind); - this.space(); - - var hasInits = false; - - if (!t.isFor(parent)) { - for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var declar = _ref; - - if (declar.init) { - hasInits = true; - } - } - } - - var separator = void 0; - if (hasInits) { - separator = node.kind === "const" ? constDeclarationIdent : variableDeclarationIdent; - } - - this.printList(node.declarations, node, { separator: separator }); - - if (t.isFor(parent)) { - if (parent.left === node || parent.init === node) return; - } - - this.semicolon(); -} - -function VariableDeclarator(node) { - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - if (node.init) { - this.space(); - this.token("="); - this.space(); - this.print(node.init, node); - } -} -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],42:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.TaggedTemplateExpression = TaggedTemplateExpression; -exports.TemplateElement = TemplateElement; -exports.TemplateLiteral = TemplateLiteral; -function TaggedTemplateExpression(node) { - this.print(node.tag, node); - this.print(node.quasi, node); -} - -function TemplateElement(node, parent) { - var isFirst = parent.quasis[0] === node; - var isLast = parent.quasis[parent.quasis.length - 1] === node; - - var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); - - this.token(value); -} - -function TemplateLiteral(node) { - var quasis = node.quasis; - - for (var i = 0; i < quasis.length; i++) { - this.print(quasis[i], node); - - if (i + 1 < quasis.length) { - this.print(node.expressions[i], node); - } - } -} -},{}],43:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ArrayPattern = exports.ObjectPattern = exports.RestProperty = exports.SpreadProperty = exports.SpreadElement = undefined; -exports.Identifier = Identifier; -exports.RestElement = RestElement; -exports.ObjectExpression = ObjectExpression; -exports.ObjectMethod = ObjectMethod; -exports.ObjectProperty = ObjectProperty; -exports.ArrayExpression = ArrayExpression; -exports.RegExpLiteral = RegExpLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.NumericLiteral = NumericLiteral; -exports.StringLiteral = StringLiteral; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _jsesc = require("jsesc"); - -var _jsesc2 = _interopRequireDefault(_jsesc); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function Identifier(node) { - if (node.variance) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } - } - - this.word(node.name); -} - -function RestElement(node) { - this.token("..."); - this.print(node.argument, node); -} - -exports.SpreadElement = RestElement; -exports.SpreadProperty = RestElement; -exports.RestProperty = RestElement; -function ObjectExpression(node) { - var props = node.properties; - - this.token("{"); - this.printInnerComments(node); - - if (props.length) { - this.space(); - this.printList(props, node, { indent: true, statement: true }); - this.space(); - } - - this.token("}"); -} - -exports.ObjectPattern = ObjectExpression; -function ObjectMethod(node) { - this.printJoin(node.decorators, node); - this._method(node); -} - -function ObjectProperty(node) { - this.printJoin(node.decorators, node); - - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { - this.print(node.value, node); - return; - } - - this.print(node.key, node); - - if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { - return; - } - } - - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ArrayExpression(node) { - var elems = node.elements; - var len = elems.length; - - this.token("["); - this.printInnerComments(node); - - for (var i = 0; i < elems.length; i++) { - var elem = elems[i]; - if (elem) { - if (i > 0) this.space(); - this.print(elem, node); - if (i < len - 1) this.token(","); - } else { - this.token(","); - } - } - - this.token("]"); -} - -exports.ArrayPattern = ArrayExpression; -function RegExpLiteral(node) { - this.word("/" + node.pattern + "/" + node.flags); -} - -function BooleanLiteral(node) { - this.word(node.value ? "true" : "false"); -} - -function NullLiteral() { - this.word("null"); -} - -function NumericLiteral(node) { - var raw = this.getPossibleRaw(node); - var value = node.value + ""; - if (raw == null) { - this.number(value); - } else if (this.format.minified) { - this.number(raw.length < value.length ? raw : value); - } else { - this.number(raw); - } -} - -function StringLiteral(node, parent) { - var raw = this.getPossibleRaw(node); - if (!this.format.minified && raw != null) { - this.token(raw); - return; - } - - var opts = { - quotes: t.isJSX(parent) ? "double" : this.format.quotes, - wrap: true - }; - if (this.format.jsonCompatibleStrings) { - opts.json = true; - } - var val = (0, _jsesc2.default)(node.value, opts); - - return this.token(val); -} -},{"babel-types":151,"jsesc":296}],44:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.CodeGenerator = undefined; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -exports.default = function (ast, opts, code) { - var gen = new Generator(ast, opts, code); - return gen.generate(); -}; - -var _detectIndent = require("detect-indent"); - -var _detectIndent2 = _interopRequireDefault(_detectIndent); - -var _sourceMap = require("./source-map"); - -var _sourceMap2 = _interopRequireDefault(_sourceMap); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _printer = require("./printer"); - -var _printer2 = _interopRequireDefault(_printer); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Generator = function (_Printer) { - (0, _inherits3.default)(Generator, _Printer); - - function Generator(ast) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var code = arguments[2]; - (0, _classCallCheck3.default)(this, Generator); - - var tokens = ast.tokens || []; - var format = normalizeOptions(code, opts, tokens); - var map = opts.sourceMaps ? new _sourceMap2.default(opts, code) : null; - - var _this = (0, _possibleConstructorReturn3.default)(this, _Printer.call(this, format, map, tokens)); - - _this.ast = ast; - return _this; - } - - Generator.prototype.generate = function generate() { - return _Printer.prototype.generate.call(this, this.ast); - }; - - return Generator; -}(_printer2.default); - -function normalizeOptions(code, opts, tokens) { - var style = " "; - if (code && typeof code === "string") { - var indent = (0, _detectIndent2.default)(code).indent; - if (indent && indent !== " ") style = indent; - } - - var format = { - auxiliaryCommentBefore: opts.auxiliaryCommentBefore, - auxiliaryCommentAfter: opts.auxiliaryCommentAfter, - shouldPrintComment: opts.shouldPrintComment, - retainLines: opts.retainLines, - retainFunctionParens: opts.retainFunctionParens, - comments: opts.comments == null || opts.comments, - compact: opts.compact, - minified: opts.minified, - concise: opts.concise, - quotes: opts.quotes || findCommonStringDelimiter(code, tokens), - jsonCompatibleStrings: opts.jsonCompatibleStrings, - indent: { - adjustMultilineComment: true, - style: style, - base: 0 - }, - flowCommaSeparator: opts.flowCommaSeparator - }; - - if (format.minified) { - format.compact = true; - - format.shouldPrintComment = format.shouldPrintComment || function () { - return format.comments; - }; - } else { - format.shouldPrintComment = format.shouldPrintComment || function (value) { - return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; - }; - } - - if (format.compact === "auto") { - format.compact = code.length > 500000; - - if (format.compact) { - console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "500KB")); - } - } - - if (format.compact) { - format.indent.adjustMultilineComment = false; - } - - return format; -} - -function findCommonStringDelimiter(code, tokens) { - var DEFAULT_STRING_DELIMITER = "double"; - if (!code) { - return DEFAULT_STRING_DELIMITER; - } - - var occurrences = { - single: 0, - double: 0 - }; - - var checked = 0; - - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token.type.label !== "string") continue; - - var raw = code.slice(token.start, token.end); - if (raw[0] === "'") { - occurrences.single++; - } else { - occurrences.double++; - } - - checked++; - if (checked >= 3) break; - } - if (occurrences.single > occurrences.double) { - return "single"; - } else { - return "double"; - } -} - -var CodeGenerator = exports.CodeGenerator = function () { - function CodeGenerator(ast, opts, code) { - (0, _classCallCheck3.default)(this, CodeGenerator); - - this._generator = new Generator(ast, opts, code); - } - - CodeGenerator.prototype.generate = function generate() { - return this._generator.generate(); - }; - - return CodeGenerator; -}(); -},{"./printer":48,"./source-map":49,"babel-messages":61,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"detect-indent":282}],45:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -exports.needsWhitespace = needsWhitespace; -exports.needsWhitespaceBefore = needsWhitespaceBefore; -exports.needsWhitespaceAfter = needsWhitespaceAfter; -exports.needsParens = needsParens; - -var _whitespace = require("./whitespace"); - -var _whitespace2 = _interopRequireDefault(_whitespace); - -var _parentheses = require("./parentheses"); - -var parens = _interopRequireWildcard(_parentheses); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function expandAliases(obj) { - var newObj = {}; - - function add(type, func) { - var fn = newObj[type]; - newObj[type] = fn ? function (node, parent, stack) { - var result = fn(node, parent, stack); - - return result == null ? func(node, parent, stack) : result; - } : func; - } - - for (var _iterator = (0, _keys2.default)(obj), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var type = _ref; - - - var aliases = t.FLIPPED_ALIAS_KEYS[type]; - if (aliases) { - for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var alias = _ref2; - - add(alias, obj[type]); - } - } else { - add(type, obj[type]); - } - } - - return newObj; -} - -var expandedParens = expandAliases(parens); -var expandedWhitespaceNodes = expandAliases(_whitespace2.default.nodes); -var expandedWhitespaceList = expandAliases(_whitespace2.default.list); - -function find(obj, node, parent, printStack) { - var fn = obj[node.type]; - return fn ? fn(node, parent, printStack) : null; -} - -function isOrHasCallExpression(node) { - if (t.isCallExpression(node)) { - return true; - } - - if (t.isMemberExpression(node)) { - return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); - } else { - return false; - } -} - -function needsWhitespace(node, parent, type) { - if (!node) return 0; - - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - var linesInfo = find(expandedWhitespaceNodes, node, parent); - - if (!linesInfo) { - var items = find(expandedWhitespaceList, node, parent); - if (items) { - for (var i = 0; i < items.length; i++) { - linesInfo = needsWhitespace(items[i], node, type); - if (linesInfo) break; - } - } - } - - return linesInfo && linesInfo[type] || 0; -} - -function needsWhitespaceBefore(node, parent) { - return needsWhitespace(node, parent, "before"); -} - -function needsWhitespaceAfter(node, parent) { - return needsWhitespace(node, parent, "after"); -} - -function needsParens(node, parent, printStack) { - if (!parent) return false; - - if (t.isNewExpression(parent) && parent.callee === node) { - if (isOrHasCallExpression(node)) return true; - } - - return find(expandedParens, node, parent, printStack); -} -},{"./parentheses":46,"./whitespace":47,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/keys":102,"babel-types":151}],46:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.AwaitExpression = exports.FunctionTypeAnnotation = undefined; -exports.NullableTypeAnnotation = NullableTypeAnnotation; -exports.UpdateExpression = UpdateExpression; -exports.ObjectExpression = ObjectExpression; -exports.DoExpression = DoExpression; -exports.Binary = Binary; -exports.BinaryExpression = BinaryExpression; -exports.SequenceExpression = SequenceExpression; -exports.YieldExpression = YieldExpression; -exports.ClassExpression = ClassExpression; -exports.UnaryLike = UnaryLike; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.AssignmentExpression = AssignmentExpression; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var PRECEDENCE = { - "||": 0, - "&&": 1, - "|": 2, - "^": 3, - "&": 4, - "==": 5, - "===": 5, - "!=": 5, - "!==": 5, - "<": 6, - ">": 6, - "<=": 6, - ">=": 6, - in: 6, - instanceof: 6, - ">>": 7, - "<<": 7, - ">>>": 7, - "+": 8, - "-": 8, - "*": 9, - "/": 9, - "%": 9, - "**": 10 -}; - -function NullableTypeAnnotation(node, parent) { - return t.isArrayTypeAnnotation(parent); -} - -exports.FunctionTypeAnnotation = NullableTypeAnnotation; -function UpdateExpression(node, parent) { - return t.isMemberExpression(parent) && parent.object === node; -} - -function ObjectExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerArrow: true }); -} - -function DoExpression(node, parent, printStack) { - return isFirstInStatement(printStack); -} - -function Binary(node, parent) { - if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isUnaryLike(parent) || t.isMemberExpression(parent) && parent.object === node || t.isAwaitExpression(parent)) { - return true; - } - - if (t.isBinary(parent)) { - var parentOp = parent.operator; - var parentPos = PRECEDENCE[parentOp]; - - var nodeOp = node.operator; - var nodePos = PRECEDENCE[nodeOp]; - - if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent) || parentPos > nodePos) { - return true; - } - } - - return false; -} - -function BinaryExpression(node, parent) { - return node.operator === "in" && (t.isVariableDeclarator(parent) || t.isFor(parent)); -} - -function SequenceExpression(node, parent) { - - if (t.isForStatement(parent) || t.isThrowStatement(parent) || t.isReturnStatement(parent) || t.isIfStatement(parent) && parent.test === node || t.isWhileStatement(parent) && parent.test === node || t.isForInStatement(parent) && parent.right === node || t.isSwitchStatement(parent) && parent.discriminant === node || t.isExpressionStatement(parent) && parent.expression === node) { - return false; - } - - return true; -} - -function YieldExpression(node, parent) { - return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) && node === parent.test; -} - -exports.AwaitExpression = YieldExpression; -function ClassExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); -} - -function UnaryLike(node, parent) { - return t.isMemberExpression(parent, { object: node }) || t.isCallExpression(parent, { callee: node }) || t.isNewExpression(parent, { callee: node }); -} - -function FunctionExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); -} - -function ArrowFunctionExpression(node, parent) { - if (t.isExportDeclaration(parent) || t.isBinaryExpression(parent) || t.isLogicalExpression(parent) || t.isUnaryExpression(parent) || t.isTaggedTemplateExpression(parent)) { - return true; - } - - return UnaryLike(node, parent); -} - -function ConditionalExpression(node, parent) { - if (t.isUnaryLike(parent) || t.isBinary(parent) || t.isConditionalExpression(parent, { test: node }) || t.isAwaitExpression(parent)) { - return true; - } - - return UnaryLike(node, parent); -} - -function AssignmentExpression(node) { - if (t.isObjectPattern(node.left)) { - return true; - } else { - return ConditionalExpression.apply(undefined, arguments); - } -} - -function isFirstInStatement(printStack) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$considerArrow = _ref.considerArrow, - considerArrow = _ref$considerArrow === undefined ? false : _ref$considerArrow, - _ref$considerDefaultE = _ref.considerDefaultExports, - considerDefaultExports = _ref$considerDefaultE === undefined ? false : _ref$considerDefaultE; - - var i = printStack.length - 1; - var node = printStack[i]; - i--; - var parent = printStack[i]; - while (i > 0) { - if (t.isExpressionStatement(parent, { expression: node }) || t.isTaggedTemplateExpression(parent) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: node }) || considerArrow && t.isArrowFunctionExpression(parent, { body: node })) { - return true; - } - - if (t.isCallExpression(parent, { callee: node }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { object: node }) || t.isConditional(parent, { test: node }) || t.isBinary(parent, { left: node }) || t.isAssignmentExpression(parent, { left: node })) { - node = parent; - i--; - parent = printStack[i]; - } else { - return false; - } - } - - return false; -} -},{"babel-types":151}],47:[function(require,module,exports){ -"use strict"; - -var _map = require("lodash/map"); - -var _map2 = _interopRequireDefault(_map); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function crawl(node) { - var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - if (t.isMemberExpression(node)) { - crawl(node.object, state); - if (node.computed) crawl(node.property, state); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - crawl(node.left, state); - crawl(node.right, state); - } else if (t.isCallExpression(node)) { - state.hasCall = true; - crawl(node.callee, state); - } else if (t.isFunction(node)) { - state.hasFunction = true; - } else if (t.isIdentifier(node)) { - state.hasHelper = state.hasHelper || isHelper(node.callee); - } - - return state; -} - -function isHelper(node) { - if (t.isMemberExpression(node)) { - return isHelper(node.object) || isHelper(node.property); - } else if (t.isIdentifier(node)) { - return node.name === "require" || node.name[0] === "_"; - } else if (t.isCallExpression(node)) { - return isHelper(node.callee); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); - } else { - return false; - } -} - -function isType(node) { - return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); -} - -exports.nodes = { - AssignmentExpression: function AssignmentExpression(node) { - var state = crawl(node.right); - if (state.hasCall && state.hasHelper || state.hasFunction) { - return { - before: state.hasFunction, - after: true - }; - } - }, - SwitchCase: function SwitchCase(node, parent) { - return { - before: node.consequent.length || parent.cases[0] === node - }; - }, - LogicalExpression: function LogicalExpression(node) { - if (t.isFunction(node.left) || t.isFunction(node.right)) { - return { - after: true - }; - } - }, - Literal: function Literal(node) { - if (node.value === "use strict") { - return { - after: true - }; - } - }, - CallExpression: function CallExpression(node) { - if (t.isFunction(node.callee) || isHelper(node)) { - return { - before: true, - after: true - }; - } - }, - VariableDeclaration: function VariableDeclaration(node) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - - var enabled = isHelper(declar.id) && !isType(declar.init); - if (!enabled) { - var state = crawl(declar.init); - enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; - } - - if (enabled) { - return { - before: true, - after: true - }; - } - } - }, - IfStatement: function IfStatement(node) { - if (t.isBlockStatement(node.consequent)) { - return { - before: true, - after: true - }; - } - } -}; - -exports.nodes.ObjectProperty = exports.nodes.ObjectTypeProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) { - if (parent.properties[0] === node) { - return { - before: true - }; - } -}; - -exports.list = { - VariableDeclaration: function VariableDeclaration(node) { - return (0, _map2.default)(node.declarations, "init"); - }, - ArrayExpression: function ArrayExpression(node) { - return node.elements; - }, - ObjectExpression: function ObjectExpression(node) { - return node.properties; - } -}; - -[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function (_ref) { - var type = _ref[0], - amounts = _ref[1]; - - if (typeof amounts === "boolean") { - amounts = { after: amounts, before: amounts }; - } - [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { - exports.nodes[type] = function () { - return amounts; - }; - }); -}); -},{"babel-types":151,"lodash/map":500}],48:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _weakSet = require("babel-runtime/core-js/weak-set"); - -var _weakSet2 = _interopRequireDefault(_weakSet); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _find = require("lodash/find"); - -var _find2 = _interopRequireDefault(_find); - -var _findLast = require("lodash/findLast"); - -var _findLast2 = _interopRequireDefault(_findLast); - -var _isInteger = require("lodash/isInteger"); - -var _isInteger2 = _interopRequireDefault(_isInteger); - -var _repeat = require("lodash/repeat"); - -var _repeat2 = _interopRequireDefault(_repeat); - -var _buffer = require("./buffer"); - -var _buffer2 = _interopRequireDefault(_buffer); - -var _node = require("./node"); - -var n = _interopRequireWildcard(_node); - -var _whitespace = require("./whitespace"); - -var _whitespace2 = _interopRequireDefault(_whitespace); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SCIENTIFIC_NOTATION = /e/i; -var ZERO_DECIMAL_INTEGER = /\.0+$/; -var NON_DECIMAL_LITERAL = /^0[box]/; - -var Printer = function () { - function Printer(format, map, tokens) { - (0, _classCallCheck3.default)(this, Printer); - this.inForStatementInitCounter = 0; - this._printStack = []; - this._indent = 0; - this._insideAux = false; - this._printedCommentStarts = {}; - this._parenPushNewlineState = null; - this._printAuxAfterOnNextUserNode = false; - this._printedComments = new _weakSet2.default(); - this._endsWithInteger = false; - this._endsWithWord = false; - - this.format = format || {}; - this._buf = new _buffer2.default(map); - this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null; - } - - Printer.prototype.generate = function generate(ast) { - this.print(ast); - this._maybeAddAuxComment(); - - return this._buf.get(); - }; - - Printer.prototype.indent = function indent() { - if (this.format.compact || this.format.concise) return; - - this._indent++; - }; - - Printer.prototype.dedent = function dedent() { - if (this.format.compact || this.format.concise) return; - - this._indent--; - }; - - Printer.prototype.semicolon = function semicolon() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - this._maybeAddAuxComment(); - this._append(";", !force); - }; - - Printer.prototype.rightBrace = function rightBrace() { - if (this.format.minified) { - this._buf.removeLastSemicolon(); - } - this.token("}"); - }; - - Printer.prototype.space = function space() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - if (this.format.compact) return; - - if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { - this._space(); - } - }; - - Printer.prototype.word = function word(str) { - if (this._endsWithWord) this._space(); - - this._maybeAddAuxComment(); - this._append(str); - - this._endsWithWord = true; - }; - - Printer.prototype.number = function number(str) { - this.word(str); - - this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; - }; - - Printer.prototype.token = function token(str) { - if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { - this._space(); - } - - this._maybeAddAuxComment(); - this._append(str); - }; - - Printer.prototype.newline = function newline(i) { - if (this.format.retainLines || this.format.compact) return; - - if (this.format.concise) { - this.space(); - return; - } - - if (this.endsWith("\n\n")) return; - - if (typeof i !== "number") i = 1; - - i = Math.min(2, i); - if (this.endsWith("{\n") || this.endsWith(":\n")) i--; - if (i <= 0) return; - - for (var j = 0; j < i; j++) { - this._newline(); - } - }; - - Printer.prototype.endsWith = function endsWith(str) { - return this._buf.endsWith(str); - }; - - Printer.prototype.removeTrailingNewline = function removeTrailingNewline() { - this._buf.removeTrailingNewline(); - }; - - Printer.prototype.source = function source(prop, loc) { - this._catchUp(prop, loc); - - this._buf.source(prop, loc); - }; - - Printer.prototype.withSource = function withSource(prop, loc, cb) { - this._catchUp(prop, loc); - - this._buf.withSource(prop, loc, cb); - }; - - Printer.prototype._space = function _space() { - this._append(" ", true); - }; - - Printer.prototype._newline = function _newline() { - this._append("\n", true); - }; - - Printer.prototype._append = function _append(str) { - var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - this._maybeAddParen(str); - this._maybeIndent(str); - - if (queue) this._buf.queue(str);else this._buf.append(str); - - this._endsWithWord = false; - this._endsWithInteger = false; - }; - - Printer.prototype._maybeIndent = function _maybeIndent(str) { - if (this._indent && this.endsWith("\n") && str[0] !== "\n") { - this._buf.queue(this._getIndent()); - } - }; - - Printer.prototype._maybeAddParen = function _maybeAddParen(str) { - var parenPushNewlineState = this._parenPushNewlineState; - if (!parenPushNewlineState) return; - this._parenPushNewlineState = null; - - var i = void 0; - for (i = 0; i < str.length && str[i] === " "; i++) { - continue; - }if (i === str.length) return; - - var cha = str[i]; - if (cha === "\n" || cha === "/") { - this.token("("); - this.indent(); - parenPushNewlineState.printed = true; - } - }; - - Printer.prototype._catchUp = function _catchUp(prop, loc) { - if (!this.format.retainLines) return; - - var pos = loc ? loc[prop] : null; - if (pos && pos.line !== null) { - var count = pos.line - this._buf.getCurrentLine(); - - for (var i = 0; i < count; i++) { - this._newline(); - } - } - }; - - Printer.prototype._getIndent = function _getIndent() { - return (0, _repeat2.default)(this.format.indent.style, this._indent); - }; - - Printer.prototype.startTerminatorless = function startTerminatorless() { - return this._parenPushNewlineState = { - printed: false - }; - }; - - Printer.prototype.endTerminatorless = function endTerminatorless(state) { - if (state.printed) { - this.dedent(); - this.newline(); - this.token(")"); - } - }; - - Printer.prototype.print = function print(node, parent) { - var _this = this; - - if (!node) return; - - var oldConcise = this.format.concise; - if (node._compact) { - this.format.concise = true; - } - - var printMethod = this[node.type]; - if (!printMethod) { - throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name)); - } - - this._printStack.push(node); - - var oldInAux = this._insideAux; - this._insideAux = !node.loc; - this._maybeAddAuxComment(this._insideAux && !oldInAux); - - var needsParens = n.needsParens(node, parent, this._printStack); - if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { - needsParens = true; - } - if (needsParens) this.token("("); - - this._printLeadingComments(node, parent); - - var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; - this.withSource("start", loc, function () { - _this[node.type](node, parent); - }); - - this._printTrailingComments(node, parent); - - if (needsParens) this.token(")"); - - this._printStack.pop(); - - this.format.concise = oldConcise; - this._insideAux = oldInAux; - }; - - Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) { - if (enteredPositionlessNode) this._printAuxBeforeComment(); - if (!this._insideAux) this._printAuxAfterComment(); - }; - - Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() { - if (this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = true; - - var comment = this.format.auxiliaryCommentBefore; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; - - Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() { - if (!this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = false; - - var comment = this.format.auxiliaryCommentAfter; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; - - Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { - var extra = node.extra; - if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { - return extra.raw; - } - }; - - Printer.prototype.printJoin = function printJoin(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - if (!nodes || !nodes.length) return; - - if (opts.indent) this.indent(); - - var newlineOpts = { - addNewlines: opts.addNewlines - }; - - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; - - if (opts.statement) this._printNewline(true, node, parent, newlineOpts); - - this.print(node, parent); - - if (opts.iterator) { - opts.iterator(node, i); - } - - if (opts.separator && i < nodes.length - 1) { - opts.separator.call(this); - } - - if (opts.statement) this._printNewline(false, node, parent, newlineOpts); - } - - if (opts.indent) this.dedent(); - }; - - Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) { - var indent = !!node.leadingComments; - if (indent) this.indent(); - this.print(node, parent); - if (indent) this.dedent(); - }; - - Printer.prototype.printBlock = function printBlock(parent) { - var node = parent.body; - - if (!t.isEmptyStatement(node)) { - this.space(); - } - - this.print(node, parent); - }; - - Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) { - this._printComments(this._getComments(false, node, parent)); - }; - - Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) { - this._printComments(this._getComments(true, node, parent)); - }; - - Printer.prototype.printInnerComments = function printInnerComments(node) { - var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - if (!node.innerComments) return; - if (indent) this.indent(); - this._printComments(node.innerComments); - if (indent) this.dedent(); - }; - - Printer.prototype.printSequence = function printSequence(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - opts.statement = true; - return this.printJoin(nodes, parent, opts); - }; - - Printer.prototype.printList = function printList(items, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - if (opts.separator == null) { - opts.separator = commaSeparator; - } - - return this.printJoin(items, parent, opts); - }; - - Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { - var _this2 = this; - - if (this.format.retainLines || this.format.compact) return; - - if (this.format.concise) { - this.space(); - return; - } - - var lines = 0; - - if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) { - if (leading) { - var _comments = node.leadingComments; - var _comment = _comments && (0, _find2.default)(_comments, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); - - lines = this._whitespace.getNewlinesBefore(_comment || node); - } else { - var _comments2 = node.trailingComments; - var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); - - lines = this._whitespace.getNewlinesAfter(_comment2 || node); - } - } else { - if (!leading) lines++; - if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; - - var needs = n.needsWhitespaceAfter; - if (leading) needs = n.needsWhitespaceBefore; - if (needs(node, parent)) lines++; - - if (!this._buf.hasContent()) lines = 0; - } - - this.newline(lines); - }; - - Printer.prototype._getComments = function _getComments(leading, node) { - return node && (leading ? node.leadingComments : node.trailingComments) || []; - }; - - Printer.prototype._printComment = function _printComment(comment) { - var _this3 = this; - - if (!this.format.shouldPrintComment(comment.value)) return; - - if (comment.ignore) return; - - if (this._printedComments.has(comment)) return; - this._printedComments.add(comment); - - if (comment.start != null) { - if (this._printedCommentStarts[comment.start]) return; - this._printedCommentStarts[comment.start] = true; - } - - this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0); - - if (!this.endsWith("[") && !this.endsWith("{")) this.space(); - - var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/"; - - if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { - var offset = comment.loc && comment.loc.start.column; - if (offset) { - var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); - val = val.replace(newlineRegex, "\n"); - } - - var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); - val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize)); - } - - this.withSource("start", comment.loc, function () { - _this3._append(val); - }); - - this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0)); - }; - - Printer.prototype._printComments = function _printComments(comments) { - if (!comments || !comments.length) return; - - for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _comment3 = _ref; - - this._printComment(_comment3); - } - }; - - return Printer; -}(); - -exports.default = Printer; - - -function commaSeparator() { - this.token(","); - this.space(); -} - -var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")]; -for (var _i2 = 0; _i2 < _arr.length; _i2++) { - var generator = _arr[_i2]; - (0, _assign2.default)(Printer.prototype, generator); -} -module.exports = exports["default"]; -},{"./buffer":33,"./generators/base":34,"./generators/classes":35,"./generators/expressions":36,"./generators/flow":37,"./generators/jsx":38,"./generators/methods":39,"./generators/modules":40,"./generators/statements":41,"./generators/template-literals":42,"./generators/types":43,"./node":45,"./whitespace":50,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/object/assign":99,"babel-runtime/core-js/weak-set":108,"babel-runtime/helpers/classCallCheck":109,"babel-types":151,"lodash/find":474,"lodash/findLast":476,"lodash/isInteger":489,"lodash/repeat":507}],49:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _sourceMap = require("source-map"); - -var _sourceMap2 = _interopRequireDefault(_sourceMap); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SourceMap = function () { - function SourceMap(opts, code) { - (0, _classCallCheck3.default)(this, SourceMap); - - this._cachedMap = null; - this._code = code; - this._opts = opts; - this._rawMappings = []; - } - - SourceMap.prototype.get = function get() { - if (!this._cachedMap) { - var map = this._cachedMap = new _sourceMap2.default.SourceMapGenerator({ - file: this._opts.sourceMapTarget, - sourceRoot: this._opts.sourceRoot - }); - - var code = this._code; - if (typeof code === "string") { - map.setSourceContent(this._opts.sourceFileName, code); - } else if ((typeof code === "undefined" ? "undefined" : (0, _typeof3.default)(code)) === "object") { - (0, _keys2.default)(code).forEach(function (sourceFileName) { - map.setSourceContent(sourceFileName, code[sourceFileName]); - }); - } - - this._rawMappings.forEach(map.addMapping, map); - } - - return this._cachedMap.toJSON(); - }; - - SourceMap.prototype.getRawMappings = function getRawMappings() { - return this._rawMappings.slice(); - }; - - SourceMap.prototype.mark = function mark(generatedLine, generatedColumn, line, column, identifierName, filename) { - if (this._lastGenLine !== generatedLine && line === null) return; - - if (this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { - return; - } - - this._cachedMap = null; - this._lastGenLine = generatedLine; - this._lastSourceLine = line; - this._lastSourceColumn = column; - - this._rawMappings.push({ - name: identifierName || undefined, - generated: { - line: generatedLine, - column: generatedColumn - }, - source: line == null ? undefined : filename || this._opts.sourceFileName, - original: line == null ? undefined : { - line: line, - column: column - } - }); - }; - - return SourceMap; -}(); - -exports.default = SourceMap; -module.exports = exports["default"]; -},{"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/typeof":113,"source-map":552}],50:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Whitespace = function () { - function Whitespace(tokens) { - (0, _classCallCheck3.default)(this, Whitespace); - - this.tokens = tokens; - this.used = {}; - } - - Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; - - var index = this._findToken(function (token) { - return token.start - node.start; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.start === tokens[index - 1].start) { - --index; - }startToken = tokens[index - 1]; - endToken = tokens[index]; - } - - return this._getNewlinesBetween(startToken, endToken); - }; - - Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; - - var index = this._findToken(function (token) { - return token.end - node.end; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.end === tokens[index - 1].end) { - --index; - }startToken = tokens[index]; - endToken = tokens[index + 1]; - if (endToken.type.label === ",") endToken = tokens[index + 2]; - } - - if (endToken && endToken.type.label === "eof") { - return 1; - } else { - return this._getNewlinesBetween(startToken, endToken); - } - }; - - Whitespace.prototype._getNewlinesBetween = function _getNewlinesBetween(startToken, endToken) { - if (!endToken || !endToken.loc) return 0; - - var start = startToken ? startToken.loc.end.line : 1; - var end = endToken.loc.start.line; - var lines = 0; - - for (var line = start; line < end; line++) { - if (typeof this.used[line] === "undefined") { - this.used[line] = true; - lines++; - } - } - - return lines; - }; - - Whitespace.prototype._findToken = function _findToken(test, start, end) { - if (start >= end) return -1; - var middle = start + end >>> 1; - var match = test(this.tokens[middle]); - if (match < 0) { - return this._findToken(test, middle + 1, end); - } else if (match > 0) { - return this._findToken(test, start, middle); - } else if (match === 0) { - return middle; - } - return -1; - }; - - return Whitespace; -}(); - -exports.default = Whitespace; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109}],51:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (path) { - var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : path.scope; - var node = path.node; - - var container = t.functionExpression(null, [], node.body, node.generator, node.async); - - var callee = container; - var args = []; - - (0, _babelHelperHoistVariables2.default)(path, function (id) { - return scope.push({ id: id }); - }); - - var state = { - foundThis: false, - foundArguments: false - }; - - path.traverse(visitor, state); - - if (state.foundArguments) { - callee = t.memberExpression(container, t.identifier("apply")); - args = []; - - if (state.foundThis) { - args.push(t.thisExpression()); - } - - if (state.foundArguments) { - if (!state.foundThis) args.push(t.nullLiteral()); - args.push(t.identifier("arguments")); - } - } - - var call = t.callExpression(callee, args); - if (node.generator) call = t.yieldExpression(call, true); - - return t.returnStatement(call); -}; - -var _babelHelperHoistVariables = require("babel-helper-hoist-variables"); - -var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var visitor = { - enter: function enter(path, state) { - if (path.isThisExpression()) { - state.foundThis = true; - } - - if (path.isReferencedIdentifier({ name: "arguments" })) { - state.foundArguments = true; - } - }, - Function: function Function(path) { - path.skip(); - } -}; - -module.exports = exports["default"]; -},{"babel-helper-hoist-variables":55,"babel-types":151}],52:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -exports.push = push; -exports.hasComputed = hasComputed; -exports.toComputedObjectFromClass = toComputedObjectFromClass; -exports.toClassObject = toClassObject; -exports.toDefineObject = toDefineObject; - -var _babelHelperFunctionName = require("babel-helper-function-name"); - -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); - -var _has = require("lodash/has"); - -var _has2 = _interopRequireDefault(_has); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toKind(node) { - if (t.isClassMethod(node) || t.isObjectMethod(node)) { - if (node.kind === "get" || node.kind === "set") { - return node.kind; - } - } - - return "value"; -} - -function push(mutatorMap, node, kind, file, scope) { - var alias = t.toKeyAlias(node); - - var map = {}; - if ((0, _has2.default)(mutatorMap, alias)) map = mutatorMap[alias]; - mutatorMap[alias] = map; - - map._inherits = map._inherits || []; - map._inherits.push(node); - - map._key = node.key; - - if (node.computed) { - map._computed = true; - } - - if (node.decorators) { - var decorators = map.decorators = map.decorators || t.arrayExpression([]); - decorators.elements = decorators.elements.concat(node.decorators.map(function (dec) { - return dec.expression; - }).reverse()); - } - - if (map.value || map.initializer) { - throw file.buildCodeFrameError(node, "Key conflict with sibling node"); - } - - var key = void 0, - value = void 0; - - if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) { - key = t.toComputedKey(node, node.key); - } - - if (t.isObjectProperty(node) || t.isClassProperty(node)) { - value = node.value; - } else if (t.isObjectMethod(node) || t.isClassMethod(node)) { - value = t.functionExpression(null, node.params, node.body, node.generator, node.async); - value.returnType = node.returnType; - } - - var inheritedKind = toKind(node); - if (!kind || inheritedKind !== "value") { - kind = inheritedKind; - } - - if (scope && t.isStringLiteral(key) && (kind === "value" || kind === "initializer") && t.isFunctionExpression(value)) { - value = (0, _babelHelperFunctionName2.default)({ id: key, node: value, scope: scope }); - } - - if (value) { - t.inheritsComments(value, node); - map[kind] = value; - } - - return map; -} - -function hasComputed(mutatorMap) { - for (var key in mutatorMap) { - if (mutatorMap[key]._computed) { - return true; - } - } - return false; -} - -function toComputedObjectFromClass(obj) { - var objExpr = t.arrayExpression([]); - - for (var i = 0; i < obj.properties.length; i++) { - var prop = obj.properties[i]; - var val = prop.value; - val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); - objExpr.elements.push(val); - } - - return objExpr; -} - -function toClassObject(mutatorMap) { - var objExpr = t.objectExpression([]); - - (0, _keys2.default)(mutatorMap).forEach(function (mutatorMapKey) { - var map = mutatorMap[mutatorMapKey]; - var mapNode = t.objectExpression([]); - - var propNode = t.objectProperty(map._key, mapNode, map._computed); - - (0, _keys2.default)(map).forEach(function (key) { - var node = map[key]; - if (key[0] === "_") return; - - var inheritNode = node; - if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value; - - var prop = t.objectProperty(t.identifier(key), node); - t.inheritsComments(prop, inheritNode); - t.removeComments(inheritNode); - - mapNode.properties.push(prop); - }); - - objExpr.properties.push(propNode); - }); - - return objExpr; -} - -function toDefineObject(mutatorMap) { - (0, _keys2.default)(mutatorMap).forEach(function (key) { - var map = mutatorMap[key]; - if (map.value) map.writable = t.booleanLiteral(true); - map.configurable = t.booleanLiteral(true); - map.enumerable = t.booleanLiteral(true); - }); - - return toClassObject(mutatorMap); -} -},{"babel-helper-function-name":53,"babel-runtime/core-js/object/keys":102,"babel-types":151,"lodash/has":479}],53:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (_ref) { - var node = _ref.node, - parent = _ref.parent, - scope = _ref.scope, - id = _ref.id; - - if (node.id) return; - - if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, { kind: "method" })) && (!parent.computed || t.isLiteral(parent.key))) { - id = parent.key; - } else if (t.isVariableDeclarator(parent)) { - id = parent.id; - - if (t.isIdentifier(id)) { - var binding = scope.parent.getBinding(id.name); - if (binding && binding.constant && scope.getBinding(id.name) === binding) { - node.id = id; - node.id[t.NOT_LOCAL_BINDING] = true; - return; - } - } - } else if (t.isAssignmentExpression(parent)) { - id = parent.left; - } else if (!id) { - return; - } - - var name = void 0; - if (id && t.isLiteral(id)) { - name = id.value; - } else if (id && t.isIdentifier(id)) { - name = id.name; - } else { - return; - } - - name = t.toBindingIdentifierName(name); - id = t.identifier(name); - - id[t.NOT_LOCAL_BINDING] = true; - - var state = visit(node, name, scope); - return wrap(state, node, id, scope) || node; -}; - -var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); - -var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); - -var buildGeneratorPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); - -var visitor = { - "ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) { - if (path.node.name !== state.name) return; - - var localDeclar = path.scope.getBindingIdentifier(state.name); - if (localDeclar !== state.outerDeclar) return; - - state.selfReference = true; - path.stop(); - } -}; - -function wrap(state, method, id, scope) { - if (state.selfReference) { - if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { - scope.rename(id.name); - } else { - if (!t.isFunction(method)) return; - - var build = buildPropertyMethodAssignmentWrapper; - if (method.generator) build = buildGeneratorPropertyMethodAssignmentWrapper; - var _template = build({ - FUNCTION: method, - FUNCTION_ID: id, - FUNCTION_KEY: scope.generateUidIdentifier(id.name) - }).expression; - _template.callee._skipModulesRemap = true; - - var params = _template.callee.body.body[0].params; - for (var i = 0, len = (0, _babelHelperGetFunctionArity2.default)(method); i < len; i++) { - params.push(scope.generateUidIdentifier("x")); - } - - return _template; - } - } - - method.id = id; - scope.getProgramParent().references[id.name] = true; -} - -function visit(node, name, scope) { - var state = { - selfAssignment: false, - selfReference: false, - outerDeclar: scope.getBindingIdentifier(name), - references: [], - name: name - }; - - var binding = scope.getOwnBinding(name); - - if (binding) { - if (binding.kind === "param") { - state.selfReference = true; - } else {} - } else if (state.outerDeclar || scope.hasGlobal(name)) { - scope.traverse(node, visitor, state); - } - - return state; -} - -module.exports = exports["default"]; -},{"babel-helper-get-function-arity":54,"babel-template":114,"babel-types":151}],54:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (node) { - var params = node.params; - for (var i = 0; i < params.length; i++) { - var param = params[i]; - if (t.isAssignmentPattern(param) || t.isRestElement(param)) { - return i; - } - } - return params.length; -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":151}],55:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (path, emit) { - var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "var"; - - path.traverse(visitor, { kind: kind, emit: emit }); -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var visitor = { - Scope: function Scope(path, state) { - if (state.kind === "let") path.skip(); - }, - Function: function Function(path) { - path.skip(); - }, - VariableDeclaration: function VariableDeclaration(path, state) { - if (state.kind && path.node.kind !== state.kind) return; - - var nodes = []; - - var declarations = path.get("declarations"); - var firstId = void 0; - - for (var _iterator = declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var declar = _ref; - - firstId = declar.node.id; - - if (declar.node.init) { - nodes.push(t.expressionStatement(t.assignmentExpression("=", declar.node.id, declar.node.init))); - } - - for (var name in declar.getBindingIdentifiers()) { - state.emit(t.identifier(name), name); - } - } - - if (path.parentPath.isFor({ left: path.node })) { - path.replaceWith(firstId); - } else { - path.replaceWithMultiple(nodes); - } - } -}; - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],56:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (callee, thisNode, args) { - if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { name: "arguments" })) { - return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); - } else { - return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode].concat(args)); - } -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":151}],57:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.is = is; -exports.pullFlag = pullFlag; - -var _pull = require("lodash/pull"); - -var _pull2 = _interopRequireDefault(_pull); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function is(node, flag) { - return t.isRegExpLiteral(node) && node.flags.indexOf(flag) >= 0; -} - -function pullFlag(node, flag) { - var flags = node.flags.split(""); - if (node.flags.indexOf(flag) < 0) return; - (0, _pull2.default)(flags, flag); - node.flags = flags.join(""); -} -},{"babel-types":151,"lodash/pull":505}],58:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); - -var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var HARDCORE_THIS_REF = (0, _symbol2.default)(); - -function isIllegalBareSuper(node, parent) { - if (!t.isSuper(node)) return false; - if (t.isMemberExpression(parent, { computed: false })) return false; - if (t.isCallExpression(parent, { callee: node })) return false; - return true; -} - -function isMemberExpressionSuper(node) { - return t.isMemberExpression(node) && t.isSuper(node.object); -} - -function getPrototypeOfExpression(objectRef, isStatic) { - var targetRef = isStatic ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); - - return t.logicalExpression("||", t.memberExpression(targetRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [targetRef])); -} - -var visitor = { - Function: function Function(path) { - if (!path.inShadow("this")) { - path.skip(); - } - }, - ReturnStatement: function ReturnStatement(path, state) { - if (!path.inShadow("this")) { - state.returns.push(path); - } - }, - ThisExpression: function ThisExpression(path, state) { - if (!path.node[HARDCORE_THIS_REF]) { - state.thises.push(path); - } - }, - enter: function enter(path, state) { - var callback = state.specHandle; - if (state.isLoose) callback = state.looseHandle; - - var isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); - - var result = callback.call(state, path); - - if (result) { - state.hasSuper = true; - } - - if (isBareSuper) { - state.bareSupers.push(path); - } - - if (result === true) { - path.requeue(); - } - - if (result !== true && result) { - if (Array.isArray(result)) { - path.replaceWithMultiple(result); - } else { - path.replaceWith(result); - } - } - } -}; - -var ReplaceSupers = function () { - function ReplaceSupers(opts) { - var inClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - (0, _classCallCheck3.default)(this, ReplaceSupers); - - this.forceSuperMemoisation = opts.forceSuperMemoisation; - this.methodPath = opts.methodPath; - this.methodNode = opts.methodNode; - this.superRef = opts.superRef; - this.isStatic = opts.isStatic; - this.hasSuper = false; - this.inClass = inClass; - this.isLoose = opts.isLoose; - this.scope = this.methodPath.scope; - this.file = opts.file; - this.opts = opts; - - this.bareSupers = []; - this.returns = []; - this.thises = []; - } - - ReplaceSupers.prototype.getObjectRef = function getObjectRef() { - return this.opts.objectRef || this.opts.getObjectRef(); - }; - - ReplaceSupers.prototype.setSuperProperty = function setSuperProperty(property, value, isComputed) { - return t.callExpression(this.file.addHelper("set"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), value, t.thisExpression()]); - }; - - ReplaceSupers.prototype.getSuperProperty = function getSuperProperty(property, isComputed) { - return t.callExpression(this.file.addHelper("get"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), t.thisExpression()]); - }; - - ReplaceSupers.prototype.replace = function replace() { - this.methodPath.traverse(visitor, this); - }; - - ReplaceSupers.prototype.getLooseSuperProperty = function getLooseSuperProperty(id, parent) { - var methodNode = this.methodNode; - var superRef = this.superRef || t.identifier("Function"); - - if (parent.property === id) { - return; - } else if (t.isCallExpression(parent, { callee: id })) { - return; - } else if (t.isMemberExpression(parent) && !methodNode.static) { - return t.memberExpression(superRef, t.identifier("prototype")); - } else { - return superRef; - } - }; - - ReplaceSupers.prototype.looseHandle = function looseHandle(path) { - var node = path.node; - if (path.isSuper()) { - return this.getLooseSuperProperty(node, path.parent); - } else if (path.isCallExpression()) { - var callee = node.callee; - if (!t.isMemberExpression(callee)) return; - if (!t.isSuper(callee.object)) return; - - t.appendToMemberExpression(callee, t.identifier("call")); - node.arguments.unshift(t.thisExpression()); - return true; - } - }; - - ReplaceSupers.prototype.specHandleAssignmentExpression = function specHandleAssignmentExpression(ref, path, node) { - if (node.operator === "=") { - return this.setSuperProperty(node.left.property, node.right, node.left.computed); - } else { - ref = ref || path.scope.generateUidIdentifier("ref"); - return [t.variableDeclaration("var", [t.variableDeclarator(ref, node.left)]), t.expressionStatement(t.assignmentExpression("=", node.left, t.binaryExpression(node.operator[0], ref, node.right)))]; - } - }; - - ReplaceSupers.prototype.specHandle = function specHandle(path) { - var property = void 0; - var computed = void 0; - var args = void 0; - - var parent = path.parent; - var node = path.node; - - if (isIllegalBareSuper(node, parent)) { - throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper")); - } - - if (t.isCallExpression(node)) { - var callee = node.callee; - if (t.isSuper(callee)) { - return; - } else if (isMemberExpressionSuper(callee)) { - property = callee.property; - computed = callee.computed; - args = node.arguments; - } - } else if (t.isMemberExpression(node) && t.isSuper(node.object)) { - property = node.property; - computed = node.computed; - } else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) { - var binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); - if (node.prefix) { - return this.specHandleAssignmentExpression(null, path, binary); - } else { - var ref = path.scope.generateUidIdentifier("ref"); - return this.specHandleAssignmentExpression(ref, path, binary).concat(t.expressionStatement(ref)); - } - } else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) { - return this.specHandleAssignmentExpression(null, path, node); - } - - if (!property) return; - - var superProperty = this.getSuperProperty(property, computed); - - if (args) { - return this.optimiseCall(superProperty, args); - } else { - return superProperty; - } - }; - - ReplaceSupers.prototype.optimiseCall = function optimiseCall(callee, args) { - var thisNode = t.thisExpression(); - thisNode[HARDCORE_THIS_REF] = true; - return (0, _babelHelperOptimiseCallExpression2.default)(callee, thisNode, args); - }; - - return ReplaceSupers; -}(); - -exports.default = ReplaceSupers; -module.exports = exports["default"]; -},{"babel-helper-optimise-call-expression":56,"babel-messages":61,"babel-runtime/core-js/symbol":104,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],59:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var helpers = {}; -exports.default = helpers; - - -helpers.typeof = (0, _babelTemplate2.default)("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n"); - -helpers.jsx = (0, _babelTemplate2.default)("\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === \"function\" && Symbol.for && Symbol.for(\"react.element\")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n"); - -helpers.asyncIterator = (0, _babelTemplate2.default)("\n (function (iterable) {\n if (typeof Symbol === \"function\") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n })\n"); - -helpers.asyncGenerator = (0, _babelTemplate2.default)("\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume(\"next\", arg); },\n function (arg) { resume(\"throw\", arg); });\n } else {\n settle(result.done ? \"return\" : \"normal\", result.value);\n }\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n"); - -helpers.asyncGeneratorDelegate = (0, _babelTemplate2.default)("\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n return pump(\"return\", value);\n };\n }\n\n return iter;\n })\n"); - -helpers.asyncToGenerator = (0, _babelTemplate2.default)("\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step(\"next\", value);\n }, function (err) {\n step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n"); - -helpers.classCallCheck = (0, _babelTemplate2.default)("\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n });\n"); - -helpers.createClass = (0, _babelTemplate2.default)("\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n"); - -helpers.defineEnumerableProperties = (0, _babelTemplate2.default)("\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n"); - -helpers.defaults = (0, _babelTemplate2.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"); - -helpers.defineProperty = (0, _babelTemplate2.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"); - -helpers.extends = (0, _babelTemplate2.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"); - -helpers.get = (0, _babelTemplate2.default)("\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n"); - -helpers.inherits = (0, _babelTemplate2.default)("\n (function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n"); - -helpers.instanceof = (0, _babelTemplate2.default)("\n (function (left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n"); - -helpers.interopRequireDefault = (0, _babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"); - -helpers.interopRequireWildcard = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"); - -helpers.newArrowCheck = (0, _babelTemplate2.default)("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n"); - -helpers.objectDestructuringEmpty = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n"); - -helpers.objectWithoutProperties = (0, _babelTemplate2.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"); - -helpers.possibleConstructorReturn = (0, _babelTemplate2.default)("\n (function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n });\n"); - -helpers.selfGlobal = (0, _babelTemplate2.default)("\n typeof global === \"undefined\" ? self : global\n"); - -helpers.set = (0, _babelTemplate2.default)("\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if (\"value\" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n"); - -helpers.slicedToArray = (0, _babelTemplate2.default)("\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n })();\n"); - -helpers.slicedToArrayLoose = (0, _babelTemplate2.default)("\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n });\n"); - -helpers.taggedTemplateLiteral = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"); - -helpers.taggedTemplateLiteralLoose = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"); - -helpers.temporalRef = (0, _babelTemplate2.default)("\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n } else {\n return val;\n }\n })\n"); - -helpers.temporalUndefined = (0, _babelTemplate2.default)("\n ({})\n"); - -helpers.toArray = (0, _babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"); - -helpers.toConsumableArray = (0, _babelTemplate2.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"); -module.exports = exports["default"]; -},{"babel-template":114}],60:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.list = undefined; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -exports.get = get; - -var _helpers = require("./helpers"); - -var _helpers2 = _interopRequireDefault(_helpers); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function get(name) { - var fn = _helpers2.default[name]; - if (!fn) throw new ReferenceError("Unknown helper " + name); - - return fn().expression; -} - -var list = exports.list = (0, _keys2.default)(_helpers2.default).map(function (name) { - return name.replace(/^_/, ""); -}).filter(function (name) { - return name !== "__esModule"; -}); - -exports.default = get; -},{"./helpers":59,"babel-runtime/core-js/object/keys":102}],61:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.MESSAGES = undefined; - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -exports.get = get; -exports.parseArgs = parseArgs; - -var _util = require("util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var MESSAGES = exports.MESSAGES = { - tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence", - classesIllegalBareSuper: "Illegal use of bare super", - classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead", - scopeDuplicateDeclaration: "Duplicate declaration $1", - settersNoRest: "Setters aren't allowed to have a rest", - noAssignmentsInForHead: "No assignments allowed in for-in/of head", - expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier", - invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue", - readOnly: "$1 is read-only", - unknownForHead: "Unknown node type $1 in ForStatement", - didYouMean: "Did you mean $1?", - codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.", - missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues", - unsupportedOutputType: "Unsupported output type $1", - illegalMethodName: "Illegal method name $1", - lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated", - - modulesIllegalExportName: "Illegal export $1", - modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes", - - undeclaredVariable: "Reference to undeclared variable $1", - undeclaredVariableType: "Referencing a type alias outside of a type annotation", - undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?", - - traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.", - traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?", - traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2", - traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type", - - pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", - pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", - pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", - pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" -}; - -function get(key) { - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - var msg = MESSAGES[key]; - if (!msg) throw new ReferenceError("Unknown message " + (0, _stringify2.default)(key)); - - args = parseArgs(args); - - return msg.replace(/\$(\d+)/g, function (str, i) { - return args[i - 1]; - }); -} - -function parseArgs(args) { - return args.map(function (val) { - if (val != null && val.inspect) { - return val.inspect(); - } else { - try { - return (0, _stringify2.default)(val) || val + ""; - } catch (e) { - return util.inspect(val); - } - } - }); -} -},{"babel-runtime/core-js/json/stringify":96,"util":560}],62:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (_ref) { - var messages = _ref.messages; - - return { - visitor: { - Scope: function Scope(_ref2) { - var scope = _ref2.scope; - - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - if (binding.kind !== "const" && binding.kind !== "module") continue; - - for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref3; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref3 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref3 = _i.value; - } - - var violation = _ref3; - - throw violation.buildCodeFrameError(messages.get("readOnly", name)); - } - } - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],63:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - manipulateOptions: function manipulateOptions(opts, parserOpts) { - parserOpts.plugins.push("dynamicImport"); - } - }; -}; - -module.exports = exports["default"]; -},{}],64:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (_ref) { - var t = _ref.types; - - return { - visitor: { - ArrowFunctionExpression: function ArrowFunctionExpression(path, state) { - if (state.opts.spec) { - var node = path.node; - - if (node.shadow) return; - - node.shadow = { this: false }; - node.type = "FunctionExpression"; - - var boundThis = t.thisExpression(); - boundThis._forceShadow = path; - - path.ensureBlock(); - path.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [t.thisExpression(), boundThis]))); - - path.replaceWith(t.callExpression(t.memberExpression(node, t.identifier("bind")), [t.thisExpression()])); - } else { - path.arrowFunctionToShadowed(); - } - } - } - }; -}; - -module.exports = exports["default"]; -},{}],65:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (_ref) { - var t = _ref.types; - - function statementList(key, path) { - var paths = path.get(key); - - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var _path = _ref2; - - var func = _path.node; - if (!_path.isFunctionDeclaration()) continue; - - var declar = t.variableDeclaration("let", [t.variableDeclarator(func.id, t.toExpression(func))]); - - declar._blockHoist = 2; - - func.id = null; - - _path.replaceWith(declar); - } - } - - return { - visitor: { - BlockStatement: function BlockStatement(path) { - var node = path.node, - parent = path.parent; - - if (t.isFunction(parent, { body: node }) || t.isExportDeclaration(parent)) { - return; - } - - statementList("body", path); - }, - SwitchCase: function SwitchCase(path) { - statementList("consequent", path); - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],66:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -exports.default = function () { - return { - visitor: { - VariableDeclaration: function VariableDeclaration(path, file) { - var node = path.node, - parent = path.parent, - scope = path.scope; - - if (!isBlockScoped(node)) return; - convertBlockScopedToVar(path, null, parent, scope, true); - - if (node._tdzThis) { - var nodes = [node]; - - for (var i = 0; i < node.declarations.length; i++) { - var decl = node.declarations[i]; - if (decl.init) { - var assign = t.assignmentExpression("=", decl.id, decl.init); - assign._ignoreBlockScopingTDZ = true; - nodes.push(t.expressionStatement(assign)); - } - decl.init = file.addHelper("temporalUndefined"); - } - - node._blockHoist = 2; - - if (path.isCompletionRecord()) { - nodes.push(t.expressionStatement(scope.buildUndefinedNode())); - } - - path.replaceWithMultiple(nodes); - } - }, - Loop: function Loop(path, file) { - var node = path.node, - parent = path.parent, - scope = path.scope; - - t.ensureBlock(node); - var blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); - var replace = blockScoping.run(); - if (replace) path.replaceWith(replace); - }, - CatchClause: function CatchClause(path, file) { - var parent = path.parent, - scope = path.scope; - - var blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); - blockScoping.run(); - }, - "BlockStatement|SwitchStatement|Program": function BlockStatementSwitchStatementProgram(path, file) { - if (!ignoreBlock(path)) { - var blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); - blockScoping.run(); - } - } - } - }; -}; - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _tdz = require("./tdz"); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _values = require("lodash/values"); - -var _values2 = _interopRequireDefault(_values); - -var _extend = require("lodash/extend"); - -var _extend2 = _interopRequireDefault(_extend); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function ignoreBlock(path) { - return t.isLoop(path.parent) || t.isCatchClause(path.parent); -} - -var buildRetCheck = (0, _babelTemplate2.default)("\n if (typeof RETURN === \"object\") return RETURN.v;\n"); - -function isBlockScoped(node) { - if (!t.isVariableDeclaration(node)) return false; - if (node[t.BLOCK_SCOPED_SYMBOL]) return true; - if (node.kind !== "let" && node.kind !== "const") return false; - return true; -} - -function convertBlockScopedToVar(path, node, parent, scope) { - var moveBindingsToParent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - - if (!node) { - node = path.node; - } - - if (!t.isFor(parent)) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - declar.init = declar.init || scope.buildUndefinedNode(); - } - } - - node[t.BLOCK_SCOPED_SYMBOL] = true; - node.kind = "var"; - - if (moveBindingsToParent) { - var parentScope = scope.getFunctionParent(); - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = scope.getOwnBinding(name); - if (binding) binding.kind = "var"; - scope.moveBindingTo(name, parentScope); - } - } -} - -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); -} - -var letReferenceBlockVisitor = _babelTraverse2.default.visitors.merge([{ - Loop: { - enter: function enter(path, state) { - state.loopDepth++; - }, - exit: function exit(path, state) { - state.loopDepth--; - } - }, - Function: function Function(path, state) { - if (state.loopDepth > 0) { - path.traverse(letReferenceFunctionVisitor, state); - } - return path.skip(); - } -}, _tdz.visitor]); - -var letReferenceFunctionVisitor = _babelTraverse2.default.visitors.merge([{ - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var ref = state.letReferences[path.node.name]; - - if (!ref) return; - - var localBinding = path.scope.getBindingIdentifier(path.node.name); - if (localBinding && localBinding !== ref) return; - - state.closurify = true; - } -}, _tdz.visitor]); - -var hoistVarDeclarationsVisitor = { - enter: function enter(path, self) { - var node = path.node, - parent = path.parent; - - - if (path.isForStatement()) { - if (isVar(node.init, node)) { - var nodes = self.pushDeclar(node.init); - if (nodes.length === 1) { - node.init = nodes[0]; - } else { - node.init = t.sequenceExpression(nodes); - } - } - } else if (path.isFor()) { - if (isVar(node.left, node)) { - self.pushDeclar(node.left); - node.left = node.left.declarations[0].id; - } - } else if (isVar(node, parent)) { - path.replaceWithMultiple(self.pushDeclar(node).map(function (expr) { - return t.expressionStatement(expr); - })); - } else if (path.isFunction()) { - return path.skip(); - } - } -}; - -var loopLabelVisitor = { - LabeledStatement: function LabeledStatement(_ref, state) { - var node = _ref.node; - - state.innerLabels.push(node.label.name); - } -}; - -var continuationVisitor = { - enter: function enter(path, state) { - if (path.isAssignmentExpression() || path.isUpdateExpression()) { - var bindings = path.getBindingIdentifiers(); - for (var name in bindings) { - if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) continue; - state.reassignments[name] = true; - } - } - } -}; - -function loopNodeTo(node) { - if (t.isBreakStatement(node)) { - return "break"; - } else if (t.isContinueStatement(node)) { - return "continue"; - } -} - -var loopVisitor = { - Loop: function Loop(path, state) { - var oldIgnoreLabeless = state.ignoreLabeless; - state.ignoreLabeless = true; - path.traverse(loopVisitor, state); - state.ignoreLabeless = oldIgnoreLabeless; - path.skip(); - }, - Function: function Function(path) { - path.skip(); - }, - SwitchCase: function SwitchCase(path, state) { - var oldInSwitchCase = state.inSwitchCase; - state.inSwitchCase = true; - path.traverse(loopVisitor, state); - state.inSwitchCase = oldInSwitchCase; - path.skip(); - }, - "BreakStatement|ContinueStatement|ReturnStatement": function BreakStatementContinueStatementReturnStatement(path, state) { - var node = path.node, - parent = path.parent, - scope = path.scope; - - if (node[this.LOOP_IGNORE]) return; - - var replace = void 0; - var loopText = loopNodeTo(node); - - if (loopText) { - if (node.label) { - if (state.innerLabels.indexOf(node.label.name) >= 0) { - return; - } - - loopText = loopText + "|" + node.label.name; - } else { - if (state.ignoreLabeless) return; - - if (state.inSwitchCase) return; - - if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return; - } - - state.hasBreakContinue = true; - state.map[loopText] = node; - replace = t.stringLiteral(loopText); - } - - if (path.isReturnStatement()) { - state.hasReturn = true; - replace = t.objectExpression([t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode())]); - } - - if (replace) { - replace = t.returnStatement(replace); - replace[this.LOOP_IGNORE] = true; - path.skip(); - path.replaceWith(t.inherits(replace, node)); - } - } -}; - -var BlockScoping = function () { - function BlockScoping(loopPath, blockPath, parent, scope, file) { - (0, _classCallCheck3.default)(this, BlockScoping); - - this.parent = parent; - this.scope = scope; - this.file = file; - - this.blockPath = blockPath; - this.block = blockPath.node; - - this.outsideLetReferences = (0, _create2.default)(null); - this.hasLetReferences = false; - this.letReferences = (0, _create2.default)(null); - this.body = []; - - if (loopPath) { - this.loopParent = loopPath.parent; - this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; - this.loopPath = loopPath; - this.loop = loopPath.node; - } - } - - BlockScoping.prototype.run = function run() { - var block = this.block; - if (block._letDone) return; - block._letDone = true; - - var needsClosure = this.getLetReferences(); - - if (t.isFunction(this.parent) || t.isProgram(this.block)) { - this.updateScopeInfo(); - return; - } - - if (!this.hasLetReferences) return; - - if (needsClosure) { - this.wrapClosure(); - } else { - this.remap(); - } - - this.updateScopeInfo(needsClosure); - - if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { - return t.labeledStatement(this.loopLabel, this.loop); - } - }; - - BlockScoping.prototype.updateScopeInfo = function updateScopeInfo(wrappedInClosure) { - var scope = this.scope; - var parentScope = scope.getFunctionParent(); - var letRefs = this.letReferences; - - for (var key in letRefs) { - var ref = letRefs[key]; - var binding = scope.getBinding(ref.name); - if (!binding) continue; - if (binding.kind === "let" || binding.kind === "const") { - binding.kind = "var"; - - if (wrappedInClosure) { - scope.removeBinding(ref.name); - } else { - scope.moveBindingTo(ref.name, parentScope); - } - } - } - }; - - BlockScoping.prototype.remap = function remap() { - var letRefs = this.letReferences; - var scope = this.scope; - - for (var key in letRefs) { - var ref = letRefs[key]; - - if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { - if (scope.hasOwnBinding(key)) scope.rename(ref.name); - - if (this.blockPath.scope.hasOwnBinding(key)) this.blockPath.scope.rename(ref.name); - } - } - }; - - BlockScoping.prototype.wrapClosure = function wrapClosure() { - if (this.file.opts.throwIfClosureRequired) { - throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired)."); - } - var block = this.block; - - var outsideRefs = this.outsideLetReferences; - - if (this.loop) { - for (var name in outsideRefs) { - var id = outsideRefs[name]; - - if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { - delete outsideRefs[id.name]; - delete this.letReferences[id.name]; - - this.scope.rename(id.name); - - this.letReferences[id.name] = id; - outsideRefs[id.name] = id; - } - } - } - - this.has = this.checkLoop(); - - this.hoistVarDeclarations(); - - var params = (0, _values2.default)(outsideRefs); - var args = (0, _values2.default)(outsideRefs); - - var isSwitch = this.blockPath.isSwitchStatement(); - - var fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); - fn.shadow = true; - - this.addContinuations(fn); - - var ref = fn; - - if (this.loop) { - ref = this.scope.generateUidIdentifier("loop"); - this.loopPath.insertBefore(t.variableDeclaration("var", [t.variableDeclarator(ref, fn)])); - } - - var call = t.callExpression(ref, args); - var ret = this.scope.generateUidIdentifier("ret"); - - var hasYield = _babelTraverse2.default.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); - if (hasYield) { - fn.generator = true; - call = t.yieldExpression(call, true); - } - - var hasAsync = _babelTraverse2.default.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); - if (hasAsync) { - fn.async = true; - call = t.awaitExpression(call); - } - - this.buildClosure(ret, call); - - if (isSwitch) this.blockPath.replaceWithMultiple(this.body);else block.body = this.body; - }; - - BlockScoping.prototype.buildClosure = function buildClosure(ret, call) { - var has = this.has; - if (has.hasReturn || has.hasBreakContinue) { - this.buildHas(ret, call); - } else { - this.body.push(t.expressionStatement(call)); - } - }; - - BlockScoping.prototype.addContinuations = function addContinuations(fn) { - var state = { - reassignments: {}, - outsideReferences: this.outsideLetReferences - }; - - this.scope.traverse(fn, continuationVisitor, state); - - for (var i = 0; i < fn.params.length; i++) { - var param = fn.params[i]; - if (!state.reassignments[param.name]) continue; - - var newParam = this.scope.generateUidIdentifier(param.name); - fn.params[i] = newParam; - - this.scope.rename(param.name, newParam.name, fn); - - fn.body.body.push(t.expressionStatement(t.assignmentExpression("=", param, newParam))); - } - }; - - BlockScoping.prototype.getLetReferences = function getLetReferences() { - var _this = this; - - var block = this.block; - - var declarators = []; - - if (this.loop) { - var init = this.loop.left || this.loop.init; - if (isBlockScoped(init)) { - declarators.push(init); - (0, _extend2.default)(this.outsideLetReferences, t.getBindingIdentifiers(init)); - } - } - - var addDeclarationsFromChild = function addDeclarationsFromChild(path, node) { - node = node || path.node; - if (t.isClassDeclaration(node) || t.isFunctionDeclaration(node) || isBlockScoped(node)) { - if (isBlockScoped(node)) { - convertBlockScopedToVar(path, node, block, _this.scope); - } - declarators = declarators.concat(node.declarations || node); - } - if (t.isLabeledStatement(node)) { - addDeclarationsFromChild(path.get("body"), node.body); - } - }; - - if (block.body) { - for (var i = 0; i < block.body.length; i++) { - var declarPath = this.blockPath.get("body")[i]; - addDeclarationsFromChild(declarPath); - } - } - - if (block.cases) { - for (var _i = 0; _i < block.cases.length; _i++) { - var consequents = block.cases[_i].consequent; - - for (var j = 0; j < consequents.length; j++) { - var _declarPath = this.blockPath.get("cases")[_i]; - var declar = consequents[j]; - addDeclarationsFromChild(_declarPath, declar); - } - } - } - - for (var _i2 = 0; _i2 < declarators.length; _i2++) { - var _declar = declarators[_i2]; - - var keys = t.getBindingIdentifiers(_declar, false, true); - (0, _extend2.default)(this.letReferences, keys); - this.hasLetReferences = true; - } - - if (!this.hasLetReferences) return; - - var state = { - letReferences: this.letReferences, - closurify: false, - file: this.file, - loopDepth: 0 - }; - - var loopOrFunctionParent = this.blockPath.find(function (path) { - return path.isLoop() || path.isFunction(); - }); - if (loopOrFunctionParent && loopOrFunctionParent.isLoop()) { - state.loopDepth++; - } - - this.blockPath.traverse(letReferenceBlockVisitor, state); - - return state.closurify; - }; - - BlockScoping.prototype.checkLoop = function checkLoop() { - var state = { - hasBreakContinue: false, - ignoreLabeless: false, - inSwitchCase: false, - innerLabels: [], - hasReturn: false, - isLoop: !!this.loop, - map: {}, - LOOP_IGNORE: (0, _symbol2.default)() - }; - - this.blockPath.traverse(loopLabelVisitor, state); - this.blockPath.traverse(loopVisitor, state); - - return state; - }; - - BlockScoping.prototype.hoistVarDeclarations = function hoistVarDeclarations() { - this.blockPath.traverse(hoistVarDeclarationsVisitor, this); - }; - - BlockScoping.prototype.pushDeclar = function pushDeclar(node) { - var declars = []; - var names = t.getBindingIdentifiers(node); - for (var name in names) { - declars.push(t.variableDeclarator(names[name])); - } - - this.body.push(t.variableDeclaration(node.kind, declars)); - - var replace = []; - - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - if (!declar.init) continue; - - var expr = t.assignmentExpression("=", declar.id, declar.init); - replace.push(t.inherits(expr, declar)); - } - - return replace; - }; - - BlockScoping.prototype.buildHas = function buildHas(ret, call) { - var body = this.body; - - body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); - - var retCheck = void 0; - var has = this.has; - var cases = []; - - if (has.hasReturn) { - retCheck = buildRetCheck({ - RETURN: ret - }); - } - - if (has.hasBreakContinue) { - for (var key in has.map) { - cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]])); - } - - if (has.hasReturn) { - cases.push(t.switchCase(null, [retCheck])); - } - - if (cases.length === 1) { - var single = cases[0]; - body.push(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0])); - } else { - if (this.loop) { - for (var i = 0; i < cases.length; i++) { - var caseConsequent = cases[i].consequent[0]; - if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { - caseConsequent.label = this.loopLabel = this.loopLabel || this.scope.generateUidIdentifier("loop"); - } - } - } - - body.push(t.switchStatement(ret, cases)); - } - } else { - if (has.hasReturn) { - body.push(retCheck); - } - } - }; - - return BlockScoping; -}(); - -module.exports = exports["default"]; -},{"./tdz":67,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/symbol":104,"babel-runtime/helpers/classCallCheck":109,"babel-template":114,"babel-traverse":118,"babel-types":151,"lodash/extend":473,"lodash/values":518}],67:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.visitor = undefined; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function getTDZStatus(refPath, bindingPath) { - var executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); - - if (executionStatus === "before") { - return "inside"; - } else if (executionStatus === "after") { - return "outside"; - } else { - return "maybe"; - } -} - -function buildTDZAssert(node, file) { - return t.callExpression(file.addHelper("temporalRef"), [node, t.stringLiteral(node.name), file.addHelper("temporalUndefined")]); -} - -function isReference(node, scope, state) { - var declared = state.letReferences[node.name]; - if (!declared) return false; - - return scope.getBindingIdentifier(node.name) === declared; -} - -var visitor = exports.visitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (!this.file.opts.tdz) return; - - var node = path.node, - parent = path.parent, - scope = path.scope; - - - if (path.parentPath.isFor({ left: node })) return; - if (!isReference(node, scope, state)) return; - - var bindingPath = scope.getBinding(node.name).path; - - var status = getTDZStatus(path, bindingPath); - if (status === "inside") return; - - if (status === "maybe") { - var assert = buildTDZAssert(node, state.file); - - bindingPath.parent._tdzThis = true; - - path.skip(); - - if (path.parentPath.isUpdateExpression()) { - if (parent._ignoreBlockScopingTDZ) return; - path.parentPath.replaceWith(t.sequenceExpression([assert, parent])); - } else { - path.replaceWith(assert); - } - } else if (status === "outside") { - path.replaceWith(t.throwStatement(t.inherits(t.newExpression(t.identifier("ReferenceError"), [t.stringLiteral(node.name + " is not defined - temporal dead zone")]), node))); - } - }, - - - AssignmentExpression: { - exit: function exit(path, state) { - if (!this.file.opts.tdz) return; - - var node = path.node; - - if (node._ignoreBlockScopingTDZ) return; - - var nodes = []; - var ids = path.getBindingIdentifiers(); - - for (var name in ids) { - var id = ids[name]; - - if (isReference(id, path.scope, state)) { - nodes.push(buildTDZAssert(id, state.file)); - } - } - - if (nodes.length) { - node._ignoreBlockScopingTDZ = true; - nodes.push(node); - path.replaceWithMultiple(nodes.map(t.expressionStatement)); - } - } - } -}; -},{"babel-types":151}],68:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (_ref) { - var t = _ref.types; - - var VISITED = (0, _symbol2.default)(); - - return { - visitor: { - ExportDefaultDeclaration: function ExportDefaultDeclaration(path) { - if (!path.get("declaration").isClassDeclaration()) return; - - var node = path.node; - - var ref = node.declaration.id || path.scope.generateUidIdentifier("class"); - node.declaration.id = ref; - - path.replaceWith(node.declaration); - path.insertAfter(t.exportDefaultDeclaration(ref)); - }, - ClassDeclaration: function ClassDeclaration(path) { - var node = path.node; - - - var ref = node.id || path.scope.generateUidIdentifier("class"); - - path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(ref, t.toExpression(node))])); - }, - ClassExpression: function ClassExpression(path, state) { - var node = path.node; - - if (node[VISITED]) return; - - var inferred = (0, _babelHelperFunctionName2.default)(path); - if (inferred && inferred !== node) return path.replaceWith(inferred); - - node[VISITED] = true; - - var Constructor = _vanilla2.default; - if (state.opts.loose) Constructor = _loose2.default; - - path.replaceWith(new Constructor(path, state.file).run()); - } - } - }; -}; - -var _loose = require("./loose"); - -var _loose2 = _interopRequireDefault(_loose); - -var _vanilla = require("./vanilla"); - -var _vanilla2 = _interopRequireDefault(_vanilla); - -var _babelHelperFunctionName = require("babel-helper-function-name"); - -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"./loose":69,"./vanilla":70,"babel-helper-function-name":53,"babel-runtime/core-js/symbol":104}],69:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _babelHelperFunctionName = require("babel-helper-function-name"); - -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); - -var _vanilla = require("./vanilla"); - -var _vanilla2 = _interopRequireDefault(_vanilla); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var LooseClassTransformer = function (_VanillaTransformer) { - (0, _inherits3.default)(LooseClassTransformer, _VanillaTransformer); - - function LooseClassTransformer() { - (0, _classCallCheck3.default)(this, LooseClassTransformer); - - var _this = (0, _possibleConstructorReturn3.default)(this, _VanillaTransformer.apply(this, arguments)); - - _this.isLoose = true; - return _this; - } - - LooseClassTransformer.prototype._processMethod = function _processMethod(node, scope) { - if (!node.decorators) { - - var classRef = this.classRef; - if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype")); - var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); - - var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); - func.returnType = node.returnType; - var key = t.toComputedKey(node, node.key); - if (t.isStringLiteral(key)) { - func = (0, _babelHelperFunctionName2.default)({ - node: func, - id: key, - scope: scope - }); - } - - var expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); - t.inheritsComments(expr, node); - this.body.push(expr); - return true; - } - }; - - return LooseClassTransformer; -}(_vanilla2.default); - -exports.default = LooseClassTransformer; -module.exports = exports["default"]; -},{"./vanilla":70,"babel-helper-function-name":53,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"babel-types":151}],70:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _babelTraverse = require("babel-traverse"); - -var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); - -var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); - -var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); - -var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); - -var _babelHelperDefineMap = require("babel-helper-define-map"); - -var defineMap = _interopRequireWildcard(_babelHelperDefineMap); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildDerivedConstructor = (0, _babelTemplate2.default)("\n (function () {\n super(...arguments);\n })\n"); - -var noMethodVisitor = { - "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { - if (!path.is("shadow")) { - path.skip(); - } - }, - Method: function Method(path) { - path.skip(); - } -}; - -var verifyConstructorVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { - Super: function Super(path) { - if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { - throw path.buildCodeFrameError("'super.*' is not allowed before super()"); - } - }, - - - CallExpression: { - exit: function exit(path) { - if (path.get("callee").isSuper()) { - this.hasBareSuper = true; - - if (!this.isDerived) { - throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); - } - } - } - }, - - ThisExpression: function ThisExpression(path) { - if (this.isDerived && !this.hasBareSuper) { - if (!path.inShadow("this")) { - throw path.buildCodeFrameError("'this' is not allowed before super()"); - } - } - } -}]); - -var findThisesVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { - ThisExpression: function ThisExpression(path) { - this.superThises.push(path); - } -}]); - -var ClassTransformer = function () { - function ClassTransformer(path, file) { - (0, _classCallCheck3.default)(this, ClassTransformer); - - this.parent = path.parent; - this.scope = path.scope; - this.node = path.node; - this.path = path; - this.file = file; - - this.clearDescriptors(); - - this.instancePropBody = []; - this.instancePropRefs = {}; - this.staticPropBody = []; - this.body = []; - - this.bareSuperAfter = []; - this.bareSupers = []; - - this.pushedConstructor = false; - this.pushedInherits = false; - this.isLoose = false; - - this.superThises = []; - - this.classId = this.node.id; - - this.classRef = this.node.id ? t.identifier(this.node.id.name) : this.scope.generateUidIdentifier("class"); - - this.superName = this.node.superClass || t.identifier("Function"); - this.isDerived = !!this.node.superClass; - } - - ClassTransformer.prototype.run = function run() { - var _this = this; - - var superName = this.superName; - var file = this.file; - var body = this.body; - - var constructorBody = this.constructorBody = t.blockStatement([]); - this.constructor = this.buildConstructor(); - - var closureParams = []; - var closureArgs = []; - - if (this.isDerived) { - closureArgs.push(superName); - - superName = this.scope.generateUidIdentifierBasedOnNode(superName); - closureParams.push(superName); - - this.superName = superName; - } - - this.buildBody(); - - constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [t.thisExpression(), this.classRef]))); - - body = body.concat(this.staticPropBody.map(function (fn) { - return fn(_this.classRef); - })); - - if (this.classId) { - if (body.length === 1) return t.toExpression(body[0]); - } - - body.push(t.returnStatement(this.classRef)); - - var container = t.functionExpression(null, closureParams, t.blockStatement(body)); - container.shadow = true; - return t.callExpression(container, closureArgs); - }; - - ClassTransformer.prototype.buildConstructor = function buildConstructor() { - var func = t.functionDeclaration(this.classRef, [], this.constructorBody); - t.inherits(func, this.node); - return func; - }; - - ClassTransformer.prototype.pushToMap = function pushToMap(node, enumerable) { - var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "value"; - var scope = arguments[3]; - - var mutatorMap = void 0; - if (node.static) { - this.hasStaticDescriptors = true; - mutatorMap = this.staticMutatorMap; - } else { - this.hasInstanceDescriptors = true; - mutatorMap = this.instanceMutatorMap; - } - - var map = defineMap.push(mutatorMap, node, kind, this.file, scope); - - if (enumerable) { - map.enumerable = t.booleanLiteral(true); - } - - return map; - }; - - ClassTransformer.prototype.constructorMeMaybe = function constructorMeMaybe() { - var hasConstructor = false; - var paths = this.path.get("body.body"); - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var path = _ref; - - hasConstructor = path.equals("kind", "constructor"); - if (hasConstructor) break; - } - if (hasConstructor) return; - - var params = void 0, - body = void 0; - - if (this.isDerived) { - var _constructor = buildDerivedConstructor().expression; - params = _constructor.params; - body = _constructor.body; - } else { - params = []; - body = t.blockStatement([]); - } - - this.path.get("body").unshiftContainer("body", t.classMethod("constructor", t.identifier("constructor"), params, body)); - }; - - ClassTransformer.prototype.buildBody = function buildBody() { - this.constructorMeMaybe(); - this.pushBody(); - this.verifyConstructor(); - - if (this.userConstructor) { - var constructorBody = this.constructorBody; - constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); - t.inherits(this.constructor, this.userConstructor); - t.inherits(constructorBody, this.userConstructor.body); - } - - this.pushDescriptors(); - }; - - ClassTransformer.prototype.pushBody = function pushBody() { - var classBodyPaths = this.path.get("body.body"); - - for (var _iterator2 = classBodyPaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var path = _ref2; - - var node = path.node; - - if (path.isClassProperty()) { - throw path.buildCodeFrameError("Missing class properties transform."); - } - - if (node.decorators) { - throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one."); - } - - if (t.isClassMethod(node)) { - var isConstructor = node.kind === "constructor"; - - if (isConstructor) { - path.traverse(verifyConstructorVisitor, this); - - if (!this.hasBareSuper && this.isDerived) { - throw path.buildCodeFrameError("missing super() call in constructor"); - } - } - - var replaceSupers = new _babelHelperReplaceSupers2.default({ - forceSuperMemoisation: isConstructor, - methodPath: path, - methodNode: node, - objectRef: this.classRef, - superRef: this.superName, - isStatic: node.static, - isLoose: this.isLoose, - scope: this.scope, - file: this.file - }, true); - - replaceSupers.replace(); - - if (isConstructor) { - this.pushConstructor(replaceSupers, node, path); - } else { - this.pushMethod(node, path); - } - } - } - }; - - ClassTransformer.prototype.clearDescriptors = function clearDescriptors() { - this.hasInstanceDescriptors = false; - this.hasStaticDescriptors = false; - - this.instanceMutatorMap = {}; - this.staticMutatorMap = {}; - }; - - ClassTransformer.prototype.pushDescriptors = function pushDescriptors() { - this.pushInherits(); - - var body = this.body; - - var instanceProps = void 0; - var staticProps = void 0; - - if (this.hasInstanceDescriptors) { - instanceProps = defineMap.toClassObject(this.instanceMutatorMap); - } - - if (this.hasStaticDescriptors) { - staticProps = defineMap.toClassObject(this.staticMutatorMap); - } - - if (instanceProps || staticProps) { - if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); - if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); - - var nullNode = t.nullLiteral(); - - var args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; - - if (instanceProps) args[1] = instanceProps; - if (staticProps) args[2] = staticProps; - - if (this.instanceInitializersId) { - args[3] = this.instanceInitializersId; - body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); - } - - if (this.staticInitializersId) { - args[4] = this.staticInitializersId; - body.unshift(this.buildObjectAssignment(this.staticInitializersId)); - } - - var lastNonNullIndex = 0; - for (var i = 0; i < args.length; i++) { - if (args[i] !== nullNode) lastNonNullIndex = i; - } - args = args.slice(0, lastNonNullIndex + 1); - - body.push(t.expressionStatement(t.callExpression(this.file.addHelper("createClass"), args))); - } - - this.clearDescriptors(); - }; - - ClassTransformer.prototype.buildObjectAssignment = function buildObjectAssignment(id) { - return t.variableDeclaration("var", [t.variableDeclarator(id, t.objectExpression([]))]); - }; - - ClassTransformer.prototype.wrapSuperCall = function wrapSuperCall(bareSuper, superRef, thisRef, body) { - var bareSuperNode = bareSuper.node; - - if (this.isLoose) { - bareSuperNode.arguments.unshift(t.thisExpression()); - if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) { - bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument; - bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply")); - } else { - bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call")); - } - } else { - bareSuperNode = (0, _babelHelperOptimiseCallExpression2.default)(t.logicalExpression("||", t.memberExpression(this.classRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.classRef])), t.thisExpression(), bareSuperNode.arguments); - } - - var call = t.callExpression(this.file.addHelper("possibleConstructorReturn"), [t.thisExpression(), bareSuperNode]); - - var bareSuperAfter = this.bareSuperAfter.map(function (fn) { - return fn(thisRef); - }); - - if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { - - if (this.superThises.length || bareSuperAfter.length) { - bareSuper.scope.push({ id: thisRef }); - call = t.assignmentExpression("=", thisRef, call); - } - - if (bareSuperAfter.length) { - call = t.toSequenceExpression([call].concat(bareSuperAfter, [thisRef])); - } - - bareSuper.parentPath.replaceWith(t.returnStatement(call)); - } else { - bareSuper.replaceWithMultiple([t.variableDeclaration("var", [t.variableDeclarator(thisRef, call)])].concat(bareSuperAfter, [t.expressionStatement(thisRef)])); - } - }; - - ClassTransformer.prototype.verifyConstructor = function verifyConstructor() { - var _this2 = this; - - if (!this.isDerived) return; - - var path = this.userConstructorPath; - var body = path.get("body"); - - path.traverse(findThisesVisitor, this); - - var guaranteedSuperBeforeFinish = !!this.bareSupers.length; - - var superRef = this.superName || t.identifier("Function"); - var thisRef = path.scope.generateUidIdentifier("this"); - - for (var _iterator3 = this.bareSupers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var bareSuper = _ref3; - - this.wrapSuperCall(bareSuper, superRef, thisRef, body); - - if (guaranteedSuperBeforeFinish) { - bareSuper.find(function (parentPath) { - if (parentPath === path) { - return true; - } - - if (parentPath.isLoop() || parentPath.isConditional()) { - guaranteedSuperBeforeFinish = false; - return true; - } - }); - } - } - - for (var _iterator4 = this.superThises, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var thisPath = _ref4; - - thisPath.replaceWith(thisRef); - } - - var wrapReturn = function wrapReturn(returnArg) { - return t.callExpression(_this2.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || [])); - }; - - var bodyPaths = body.get("body"); - if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { - body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); - } - - for (var _iterator5 = this.superReturns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var returnPath = _ref5; - - if (returnPath.node.argument) { - var ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); - returnPath.get("argument").replaceWithMultiple([t.assignmentExpression("=", ref, returnPath.node.argument), wrapReturn(ref)]); - } else { - returnPath.get("argument").replaceWith(wrapReturn()); - } - } - }; - - ClassTransformer.prototype.pushMethod = function pushMethod(node, path) { - var scope = path ? path.scope : this.scope; - - if (node.kind === "method") { - if (this._processMethod(node, scope)) return; - } - - this.pushToMap(node, false, null, scope); - }; - - ClassTransformer.prototype._processMethod = function _processMethod() { - return false; - }; - - ClassTransformer.prototype.pushConstructor = function pushConstructor(replaceSupers, method, path) { - this.bareSupers = replaceSupers.bareSupers; - this.superReturns = replaceSupers.returns; - - if (path.scope.hasOwnBinding(this.classRef.name)) { - path.scope.rename(this.classRef.name); - } - - var construct = this.constructor; - - this.userConstructorPath = path; - this.userConstructor = method; - this.hasConstructor = true; - - t.inheritsComments(construct, method); - - construct._ignoreUserWhitespace = true; - construct.params = method.params; - - t.inherits(construct.body, method.body); - construct.body.directives = method.body.directives; - - this._pushConstructor(); - }; - - ClassTransformer.prototype._pushConstructor = function _pushConstructor() { - if (this.pushedConstructor) return; - this.pushedConstructor = true; - - if (this.hasInstanceDescriptors || this.hasStaticDescriptors) { - this.pushDescriptors(); - } - - this.body.push(this.constructor); - - this.pushInherits(); - }; - - ClassTransformer.prototype.pushInherits = function pushInherits() { - if (!this.isDerived || this.pushedInherits) return; - - this.pushedInherits = true; - this.body.unshift(t.expressionStatement(t.callExpression(this.file.addHelper("inherits"), [this.classRef, this.superName]))); - }; - - return ClassTransformer; -}(); - -exports.default = ClassTransformer; -module.exports = exports["default"]; -},{"babel-helper-define-map":52,"babel-helper-optimise-call-expression":56,"babel-helper-replace-supers":58,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-template":114,"babel-traverse":118,"babel-types":151}],71:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (_ref) { - var t = _ref.types, - template = _ref.template; - - var buildMutatorMapAssign = template("\n MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {};\n MUTATOR_MAP_REF[KEY].KIND = VALUE;\n "); - - function getValue(prop) { - if (t.isObjectProperty(prop)) { - return prop.value; - } else if (t.isObjectMethod(prop)) { - return t.functionExpression(null, prop.params, prop.body, prop.generator, prop.async); - } - } - - function pushAssign(objId, prop, body) { - if (prop.kind === "get" && prop.kind === "set") { - pushMutatorDefine(objId, prop, body); - } else { - body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(objId, prop.key, prop.computed || t.isLiteral(prop.key)), getValue(prop)))); - } - } - - function pushMutatorDefine(_ref2, prop) { - var objId = _ref2.objId, - body = _ref2.body, - getMutatorId = _ref2.getMutatorId, - scope = _ref2.scope; - - var key = !prop.computed && t.isIdentifier(prop.key) ? t.stringLiteral(prop.key.name) : prop.key; - - var maybeMemoise = scope.maybeGenerateMemoised(key); - if (maybeMemoise) { - body.push(t.expressionStatement(t.assignmentExpression("=", maybeMemoise, key))); - key = maybeMemoise; - } - - body.push.apply(body, buildMutatorMapAssign({ - MUTATOR_MAP_REF: getMutatorId(), - KEY: key, - VALUE: getValue(prop), - KIND: t.identifier(prop.kind) - })); - } - - function loose(info) { - for (var _iterator = info.computedProps, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref3; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref3 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref3 = _i.value; - } - - var prop = _ref3; - - if (prop.kind === "get" || prop.kind === "set") { - pushMutatorDefine(info, prop); - } else { - pushAssign(info.objId, prop, info.body); - } - } - } - - function spec(info) { - var objId = info.objId, - body = info.body, - computedProps = info.computedProps, - state = info.state; - - - for (var _iterator2 = computedProps, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref4; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref4 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref4 = _i2.value; - } - - var prop = _ref4; - - var key = t.toComputedKey(prop); - - if (prop.kind === "get" || prop.kind === "set") { - pushMutatorDefine(info, prop); - } else if (t.isStringLiteral(key, { value: "__proto__" })) { - pushAssign(objId, prop, body); - } else { - if (computedProps.length === 1) { - return t.callExpression(state.addHelper("defineProperty"), [info.initPropExpression, key, getValue(prop)]); - } else { - body.push(t.expressionStatement(t.callExpression(state.addHelper("defineProperty"), [objId, key, getValue(prop)]))); - } - } - } - } - - return { - visitor: { - ObjectExpression: { - exit: function exit(path, state) { - var node = path.node, - parent = path.parent, - scope = path.scope; - - var hasComputed = false; - for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref5; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref5 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref5 = _i3.value; - } - - var prop = _ref5; - - hasComputed = prop.computed === true; - if (hasComputed) break; - } - if (!hasComputed) return; - - var initProps = []; - var computedProps = []; - var foundComputed = false; - - for (var _iterator4 = node.properties, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref6; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref6 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref6 = _i4.value; - } - - var _prop = _ref6; - - if (_prop.computed) { - foundComputed = true; - } - - if (foundComputed) { - computedProps.push(_prop); - } else { - initProps.push(_prop); - } - } - - var objId = scope.generateUidIdentifierBasedOnNode(parent); - var initPropExpression = t.objectExpression(initProps); - var body = []; - - body.push(t.variableDeclaration("var", [t.variableDeclarator(objId, initPropExpression)])); - - var callback = spec; - if (state.opts.loose) callback = loose; - - var mutatorRef = void 0; - - var getMutatorId = function getMutatorId() { - if (!mutatorRef) { - mutatorRef = scope.generateUidIdentifier("mutatorMap"); - - body.push(t.variableDeclaration("var", [t.variableDeclarator(mutatorRef, t.objectExpression([]))])); - } - - return mutatorRef; - }; - - var single = callback({ - scope: scope, - objId: objId, - body: body, - computedProps: computedProps, - initPropExpression: initPropExpression, - getMutatorId: getMutatorId, - state: state - }); - - if (mutatorRef) { - body.push(t.expressionStatement(t.callExpression(state.addHelper("defineEnumerableProperties"), [objId, mutatorRef]))); - } - - if (single) { - path.replaceWith(single); - } else { - body.push(t.expressionStatement(objId)); - path.replaceWithMultiple(body); - } - } - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],72:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (_ref) { - var t = _ref.types; - - - function variableDeclarationHasPattern(node) { - for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var declar = _ref2; - - if (t.isPattern(declar.id)) { - return true; - } - } - return false; - } - - function hasRest(pattern) { - for (var _iterator2 = pattern.elements, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - var elem = _ref3; - - if (t.isRestElement(elem)) { - return true; - } - } - return false; - } - - var arrayUnpackVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (state.bindings[path.node.name]) { - state.deopt = true; - path.stop(); - } - } - }; - - var DestructuringTransformer = function () { - function DestructuringTransformer(opts) { - (0, _classCallCheck3.default)(this, DestructuringTransformer); - - this.blockHoist = opts.blockHoist; - this.operator = opts.operator; - this.arrays = {}; - this.nodes = opts.nodes || []; - this.scope = opts.scope; - this.file = opts.file; - this.kind = opts.kind; - } - - DestructuringTransformer.prototype.buildVariableAssignment = function buildVariableAssignment(id, init) { - var op = this.operator; - if (t.isMemberExpression(id)) op = "="; - - var node = void 0; - - if (op) { - node = t.expressionStatement(t.assignmentExpression(op, id, init)); - } else { - node = t.variableDeclaration(this.kind, [t.variableDeclarator(id, init)]); - } - - node._blockHoist = this.blockHoist; - - return node; - }; - - DestructuringTransformer.prototype.buildVariableDeclaration = function buildVariableDeclaration(id, init) { - var declar = t.variableDeclaration("var", [t.variableDeclarator(id, init)]); - declar._blockHoist = this.blockHoist; - return declar; - }; - - DestructuringTransformer.prototype.push = function push(id, init) { - if (t.isObjectPattern(id)) { - this.pushObjectPattern(id, init); - } else if (t.isArrayPattern(id)) { - this.pushArrayPattern(id, init); - } else if (t.isAssignmentPattern(id)) { - this.pushAssignmentPattern(id, init); - } else { - this.nodes.push(this.buildVariableAssignment(id, init)); - } - }; - - DestructuringTransformer.prototype.toArray = function toArray(node, count) { - if (this.file.opts.loose || t.isIdentifier(node) && this.arrays[node.name]) { - return node; - } else { - return this.scope.toArray(node, count); - } - }; - - DestructuringTransformer.prototype.pushAssignmentPattern = function pushAssignmentPattern(pattern, valueRef) { - - var tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef); - - var declar = t.variableDeclaration("var", [t.variableDeclarator(tempValueRef, valueRef)]); - declar._blockHoist = this.blockHoist; - this.nodes.push(declar); - - var tempConditional = t.conditionalExpression(t.binaryExpression("===", tempValueRef, t.identifier("undefined")), pattern.right, tempValueRef); - - var left = pattern.left; - if (t.isPattern(left)) { - var tempValueDefault = t.expressionStatement(t.assignmentExpression("=", tempValueRef, tempConditional)); - tempValueDefault._blockHoist = this.blockHoist; - - this.nodes.push(tempValueDefault); - this.push(left, tempValueRef); - } else { - this.nodes.push(this.buildVariableAssignment(left, tempConditional)); - } - }; - - DestructuringTransformer.prototype.pushObjectRest = function pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex) { - - var keys = []; - - for (var i = 0; i < pattern.properties.length; i++) { - var prop = pattern.properties[i]; - - if (i >= spreadPropIndex) break; - - if (t.isRestProperty(prop)) continue; - - var key = prop.key; - if (t.isIdentifier(key) && !prop.computed) key = t.stringLiteral(prop.key.name); - keys.push(key); - } - - keys = t.arrayExpression(keys); - - var value = t.callExpression(this.file.addHelper("objectWithoutProperties"), [objRef, keys]); - this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value)); - }; - - DestructuringTransformer.prototype.pushObjectProperty = function pushObjectProperty(prop, propRef) { - if (t.isLiteral(prop.key)) prop.computed = true; - - var pattern = prop.value; - var objRef = t.memberExpression(propRef, prop.key, prop.computed); - - if (t.isPattern(pattern)) { - this.push(pattern, objRef); - } else { - this.nodes.push(this.buildVariableAssignment(pattern, objRef)); - } - }; - - DestructuringTransformer.prototype.pushObjectPattern = function pushObjectPattern(pattern, objRef) { - - if (!pattern.properties.length) { - this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("objectDestructuringEmpty"), [objRef]))); - } - - if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) { - var temp = this.scope.generateUidIdentifierBasedOnNode(objRef); - this.nodes.push(this.buildVariableDeclaration(temp, objRef)); - objRef = temp; - } - - for (var i = 0; i < pattern.properties.length; i++) { - var prop = pattern.properties[i]; - if (t.isRestProperty(prop)) { - this.pushObjectRest(pattern, objRef, prop, i); - } else { - this.pushObjectProperty(prop, objRef); - } - } - }; - - DestructuringTransformer.prototype.canUnpackArrayPattern = function canUnpackArrayPattern(pattern, arr) { - if (!t.isArrayExpression(arr)) return false; - - if (pattern.elements.length > arr.elements.length) return; - if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false; - - for (var _iterator3 = pattern.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } - - var elem = _ref4; - - if (!elem) return false; - - if (t.isMemberExpression(elem)) return false; - } - - for (var _iterator4 = arr.elements, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref5; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref5 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref5 = _i4.value; - } - - var _elem = _ref5; - - if (t.isSpreadElement(_elem)) return false; - - if (t.isCallExpression(_elem)) return false; - - if (t.isMemberExpression(_elem)) return false; - } - - var bindings = t.getBindingIdentifiers(pattern); - var state = { deopt: false, bindings: bindings }; - this.scope.traverse(arr, arrayUnpackVisitor, state); - return !state.deopt; - }; - - DestructuringTransformer.prototype.pushUnpackedArrayPattern = function pushUnpackedArrayPattern(pattern, arr) { - for (var i = 0; i < pattern.elements.length; i++) { - var elem = pattern.elements[i]; - if (t.isRestElement(elem)) { - this.push(elem.argument, t.arrayExpression(arr.elements.slice(i))); - } else { - this.push(elem, arr.elements[i]); - } - } - }; - - DestructuringTransformer.prototype.pushArrayPattern = function pushArrayPattern(pattern, arrayRef) { - if (!pattern.elements) return; - - if (this.canUnpackArrayPattern(pattern, arrayRef)) { - return this.pushUnpackedArrayPattern(pattern, arrayRef); - } - - var count = !hasRest(pattern) && pattern.elements.length; - - var toArray = this.toArray(arrayRef, count); - - if (t.isIdentifier(toArray)) { - arrayRef = toArray; - } else { - arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef); - this.arrays[arrayRef.name] = true; - this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray)); - } - - for (var i = 0; i < pattern.elements.length; i++) { - var elem = pattern.elements[i]; - - if (!elem) continue; - - var elemRef = void 0; - - if (t.isRestElement(elem)) { - elemRef = this.toArray(arrayRef); - elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.numericLiteral(i)]); - - elem = elem.argument; - } else { - elemRef = t.memberExpression(arrayRef, t.numericLiteral(i), true); - } - - this.push(elem, elemRef); - } - }; - - DestructuringTransformer.prototype.init = function init(pattern, ref) { - - if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref)) { - var memo = this.scope.maybeGenerateMemoised(ref, true); - if (memo) { - this.nodes.push(this.buildVariableDeclaration(memo, ref)); - ref = memo; - } - } - - this.push(pattern, ref); - - return this.nodes; - }; - - return DestructuringTransformer; - }(); - - return { - visitor: { - ExportNamedDeclaration: function ExportNamedDeclaration(path) { - var declaration = path.get("declaration"); - if (!declaration.isVariableDeclaration()) return; - if (!variableDeclarationHasPattern(declaration.node)) return; - - var specifiers = []; - - for (var name in path.getOuterBindingIdentifiers(path)) { - var id = t.identifier(name); - specifiers.push(t.exportSpecifier(id, id)); - } - - path.replaceWith(declaration.node); - path.insertAfter(t.exportNamedDeclaration(null, specifiers)); - }, - ForXStatement: function ForXStatement(path, file) { - var node = path.node, - scope = path.scope; - - var left = node.left; - - if (t.isPattern(left)) { - - var temp = scope.generateUidIdentifier("ref"); - - node.left = t.variableDeclaration("var", [t.variableDeclarator(temp)]); - - path.ensureBlock(); - - node.body.body.unshift(t.variableDeclaration("var", [t.variableDeclarator(left, temp)])); - - return; - } - - if (!t.isVariableDeclaration(left)) return; - - var pattern = left.declarations[0].id; - if (!t.isPattern(pattern)) return; - - var key = scope.generateUidIdentifier("ref"); - node.left = t.variableDeclaration(left.kind, [t.variableDeclarator(key, null)]); - - var nodes = []; - - var destructuring = new DestructuringTransformer({ - kind: left.kind, - file: file, - scope: scope, - nodes: nodes - }); - - destructuring.init(pattern, key); - - path.ensureBlock(); - - var block = node.body; - block.body = nodes.concat(block.body); - }, - CatchClause: function CatchClause(_ref6, file) { - var node = _ref6.node, - scope = _ref6.scope; - - var pattern = node.param; - if (!t.isPattern(pattern)) return; - - var ref = scope.generateUidIdentifier("ref"); - node.param = ref; - - var nodes = []; - - var destructuring = new DestructuringTransformer({ - kind: "let", - file: file, - scope: scope, - nodes: nodes - }); - destructuring.init(pattern, ref); - - node.body.body = nodes.concat(node.body.body); - }, - AssignmentExpression: function AssignmentExpression(path, file) { - var node = path.node, - scope = path.scope; - - if (!t.isPattern(node.left)) return; - - var nodes = []; - - var destructuring = new DestructuringTransformer({ - operator: node.operator, - file: file, - scope: scope, - nodes: nodes - }); - - var ref = void 0; - if (path.isCompletionRecord() || !path.parentPath.isExpressionStatement()) { - ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref"); - - nodes.push(t.variableDeclaration("var", [t.variableDeclarator(ref, node.right)])); - - if (t.isArrayExpression(node.right)) { - destructuring.arrays[ref.name] = true; - } - } - - destructuring.init(node.left, ref || node.right); - - if (ref) { - nodes.push(t.expressionStatement(ref)); - } - - path.replaceWithMultiple(nodes); - }, - VariableDeclaration: function VariableDeclaration(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - - if (t.isForXStatement(parent)) return; - if (!parent || !path.container) return; - if (!variableDeclarationHasPattern(node)) return; - - var nodes = []; - var declar = void 0; - - for (var i = 0; i < node.declarations.length; i++) { - declar = node.declarations[i]; - - var patternId = declar.init; - var pattern = declar.id; - - var destructuring = new DestructuringTransformer({ - blockHoist: node._blockHoist, - nodes: nodes, - scope: scope, - kind: node.kind, - file: file - }); - - if (t.isPattern(pattern)) { - destructuring.init(pattern, patternId); - - if (+i !== node.declarations.length - 1) { - t.inherits(nodes[nodes.length - 1], declar); - } - } else { - nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar)); - } - } - - var nodesOut = []; - for (var _iterator5 = nodes, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref7; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref7 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref7 = _i5.value; - } - - var _node = _ref7; - - var tail = nodesOut[nodesOut.length - 1]; - if (tail && t.isVariableDeclaration(tail) && t.isVariableDeclaration(_node) && tail.kind === _node.kind) { - var _tail$declarations; - - (_tail$declarations = tail.declarations).push.apply(_tail$declarations, _node.declarations); - } else { - nodesOut.push(_node); - } - } - - for (var _iterator6 = nodesOut, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref8; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref8 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref8 = _i6.value; - } - - var nodeOut = _ref8; - - if (!nodeOut.declarations) continue; - for (var _iterator7 = nodeOut.declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref9; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref9 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref9 = _i7.value; - } - - var declaration = _ref9; - var name = declaration.id.name; - - if (scope.bindings[name]) { - scope.bindings[name].kind = nodeOut.kind; - } - } - } - - if (nodesOut.length === 1) { - path.replaceWith(nodesOut[0]); - } else { - path.replaceWithMultiple(nodesOut); - } - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109}],73:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -exports.default = function () { - return { - visitor: { - ObjectExpression: function ObjectExpression(path) { - var node = path.node; - - var plainProps = node.properties.filter(function (prop) { - return !t.isSpreadProperty(prop) && !prop.computed; - }); - - var alreadySeenData = (0, _create2.default)(null); - var alreadySeenGetters = (0, _create2.default)(null); - var alreadySeenSetters = (0, _create2.default)(null); - - for (var _iterator = plainProps, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var prop = _ref; - - var name = getName(prop.key); - var isDuplicate = false; - switch (prop.kind) { - case "get": - if (alreadySeenData[name] || alreadySeenGetters[name]) { - isDuplicate = true; - } - alreadySeenGetters[name] = true; - break; - case "set": - if (alreadySeenData[name] || alreadySeenSetters[name]) { - isDuplicate = true; - } - alreadySeenSetters[name] = true; - break; - default: - if (alreadySeenData[name] || alreadySeenGetters[name] || alreadySeenSetters[name]) { - isDuplicate = true; - } - alreadySeenData[name] = true; - } - - if (isDuplicate) { - prop.computed = true; - prop.key = t.stringLiteral(name); - } - } - } - } - }; -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getName(key) { - if (t.isIdentifier(key)) { - return key.name; - } - return key.value.toString(); -} - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-types":151}],74:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (_ref) { - var messages = _ref.messages, - template = _ref.template, - t = _ref.types; - - var buildForOfArray = template("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "); - - var buildForOfLoose = template("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "); - - var buildForOf = template("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n "); - - - function _ForOfStatementArray(path) { - var node = path.node, - scope = path.scope; - - var nodes = []; - var right = node.right; - - if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { - var uid = scope.generateUidIdentifier("arr"); - nodes.push(t.variableDeclaration("var", [t.variableDeclarator(uid, right)])); - right = uid; - } - - var iterationKey = scope.generateUidIdentifier("i"); - - var loop = buildForOfArray({ - BODY: node.body, - KEY: iterationKey, - ARR: right - }); - - t.inherits(loop, node); - t.ensureBlock(loop); - - var iterationValue = t.memberExpression(right, iterationKey, true); - - var left = node.left; - if (t.isVariableDeclaration(left)) { - left.declarations[0].init = iterationValue; - loop.body.body.unshift(left); - } else { - loop.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", left, iterationValue))); - } - - if (path.parentPath.isLabeledStatement()) { - loop = t.labeledStatement(path.parentPath.node.label, loop); - } - - nodes.push(loop); - - return nodes; - } - - return { - visitor: { - ForOfStatement: function ForOfStatement(path, state) { - if (path.get("right").isArrayExpression()) { - if (path.parentPath.isLabeledStatement()) { - return path.parentPath.replaceWithMultiple(_ForOfStatementArray(path)); - } else { - return path.replaceWithMultiple(_ForOfStatementArray(path)); - } - } - - var callback = spec; - if (state.opts.loose) callback = loose; - - var node = path.node; - - var build = callback(path, state); - var declar = build.declar; - var loop = build.loop; - var block = loop.body; - - path.ensureBlock(); - - if (declar) { - block.body.push(declar); - } - - block.body = block.body.concat(node.body.body); - - t.inherits(loop, node); - t.inherits(loop.body, node.body); - - if (build.replaceParent) { - path.parentPath.replaceWithMultiple(build.node); - path.remove(); - } else { - path.replaceWithMultiple(build.node); - } - } - } - }; - - function loose(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - var left = node.left; - - var declar = void 0, - id = void 0; - - if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { - id = left; - } else if (t.isVariableDeclaration(left)) { - id = scope.generateUidIdentifier("ref"); - declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, id)]); - } else { - throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); - } - - var iteratorKey = scope.generateUidIdentifier("iterator"); - var isArrayKey = scope.generateUidIdentifier("isArray"); - - var loop = buildForOfLoose({ - LOOP_OBJECT: iteratorKey, - IS_ARRAY: isArrayKey, - OBJECT: node.right, - INDEX: scope.generateUidIdentifier("i"), - ID: id - }); - - if (!declar) { - loop.body.body.shift(); - } - - var isLabeledParent = t.isLabeledStatement(parent); - var labeled = void 0; - - if (isLabeledParent) { - labeled = t.labeledStatement(parent.label, loop); - } - - return { - replaceParent: isLabeledParent, - declar: declar, - node: labeled || loop, - loop: loop - }; - } - - function spec(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - - var left = node.left; - var declar = void 0; - - var stepKey = scope.generateUidIdentifier("step"); - var stepValue = t.memberExpression(stepKey, t.identifier("value")); - - if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { - declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue)); - } else if (t.isVariableDeclaration(left)) { - declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]); - } else { - throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); - } - - var iteratorKey = scope.generateUidIdentifier("iterator"); - - var template = buildForOf({ - ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), - ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), - ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), - ITERATOR_KEY: iteratorKey, - STEP_KEY: stepKey, - OBJECT: node.right, - BODY: null - }); - - var isLabeledParent = t.isLabeledStatement(parent); - - var tryBody = template[3].block.body; - var loop = tryBody[0]; - - if (isLabeledParent) { - tryBody[0] = t.labeledStatement(parent.label, loop); - } - - return { - replaceParent: isLabeledParent, - declar: declar, - loop: loop, - node: template - }; - } -}; - -module.exports = exports["default"]; -},{}],75:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - visitor: { - FunctionExpression: { - exit: function exit(path) { - if (path.key !== "value" && !path.parentPath.isObjectProperty()) { - var replacement = (0, _babelHelperFunctionName2.default)(path); - if (replacement) path.replaceWith(replacement); - } - } - }, - - ObjectProperty: function ObjectProperty(path) { - var value = path.get("value"); - if (value.isFunction()) { - var newNode = (0, _babelHelperFunctionName2.default)(value); - if (newNode) value.replaceWith(newNode); - } - } - } - }; -}; - -var _babelHelperFunctionName = require("babel-helper-function-name"); - -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-helper-function-name":53}],76:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - visitor: { - NumericLiteral: function NumericLiteral(_ref) { - var node = _ref.node; - - if (node.extra && /^0[ob]/i.test(node.extra.raw)) { - node.extra = undefined; - } - }, - StringLiteral: function StringLiteral(_ref2) { - var node = _ref2.node; - - if (node.extra && /\\[u]/gi.test(node.extra.raw)) { - node.extra = undefined; - } - } - } - }; -}; - -module.exports = exports["default"]; -},{}],77:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -exports.default = function (_ref) { - var t = _ref.types; - - function isValidRequireCall(path) { - if (!path.isCallExpression()) return false; - if (!path.get("callee").isIdentifier({ name: "require" })) return false; - if (path.scope.getBinding("require")) return false; - - var args = path.get("arguments"); - if (args.length !== 1) return false; - - var arg = args[0]; - if (!arg.isStringLiteral()) return false; - - return true; - } - - var amdVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(_ref2) { - var node = _ref2.node, - scope = _ref2.scope; - - if (node.name === "exports" && !scope.getBinding("exports")) { - this.hasExports = true; - } - - if (node.name === "module" && !scope.getBinding("module")) { - this.hasModule = true; - } - }, - CallExpression: function CallExpression(path) { - if (!isValidRequireCall(path)) return; - this.bareSources.push(path.node.arguments[0]); - path.remove(); - }, - VariableDeclarator: function VariableDeclarator(path) { - var id = path.get("id"); - if (!id.isIdentifier()) return; - - var init = path.get("init"); - if (!isValidRequireCall(init)) return; - - var source = init.node.arguments[0]; - this.sourceNames[source.value] = true; - this.sources.push([id.node, source]); - - path.remove(); - } - }; - - return { - inherits: require("babel-plugin-transform-es2015-modules-commonjs"), - - pre: function pre() { - this.sources = []; - this.sourceNames = (0, _create2.default)(null); - - this.bareSources = []; - - this.hasExports = false; - this.hasModule = false; - }, - - - visitor: { - Program: { - exit: function exit(path) { - var _this = this; - - if (this.ran) return; - this.ran = true; - - path.traverse(amdVisitor, this); - - var params = this.sources.map(function (source) { - return source[0]; - }); - var sources = this.sources.map(function (source) { - return source[1]; - }); - - sources = sources.concat(this.bareSources.filter(function (str) { - return !_this.sourceNames[str.value]; - })); - - var moduleName = this.getModuleName(); - if (moduleName) moduleName = t.stringLiteral(moduleName); - - if (this.hasExports) { - sources.unshift(t.stringLiteral("exports")); - params.unshift(t.identifier("exports")); - } - - if (this.hasModule) { - sources.unshift(t.stringLiteral("module")); - params.unshift(t.identifier("module")); - } - - var node = path.node; - - var factory = buildFactory({ - PARAMS: params, - BODY: node.body - }); - factory.expression.body.directives = node.directives; - node.directives = []; - - node.body = [buildDefine({ - MODULE_NAME: moduleName, - SOURCES: sources, - FACTORY: factory - })]; - } - } - } - }; -}; - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildDefine = (0, _babelTemplate2.default)("\n define(MODULE_NAME, [SOURCES], FACTORY);\n"); - -var buildFactory = (0, _babelTemplate2.default)("\n (function (PARAMS) {\n BODY;\n })\n"); - -module.exports = exports["default"]; -},{"babel-plugin-transform-es2015-modules-commonjs":78,"babel-runtime/core-js/object/create":100,"babel-template":114}],78:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function () { - var REASSIGN_REMAP_SKIP = (0, _symbol2.default)(); - - var reassignmentVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path) { - var name = path.node.name; - var remap = this.remaps[name]; - if (!remap) return; - - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - - if (path.parentPath.isCallExpression({ callee: path.node })) { - path.replaceWith(t.sequenceExpression([t.numericLiteral(0), remap])); - } else if (path.isJSXIdentifier() && t.isMemberExpression(remap)) { - var object = remap.object, - property = remap.property; - - path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name))); - } else { - path.replaceWith(remap); - } - this.requeueInParent(path); - }, - AssignmentExpression: function AssignmentExpression(path) { - var node = path.node; - if (node[REASSIGN_REMAP_SKIP]) return; - - var left = path.get("left"); - if (left.isIdentifier()) { - var name = left.node.name; - var exports = this.exports[name]; - if (!exports) return; - - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - - node[REASSIGN_REMAP_SKIP] = true; - - for (var _iterator = exports, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var reid = _ref; - - node = buildExportsAssignment(reid, node).expression; - } - - path.replaceWith(node); - this.requeueInParent(path); - } else if (left.isObjectPattern()) { - for (var _iterator2 = left.node.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var property = _ref2; - - var _name = property.value.name; - - var _exports = this.exports[_name]; - if (!_exports) continue; - - if (this.scope.getBinding(_name) !== path.scope.getBinding(_name)) return; - - node[REASSIGN_REMAP_SKIP] = true; - - path.insertAfter(buildExportsAssignment(t.identifier(_name), t.identifier(_name))); - } - } else if (left.isArrayPattern()) { - for (var _iterator3 = left.node.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var element = _ref3; - - if (!element) continue; - var _name2 = element.name; - - var _exports2 = this.exports[_name2]; - if (!_exports2) continue; - - if (this.scope.getBinding(_name2) !== path.scope.getBinding(_name2)) return; - - node[REASSIGN_REMAP_SKIP] = true; - - path.insertAfter(buildExportsAssignment(t.identifier(_name2), t.identifier(_name2))); - } - } - }, - UpdateExpression: function UpdateExpression(path) { - var arg = path.get("argument"); - if (!arg.isIdentifier()) return; - - var name = arg.node.name; - var exports = this.exports[name]; - if (!exports) return; - - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - - var node = t.assignmentExpression(path.node.operator[0] + "=", arg.node, t.numericLiteral(1)); - - if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord() || path.node.prefix) { - path.replaceWith(node); - this.requeueInParent(path); - return; - } - - var nodes = []; - nodes.push(node); - - var operator = void 0; - if (path.node.operator === "--") { - operator = "+"; - } else { - operator = "-"; - } - nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1))); - - path.replaceWithMultiple(t.sequenceExpression(nodes)); - } - }; - - return { - inherits: _babelPluginTransformStrictMode2.default, - - visitor: { - ThisExpression: function ThisExpression(path, state) { - if (this.ranCommonJS) return; - - if (state.opts.allowTopLevelThis !== true && !path.findParent(function (path) { - return !path.is("shadow") && THIS_BREAK_KEYS.indexOf(path.type) >= 0; - })) { - path.replaceWith(t.identifier("undefined")); - } - }, - - - Program: { - exit: function exit(path) { - this.ranCommonJS = true; - - var strict = !!this.opts.strict; - var noInterop = !!this.opts.noInterop; - - var scope = path.scope; - - scope.rename("module"); - scope.rename("exports"); - scope.rename("require"); - - var hasExports = false; - var hasImports = false; - - var body = path.get("body"); - var imports = (0, _create2.default)(null); - var exports = (0, _create2.default)(null); - - var nonHoistedExportNames = (0, _create2.default)(null); - - var topNodes = []; - var remaps = (0, _create2.default)(null); - - var requires = (0, _create2.default)(null); - - function addRequire(source, blockHoist) { - var cached = requires[source]; - if (cached) return cached; - - var ref = path.scope.generateUidIdentifier((0, _path2.basename)(source, (0, _path2.extname)(source))); - - var varDecl = t.variableDeclaration("var", [t.variableDeclarator(ref, buildRequire(t.stringLiteral(source)).expression)]); - - if (imports[source]) { - varDecl.loc = imports[source].loc; - } - - if (typeof blockHoist === "number" && blockHoist > 0) { - varDecl._blockHoist = blockHoist; - } - - topNodes.push(varDecl); - - return requires[source] = ref; - } - - function addTo(obj, key, arr) { - var existing = obj[key] || []; - obj[key] = existing.concat(arr); - } - - for (var _iterator4 = body, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var _path = _ref4; - - if (_path.isExportDeclaration()) { - hasExports = true; - - var specifiers = [].concat(_path.get("declaration"), _path.get("specifiers")); - for (var _iterator6 = specifiers, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } - - var _specifier2 = _ref6; - - var ids = _specifier2.getBindingIdentifiers(); - if (ids.__esModule) { - throw _specifier2.buildCodeFrameError("Illegal export \"__esModule\""); - } - } - } - - if (_path.isImportDeclaration()) { - var _importsEntry$specifi; - - hasImports = true; - - var key = _path.node.source.value; - var importsEntry = imports[key] || { - specifiers: [], - maxBlockHoist: 0, - loc: _path.node.loc - }; - - (_importsEntry$specifi = importsEntry.specifiers).push.apply(_importsEntry$specifi, _path.node.specifiers); - - if (typeof _path.node._blockHoist === "number") { - importsEntry.maxBlockHoist = Math.max(_path.node._blockHoist, importsEntry.maxBlockHoist); - } - - imports[key] = importsEntry; - - _path.remove(); - } else if (_path.isExportDefaultDeclaration()) { - var declaration = _path.get("declaration"); - if (declaration.isFunctionDeclaration()) { - var id = declaration.node.id; - var defNode = t.identifier("default"); - if (id) { - addTo(exports, id.name, defNode); - topNodes.push(buildExportsAssignment(defNode, id)); - _path.replaceWith(declaration.node); - } else { - topNodes.push(buildExportsAssignment(defNode, t.toExpression(declaration.node))); - _path.remove(); - } - } else if (declaration.isClassDeclaration()) { - var _id = declaration.node.id; - var _defNode = t.identifier("default"); - if (_id) { - addTo(exports, _id.name, _defNode); - _path.replaceWithMultiple([declaration.node, buildExportsAssignment(_defNode, _id)]); - } else { - _path.replaceWith(buildExportsAssignment(_defNode, t.toExpression(declaration.node))); - - _path.parentPath.requeue(_path.get("expression.left")); - } - } else { - _path.replaceWith(buildExportsAssignment(t.identifier("default"), declaration.node)); - - _path.parentPath.requeue(_path.get("expression.left")); - } - } else if (_path.isExportNamedDeclaration()) { - var _declaration = _path.get("declaration"); - if (_declaration.node) { - if (_declaration.isFunctionDeclaration()) { - var _id2 = _declaration.node.id; - addTo(exports, _id2.name, _id2); - topNodes.push(buildExportsAssignment(_id2, _id2)); - _path.replaceWith(_declaration.node); - } else if (_declaration.isClassDeclaration()) { - var _id3 = _declaration.node.id; - addTo(exports, _id3.name, _id3); - _path.replaceWithMultiple([_declaration.node, buildExportsAssignment(_id3, _id3)]); - nonHoistedExportNames[_id3.name] = true; - } else if (_declaration.isVariableDeclaration()) { - var declarators = _declaration.get("declarations"); - for (var _iterator7 = declarators, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } - - var decl = _ref7; - - var _id4 = decl.get("id"); - - var init = decl.get("init"); - var exportsToInsert = []; - if (!init.node) init.replaceWith(t.identifier("undefined")); - - if (_id4.isIdentifier()) { - addTo(exports, _id4.node.name, _id4.node); - init.replaceWith(buildExportsAssignment(_id4.node, init.node).expression); - nonHoistedExportNames[_id4.node.name] = true; - } else if (_id4.isObjectPattern()) { - for (var _i8 = 0; _i8 < _id4.node.properties.length; _i8++) { - var prop = _id4.node.properties[_i8]; - var propValue = prop.value; - if (t.isAssignmentPattern(propValue)) { - propValue = propValue.left; - } else if (t.isRestProperty(prop)) { - propValue = prop.argument; - } - addTo(exports, propValue.name, propValue); - exportsToInsert.push(buildExportsAssignment(propValue, propValue)); - nonHoistedExportNames[propValue.name] = true; - } - } else if (_id4.isArrayPattern() && _id4.node.elements) { - for (var _i9 = 0; _i9 < _id4.node.elements.length; _i9++) { - var elem = _id4.node.elements[_i9]; - if (!elem) continue; - if (t.isAssignmentPattern(elem)) { - elem = elem.left; - } else if (t.isRestElement(elem)) { - elem = elem.argument; - } - var name = elem.name; - addTo(exports, name, elem); - exportsToInsert.push(buildExportsAssignment(elem, elem)); - nonHoistedExportNames[name] = true; - } - } - _path.insertAfter(exportsToInsert); - } - _path.replaceWith(_declaration.node); - } - continue; - } - - var _specifiers = _path.get("specifiers"); - var nodes = []; - var _source = _path.node.source; - if (_source) { - var ref = addRequire(_source.value, _path.node._blockHoist); - - for (var _iterator8 = _specifiers, _isArray8 = Array.isArray(_iterator8), _i10 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; - - if (_isArray8) { - if (_i10 >= _iterator8.length) break; - _ref8 = _iterator8[_i10++]; - } else { - _i10 = _iterator8.next(); - if (_i10.done) break; - _ref8 = _i10.value; - } - - var _specifier3 = _ref8; - - if (_specifier3.isExportNamespaceSpecifier()) {} else if (_specifier3.isExportDefaultSpecifier()) {} else if (_specifier3.isExportSpecifier()) { - if (!noInterop && _specifier3.node.local.name === "default") { - topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(t.callExpression(this.addHelper("interopRequireDefault"), [ref]), _specifier3.node.local))); - } else { - topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(ref, _specifier3.node.local))); - } - nonHoistedExportNames[_specifier3.node.exported.name] = true; - } - } - } else { - for (var _iterator9 = _specifiers, _isArray9 = Array.isArray(_iterator9), _i11 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; - - if (_isArray9) { - if (_i11 >= _iterator9.length) break; - _ref9 = _iterator9[_i11++]; - } else { - _i11 = _iterator9.next(); - if (_i11.done) break; - _ref9 = _i11.value; - } - - var _specifier4 = _ref9; - - if (_specifier4.isExportSpecifier()) { - addTo(exports, _specifier4.node.local.name, _specifier4.node.exported); - nonHoistedExportNames[_specifier4.node.exported.name] = true; - nodes.push(buildExportsAssignment(_specifier4.node.exported, _specifier4.node.local)); - } - } - } - _path.replaceWithMultiple(nodes); - } else if (_path.isExportAllDeclaration()) { - var exportNode = buildExportAll({ - OBJECT: addRequire(_path.node.source.value, _path.node._blockHoist) - }); - exportNode.loc = _path.node.loc; - topNodes.push(exportNode); - _path.remove(); - } - } - - for (var source in imports) { - var _imports$source = imports[source], - specifiers = _imports$source.specifiers, - maxBlockHoist = _imports$source.maxBlockHoist; - - if (specifiers.length) { - var uid = addRequire(source, maxBlockHoist); - - var wildcard = void 0; - - for (var i = 0; i < specifiers.length; i++) { - var specifier = specifiers[i]; - if (t.isImportNamespaceSpecifier(specifier)) { - if (strict || noInterop) { - remaps[specifier.local.name] = uid; - } else { - var varDecl = t.variableDeclaration("var", [t.variableDeclarator(specifier.local, t.callExpression(this.addHelper("interopRequireWildcard"), [uid]))]); - - if (maxBlockHoist > 0) { - varDecl._blockHoist = maxBlockHoist; - } - - topNodes.push(varDecl); - } - wildcard = specifier.local; - } else if (t.isImportDefaultSpecifier(specifier)) { - specifiers[i] = t.importSpecifier(specifier.local, t.identifier("default")); - } - } - - for (var _iterator5 = specifiers, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var _specifier = _ref5; - - if (t.isImportSpecifier(_specifier)) { - var target = uid; - if (_specifier.imported.name === "default") { - if (wildcard) { - target = wildcard; - } else if (!noInterop) { - target = wildcard = path.scope.generateUidIdentifier(uid.name); - var _varDecl = t.variableDeclaration("var", [t.variableDeclarator(target, t.callExpression(this.addHelper("interopRequireDefault"), [uid]))]); - - if (maxBlockHoist > 0) { - _varDecl._blockHoist = maxBlockHoist; - } - - topNodes.push(_varDecl); - } - } - remaps[_specifier.local.name] = t.memberExpression(target, t.cloneWithoutLoc(_specifier.imported)); - } - } - } else { - var requireNode = buildRequire(t.stringLiteral(source)); - requireNode.loc = imports[source].loc; - topNodes.push(requireNode); - } - } - - if (hasImports && (0, _keys2.default)(nonHoistedExportNames).length) { - var maxHoistedExportsNodeAssignmentLength = 100; - var nonHoistedExportNamesArr = (0, _keys2.default)(nonHoistedExportNames); - - var _loop = function _loop(currentExportsNodeAssignmentLength) { - var nonHoistedExportNamesChunk = nonHoistedExportNamesArr.slice(currentExportsNodeAssignmentLength, currentExportsNodeAssignmentLength + maxHoistedExportsNodeAssignmentLength); - - var hoistedExportsNode = t.identifier("undefined"); - - nonHoistedExportNamesChunk.forEach(function (name) { - hoistedExportsNode = buildExportsAssignment(t.identifier(name), hoistedExportsNode).expression; - }); - - var node = t.expressionStatement(hoistedExportsNode); - node._blockHoist = 3; - - topNodes.unshift(node); - }; - - for (var currentExportsNodeAssignmentLength = 0; currentExportsNodeAssignmentLength < nonHoistedExportNamesArr.length; currentExportsNodeAssignmentLength += maxHoistedExportsNodeAssignmentLength) { - _loop(currentExportsNodeAssignmentLength); - } - } - - if (hasExports && !strict) { - var buildTemplate = buildExportsModuleDeclaration; - if (this.opts.loose) buildTemplate = buildLooseExportsModuleDeclaration; - - var declar = buildTemplate(); - declar._blockHoist = 3; - - topNodes.unshift(declar); - } - - path.unshiftContainer("body", topNodes); - path.traverse(reassignmentVisitor, { - remaps: remaps, - scope: scope, - exports: exports, - requeueInParent: function requeueInParent(newPath) { - return path.requeue(newPath); - } - }); - } - } - } - }; -}; - -var _path2 = require("path"); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelPluginTransformStrictMode = require("babel-plugin-transform-strict-mode"); - -var _babelPluginTransformStrictMode2 = _interopRequireDefault(_babelPluginTransformStrictMode); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildRequire = (0, _babelTemplate2.default)("\n require($0);\n"); - -var buildExportsModuleDeclaration = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n"); - -var buildExportsFrom = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, $0, {\n enumerable: true,\n get: function () {\n return $1;\n }\n });\n"); - -var buildLooseExportsModuleDeclaration = (0, _babelTemplate2.default)("\n exports.__esModule = true;\n"); - -var buildExportsAssignment = (0, _babelTemplate2.default)("\n exports.$0 = $1;\n"); - -var buildExportAll = (0, _babelTemplate2.default)("\n Object.keys(OBJECT).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return OBJECT[key];\n }\n });\n });\n"); - -var THIS_BREAK_KEYS = ["FunctionExpression", "FunctionDeclaration", "ClassProperty", "ClassMethod", "ObjectMethod"]; - -module.exports = exports["default"]; -},{"babel-plugin-transform-strict-mode":93,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/object/keys":102,"babel-runtime/core-js/symbol":104,"babel-template":114,"babel-types":151,"path":522}],79:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (_ref) { - var t = _ref.types; - - var IGNORE_REASSIGNMENT_SYMBOL = (0, _symbol2.default)(); - - var reassignmentVisitor = { - "AssignmentExpression|UpdateExpression": function AssignmentExpressionUpdateExpression(path) { - if (path.node[IGNORE_REASSIGNMENT_SYMBOL]) return; - path.node[IGNORE_REASSIGNMENT_SYMBOL] = true; - - var arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); - if (!arg.isIdentifier()) return; - - var name = arg.node.name; - - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - - var exportedNames = this.exports[name]; - if (!exportedNames) return; - - var node = path.node; - - var isPostUpdateExpression = path.isUpdateExpression() && !node.prefix; - if (isPostUpdateExpression) { - if (node.operator === "++") node = t.binaryExpression("+", node.argument, t.numericLiteral(1));else if (node.operator === "--") node = t.binaryExpression("-", node.argument, t.numericLiteral(1));else isPostUpdateExpression = false; - } - - for (var _iterator = exportedNames, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var exportedName = _ref2; - - node = this.buildCall(exportedName, node).expression; - } - - if (isPostUpdateExpression) node = t.sequenceExpression([node, path.node]); - - path.replaceWith(node); - } - }; - - return { - visitor: { - CallExpression: function CallExpression(path, state) { - if (path.node.callee.type === TYPE_IMPORT) { - var contextIdent = state.contextIdent; - path.replaceWith(t.callExpression(t.memberExpression(contextIdent, t.identifier("import")), path.node.arguments)); - } - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.node.name == "__moduleName" && !path.scope.hasBinding("__moduleName")) { - path.replaceWith(t.memberExpression(state.contextIdent, t.identifier("id"))); - } - }, - - - Program: { - enter: function enter(path, state) { - state.contextIdent = path.scope.generateUidIdentifier("context"); - }, - exit: function exit(path, state) { - var exportIdent = path.scope.generateUidIdentifier("export"); - var contextIdent = state.contextIdent; - - var exportNames = (0, _create2.default)(null); - var modules = []; - - var beforeBody = []; - var setters = []; - var sources = []; - var variableIds = []; - var removedPaths = []; - - function addExportName(key, val) { - exportNames[key] = exportNames[key] || []; - exportNames[key].push(val); - } - - function pushModule(source, key, specifiers) { - var module = void 0; - modules.forEach(function (m) { - if (m.key === source) { - module = m; - } - }); - if (!module) { - modules.push(module = { key: source, imports: [], exports: [] }); - } - module[key] = module[key].concat(specifiers); - } - - function buildExportCall(name, val) { - return t.expressionStatement(t.callExpression(exportIdent, [t.stringLiteral(name), val])); - } - - var body = path.get("body"); - - var canHoist = true; - for (var _iterator2 = body, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - var _path = _ref3; - - if (_path.isExportDeclaration()) _path = _path.get("declaration"); - if (_path.isVariableDeclaration() && _path.node.kind !== "var") { - canHoist = false; - break; - } - } - - for (var _iterator3 = body, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } - - var _path2 = _ref4; - - if (canHoist && _path2.isFunctionDeclaration()) { - beforeBody.push(_path2.node); - removedPaths.push(_path2); - } else if (_path2.isImportDeclaration()) { - var source = _path2.node.source.value; - pushModule(source, "imports", _path2.node.specifiers); - for (var name in _path2.getBindingIdentifiers()) { - _path2.scope.removeBinding(name); - variableIds.push(t.identifier(name)); - } - _path2.remove(); - } else if (_path2.isExportAllDeclaration()) { - pushModule(_path2.node.source.value, "exports", _path2.node); - _path2.remove(); - } else if (_path2.isExportDefaultDeclaration()) { - var declar = _path2.get("declaration"); - if (declar.isClassDeclaration() || declar.isFunctionDeclaration()) { - var id = declar.node.id; - var nodes = []; - - if (id) { - nodes.push(declar.node); - nodes.push(buildExportCall("default", id)); - addExportName(id.name, "default"); - } else { - nodes.push(buildExportCall("default", t.toExpression(declar.node))); - } - - if (!canHoist || declar.isClassDeclaration()) { - _path2.replaceWithMultiple(nodes); - } else { - beforeBody = beforeBody.concat(nodes); - removedPaths.push(_path2); - } - } else { - _path2.replaceWith(buildExportCall("default", declar.node)); - } - } else if (_path2.isExportNamedDeclaration()) { - var _declar = _path2.get("declaration"); - - if (_declar.node) { - _path2.replaceWith(_declar); - - var _nodes = []; - var bindingIdentifiers = void 0; - if (_path2.isFunction()) { - var node = _declar.node; - var _name = node.id.name; - if (canHoist) { - addExportName(_name, _name); - beforeBody.push(node); - beforeBody.push(buildExportCall(_name, node.id)); - removedPaths.push(_path2); - } else { - var _bindingIdentifiers; - - bindingIdentifiers = (_bindingIdentifiers = {}, _bindingIdentifiers[_name] = node.id, _bindingIdentifiers); - } - } else { - bindingIdentifiers = _declar.getBindingIdentifiers(); - } - for (var _name2 in bindingIdentifiers) { - addExportName(_name2, _name2); - _nodes.push(buildExportCall(_name2, t.identifier(_name2))); - } - _path2.insertAfter(_nodes); - } else { - var specifiers = _path2.node.specifiers; - if (specifiers && specifiers.length) { - if (_path2.node.source) { - pushModule(_path2.node.source.value, "exports", specifiers); - _path2.remove(); - } else { - var _nodes2 = []; - - for (var _iterator7 = specifiers, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref8; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref8 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref8 = _i7.value; - } - - var specifier = _ref8; - - _nodes2.push(buildExportCall(specifier.exported.name, specifier.local)); - addExportName(specifier.local.name, specifier.exported.name); - } - - _path2.replaceWithMultiple(_nodes2); - } - } - } - } - } - - modules.forEach(function (specifiers) { - var setterBody = []; - var target = path.scope.generateUidIdentifier(specifiers.key); - - for (var _iterator4 = specifiers.imports, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref5; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref5 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref5 = _i4.value; - } - - var specifier = _ref5; - - if (t.isImportNamespaceSpecifier(specifier)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, target))); - } else if (t.isImportDefaultSpecifier(specifier)) { - specifier = t.importSpecifier(specifier.local, t.identifier("default")); - } - - if (t.isImportSpecifier(specifier)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, t.memberExpression(target, specifier.imported)))); - } - } - - if (specifiers.exports.length) { - var exportObjRef = path.scope.generateUidIdentifier("exportObj"); - - setterBody.push(t.variableDeclaration("var", [t.variableDeclarator(exportObjRef, t.objectExpression([]))])); - - for (var _iterator5 = specifiers.exports, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref6; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref6 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref6 = _i5.value; - } - - var node = _ref6; - - if (t.isExportAllDeclaration(node)) { - setterBody.push(buildExportAll({ - KEY: path.scope.generateUidIdentifier("key"), - EXPORT_OBJ: exportObjRef, - TARGET: target - })); - } else if (t.isExportSpecifier(node)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(exportObjRef, node.exported), t.memberExpression(target, node.local)))); - } else {} - } - - setterBody.push(t.expressionStatement(t.callExpression(exportIdent, [exportObjRef]))); - } - - sources.push(t.stringLiteral(specifiers.key)); - setters.push(t.functionExpression(null, [target], t.blockStatement(setterBody))); - }); - - var moduleName = this.getModuleName(); - if (moduleName) moduleName = t.stringLiteral(moduleName); - - if (canHoist) { - (0, _babelHelperHoistVariables2.default)(path, function (id) { - return variableIds.push(id); - }); - } - - if (variableIds.length) { - beforeBody.unshift(t.variableDeclaration("var", variableIds.map(function (id) { - return t.variableDeclarator(id); - }))); - } - - path.traverse(reassignmentVisitor, { - exports: exportNames, - buildCall: buildExportCall, - scope: path.scope - }); - - for (var _iterator6 = removedPaths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref7; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref7 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref7 = _i6.value; - } - - var _path3 = _ref7; - - _path3.remove(); - } - - path.node.body = [buildTemplate({ - SYSTEM_REGISTER: t.memberExpression(t.identifier(state.opts.systemGlobal || "System"), t.identifier("register")), - BEFORE_BODY: beforeBody, - MODULE_NAME: moduleName, - SETTERS: setters, - SOURCES: sources, - BODY: path.node.body, - EXPORT_IDENTIFIER: exportIdent, - CONTEXT_IDENTIFIER: contextIdent - })]; - } - } - } - }; -}; - -var _babelHelperHoistVariables = require("babel-helper-hoist-variables"); - -var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildTemplate = (0, _babelTemplate2.default)("\n SYSTEM_REGISTER(MODULE_NAME, [SOURCES], function (EXPORT_IDENTIFIER, CONTEXT_IDENTIFIER) {\n \"use strict\";\n BEFORE_BODY;\n return {\n setters: [SETTERS],\n execute: function () {\n BODY;\n }\n };\n });\n"); - -var buildExportAll = (0, _babelTemplate2.default)("\n for (var KEY in TARGET) {\n if (KEY !== \"default\" && KEY !== \"__esModule\") EXPORT_OBJ[KEY] = TARGET[KEY];\n }\n"); - -var TYPE_IMPORT = "Import"; - -module.exports = exports["default"]; -},{"babel-helper-hoist-variables":55,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/symbol":104,"babel-template":114}],80:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (_ref) { - var t = _ref.types; - - function isValidDefine(path) { - if (!path.isExpressionStatement()) return; - - var expr = path.get("expression"); - if (!expr.isCallExpression()) return false; - if (!expr.get("callee").isIdentifier({ name: "define" })) return false; - - var args = expr.get("arguments"); - if (args.length === 3 && !args.shift().isStringLiteral()) return false; - if (args.length !== 2) return false; - if (!args.shift().isArrayExpression()) return false; - if (!args.shift().isFunctionExpression()) return false; - - return true; - } - - return { - inherits: require("babel-plugin-transform-es2015-modules-amd"), - - visitor: { - Program: { - exit: function exit(path, state) { - var last = path.get("body").pop(); - if (!isValidDefine(last)) return; - - var call = last.node.expression; - var args = call.arguments; - - var moduleName = args.length === 3 ? args.shift() : null; - var amdArgs = call.arguments[0]; - var func = call.arguments[1]; - var browserGlobals = state.opts.globals || {}; - - var commonArgs = amdArgs.elements.map(function (arg) { - if (arg.value === "module" || arg.value === "exports") { - return t.identifier(arg.value); - } else { - return t.callExpression(t.identifier("require"), [arg]); - } - }); - - var browserArgs = amdArgs.elements.map(function (arg) { - if (arg.value === "module") { - return t.identifier("mod"); - } else if (arg.value === "exports") { - return t.memberExpression(t.identifier("mod"), t.identifier("exports")); - } else { - var memberExpression = void 0; - - if (state.opts.exactGlobals) { - var globalRef = browserGlobals[arg.value]; - if (globalRef) { - memberExpression = globalRef.split(".").reduce(function (accum, curr) { - return t.memberExpression(accum, t.identifier(curr)); - }, t.identifier("global")); - } else { - memberExpression = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(arg.value))); - } - } else { - var requireName = (0, _path.basename)(arg.value, (0, _path.extname)(arg.value)); - var globalName = browserGlobals[requireName] || requireName; - memberExpression = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(globalName))); - } - - return memberExpression; - } - }); - - var moduleNameOrBasename = moduleName ? moduleName.value : this.file.opts.basename; - var globalToAssign = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(moduleNameOrBasename))); - var prerequisiteAssignments = null; - - if (state.opts.exactGlobals) { - var globalName = browserGlobals[moduleNameOrBasename]; - - if (globalName) { - prerequisiteAssignments = []; - - var members = globalName.split("."); - globalToAssign = members.slice(1).reduce(function (accum, curr) { - prerequisiteAssignments.push(buildPrerequisiteAssignment({ GLOBAL_REFERENCE: accum })); - return t.memberExpression(accum, t.identifier(curr)); - }, t.memberExpression(t.identifier("global"), t.identifier(members[0]))); - } - } - - var globalExport = buildGlobalExport({ - BROWSER_ARGUMENTS: browserArgs, - PREREQUISITE_ASSIGNMENTS: prerequisiteAssignments, - GLOBAL_TO_ASSIGN: globalToAssign - }); - - last.replaceWith(buildWrapper({ - MODULE_NAME: moduleName, - AMD_ARGUMENTS: amdArgs, - COMMON_ARGUMENTS: commonArgs, - GLOBAL_EXPORT: globalExport, - FUNC: func - })); - } - } - } - }; -}; - -var _path = require("path"); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildPrerequisiteAssignment = (0, _babelTemplate2.default)("\n GLOBAL_REFERENCE = GLOBAL_REFERENCE || {}\n"); - -var buildGlobalExport = (0, _babelTemplate2.default)("\n var mod = { exports: {} };\n factory(BROWSER_ARGUMENTS);\n PREREQUISITE_ASSIGNMENTS\n GLOBAL_TO_ASSIGN = mod.exports;\n"); - -var buildWrapper = (0, _babelTemplate2.default)("\n (function (global, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(MODULE_NAME, AMD_ARGUMENTS, factory);\n } else if (typeof exports !== \"undefined\") {\n factory(COMMON_ARGUMENTS);\n } else {\n GLOBAL_EXPORT\n }\n })(this, FUNC);\n"); - -module.exports = exports["default"]; -},{"babel-plugin-transform-es2015-modules-amd":77,"babel-template":114,"path":522}],81:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (_ref) { - var t = _ref.types; - - function Property(path, node, scope, getObjectRef, file) { - var replaceSupers = new _babelHelperReplaceSupers2.default({ - getObjectRef: getObjectRef, - methodNode: node, - methodPath: path, - isStatic: true, - scope: scope, - file: file - }); - - replaceSupers.replace(); - } - - var CONTAINS_SUPER = (0, _symbol2.default)(); - - return { - visitor: { - Super: function Super(path) { - var parentObj = path.findParent(function (path) { - return path.isObjectExpression(); - }); - if (parentObj) parentObj.node[CONTAINS_SUPER] = true; - }, - - - ObjectExpression: { - exit: function exit(path, file) { - if (!path.node[CONTAINS_SUPER]) return; - - var objectRef = void 0; - var getObjectRef = function getObjectRef() { - return objectRef = objectRef || path.scope.generateUidIdentifier("obj"); - }; - - var propPaths = path.get("properties"); - for (var _iterator = propPaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var propPath = _ref2; - - if (propPath.isObjectProperty()) propPath = propPath.get("value"); - Property(propPath, propPath.node, path.scope, getObjectRef, file); - } - - if (objectRef) { - path.scope.push({ id: objectRef }); - path.replaceWith(t.assignmentExpression("=", objectRef, path.node)); - } - } - } - } - }; -}; - -var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); - -var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-helper-replace-supers":58,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/symbol":104}],82:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.visitor = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); - -var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); - -var _babelHelperCallDelegate = require("babel-helper-call-delegate"); - -var _babelHelperCallDelegate2 = _interopRequireDefault(_babelHelperCallDelegate); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildDefaultParam = (0, _babelTemplate2.default)("\n let VARIABLE_NAME =\n ARGUMENTS.length > ARGUMENT_KEY && ARGUMENTS[ARGUMENT_KEY] !== undefined ?\n ARGUMENTS[ARGUMENT_KEY]\n :\n DEFAULT_VALUE;\n"); - -var buildCutOff = (0, _babelTemplate2.default)("\n let $0 = $1[$2];\n"); - -function hasDefaults(node) { - for (var _iterator = node.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var param = _ref; - - if (!t.isIdentifier(param)) return true; - } - return false; -} - -function isSafeBinding(scope, node) { - if (!scope.hasOwnBinding(node.name)) return true; - - var _scope$getOwnBinding = scope.getOwnBinding(node.name), - kind = _scope$getOwnBinding.kind; - - return kind === "param" || kind === "local"; -} - -var iifeVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var scope = path.scope, - node = path.node; - - if (node.name === "eval" || !isSafeBinding(scope, node)) { - state.iife = true; - path.stop(); - } - }, - Scope: function Scope(path) { - path.skip(); - } -}; - -var visitor = exports.visitor = { - Function: function Function(path) { - var node = path.node, - scope = path.scope; - - if (!hasDefaults(node)) return; - - path.ensureBlock(); - - var state = { - iife: false, - scope: scope - }; - - var body = []; - - var argsIdentifier = t.identifier("arguments"); - argsIdentifier._shadowedFunctionLiteral = path; - - function pushDefNode(left, right, i) { - var defNode = buildDefaultParam({ - VARIABLE_NAME: left, - DEFAULT_VALUE: right, - ARGUMENT_KEY: t.numericLiteral(i), - ARGUMENTS: argsIdentifier - }); - defNode._blockHoist = node.params.length - i; - body.push(defNode); - } - - var lastNonDefaultParam = (0, _babelHelperGetFunctionArity2.default)(node); - - var params = path.get("params"); - for (var i = 0; i < params.length; i++) { - var param = params[i]; - - if (!param.isAssignmentPattern()) { - if (!state.iife && !param.isIdentifier()) { - param.traverse(iifeVisitor, state); - } - - continue; - } - - var left = param.get("left"); - var right = param.get("right"); - - if (i >= lastNonDefaultParam || left.isPattern()) { - var placeholder = scope.generateUidIdentifier("x"); - placeholder._isDefaultPlaceholder = true; - node.params[i] = placeholder; - } else { - node.params[i] = left.node; - } - - if (!state.iife) { - if (right.isIdentifier() && !isSafeBinding(scope, right.node)) { - state.iife = true; - } else { - right.traverse(iifeVisitor, state); - } - } - - pushDefNode(left.node, right.node, i); - } - - for (var _i2 = lastNonDefaultParam + 1; _i2 < node.params.length; _i2++) { - var _param = node.params[_i2]; - if (_param._isDefaultPlaceholder) continue; - - var declar = buildCutOff(_param, argsIdentifier, t.numericLiteral(_i2)); - declar._blockHoist = node.params.length - _i2; - body.push(declar); - } - - node.params = node.params.slice(0, lastNonDefaultParam); - - if (state.iife) { - body.push((0, _babelHelperCallDelegate2.default)(path, scope)); - path.set("body", t.blockStatement(body)); - } else { - path.get("body").unshiftContainer("body", body); - } - } -}; -},{"babel-helper-call-delegate":51,"babel-helper-get-function-arity":54,"babel-runtime/core-js/get-iterator":95,"babel-template":114,"babel-types":151}],83:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.visitor = undefined; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var visitor = exports.visitor = { - Function: function Function(path) { - var params = path.get("params"); - - var hoistTweak = t.isRestElement(params[params.length - 1]) ? 1 : 0; - var outputParamsLength = params.length - hoistTweak; - - for (var i = 0; i < outputParamsLength; i++) { - var param = params[i]; - if (param.isArrayPattern() || param.isObjectPattern()) { - var uid = path.scope.generateUidIdentifier("ref"); - - var declar = t.variableDeclaration("let", [t.variableDeclarator(param.node, uid)]); - declar._blockHoist = outputParamsLength - i; - - path.ensureBlock(); - path.get("body").unshiftContainer("body", declar); - - param.replaceWith(uid); - } - } - } -}; -},{"babel-types":151}],84:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function () { - return { - visitor: _babelTraverse.visitors.merge([{ - ArrowFunctionExpression: function ArrowFunctionExpression(path) { - var params = path.get("params"); - for (var _iterator = params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var param = _ref; - - if (param.isRestElement() || param.isAssignmentPattern()) { - path.arrowFunctionToShadowed(); - break; - } - } - } - }, destructuring.visitor, rest.visitor, def.visitor]) - }; -}; - -var _babelTraverse = require("babel-traverse"); - -var _destructuring = require("./destructuring"); - -var destructuring = _interopRequireWildcard(_destructuring); - -var _default = require("./default"); - -var def = _interopRequireWildcard(_default); - -var _rest = require("./rest"); - -var rest = _interopRequireWildcard(_rest); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"./default":82,"./destructuring":83,"./rest":85,"babel-runtime/core-js/get-iterator":95,"babel-traverse":118}],85:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.visitor = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildRest = (0, _babelTemplate2.default)("\n for (var LEN = ARGUMENTS.length,\n ARRAY = Array(ARRAY_LEN),\n KEY = START;\n KEY < LEN;\n KEY++) {\n ARRAY[ARRAY_KEY] = ARGUMENTS[KEY];\n }\n"); - -var restIndex = (0, _babelTemplate2.default)("\n ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX]\n"); - -var restIndexImpure = (0, _babelTemplate2.default)("\n REF = INDEX, ARGUMENTS.length <= REF ? undefined : ARGUMENTS[REF]\n"); - -var restLength = (0, _babelTemplate2.default)("\n ARGUMENTS.length <= OFFSET ? 0 : ARGUMENTS.length - OFFSET\n"); - -var memberExpressionOptimisationVisitor = { - Scope: function Scope(path, state) { - if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { - path.skip(); - } - }, - Flow: function Flow(path) { - if (path.isTypeCastExpression()) return; - - path.skip(); - }, - - - "Function|ClassProperty": function FunctionClassProperty(path, state) { - var oldNoOptimise = state.noOptimise; - state.noOptimise = true; - path.traverse(memberExpressionOptimisationVisitor, state); - state.noOptimise = oldNoOptimise; - - path.skip(); - }, - - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var node = path.node; - - if (node.name === "arguments") { - state.deopted = true; - } - - if (node.name !== state.name) return; - - if (state.noOptimise) { - state.deopted = true; - } else { - var parentPath = path.parentPath; - - if (parentPath.listKey === "params" && parentPath.key < state.offset) { - return; - } - - if (parentPath.isMemberExpression({ object: node })) { - var grandparentPath = parentPath.parentPath; - - var argsOptEligible = !state.deopted && !(grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left || grandparentPath.isLVal() || grandparentPath.isForXStatement() || grandparentPath.isUpdateExpression() || grandparentPath.isUnaryExpression({ operator: "delete" }) || (grandparentPath.isCallExpression() || grandparentPath.isNewExpression()) && parentPath.node === grandparentPath.node.callee); - - if (argsOptEligible) { - if (parentPath.node.computed) { - if (parentPath.get("property").isBaseType("number")) { - state.candidates.push({ cause: "indexGetter", path: path }); - return; - } - } else if (parentPath.node.property.name === "length") { - state.candidates.push({ cause: "lengthGetter", path: path }); - return; - } - } - } - - if (state.offset === 0 && parentPath.isSpreadElement()) { - var call = parentPath.parentPath; - if (call.isCallExpression() && call.node.arguments.length === 1) { - state.candidates.push({ cause: "argSpread", path: path }); - return; - } - } - - state.references.push(path); - } - }, - BindingIdentifier: function BindingIdentifier(_ref, state) { - var node = _ref.node; - - if (node.name === state.name) { - state.deopted = true; - } - } -}; -function hasRest(node) { - return t.isRestElement(node.params[node.params.length - 1]); -} - -function optimiseIndexGetter(path, argsId, offset) { - var index = void 0; - - if (t.isNumericLiteral(path.parent.property)) { - index = t.numericLiteral(path.parent.property.value + offset); - } else if (offset === 0) { - index = path.parent.property; - } else { - index = t.binaryExpression("+", path.parent.property, t.numericLiteral(offset)); - } - - var scope = path.scope; - - if (!scope.isPure(index)) { - var temp = scope.generateUidIdentifierBasedOnNode(index); - scope.push({ id: temp, kind: "var" }); - path.parentPath.replaceWith(restIndexImpure({ - ARGUMENTS: argsId, - INDEX: index, - REF: temp - })); - } else { - path.parentPath.replaceWith(restIndex({ - ARGUMENTS: argsId, - INDEX: index - })); - } -} - -function optimiseLengthGetter(path, argsId, offset) { - if (offset) { - path.parentPath.replaceWith(restLength({ - ARGUMENTS: argsId, - OFFSET: t.numericLiteral(offset) - })); - } else { - path.replaceWith(argsId); - } -} - -var visitor = exports.visitor = { - Function: function Function(path) { - var node = path.node, - scope = path.scope; - - if (!hasRest(node)) return; - - var rest = node.params.pop().argument; - - var argsId = t.identifier("arguments"); - - argsId._shadowedFunctionLiteral = path; - - var state = { - references: [], - offset: node.params.length, - - argumentsNode: argsId, - outerBinding: scope.getBindingIdentifier(rest.name), - - candidates: [], - - name: rest.name, - - deopted: false - }; - - path.traverse(memberExpressionOptimisationVisitor, state); - - if (!state.deopted && !state.references.length) { - for (var _iterator = state.candidates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref3; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref3 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref3 = _i.value; - } - - var _ref4 = _ref3; - var _path = _ref4.path, - cause = _ref4.cause; - - switch (cause) { - case "indexGetter": - optimiseIndexGetter(_path, argsId, state.offset); - break; - case "lengthGetter": - optimiseLengthGetter(_path, argsId, state.offset); - break; - default: - _path.replaceWith(argsId); - } - } - return; - } - - state.references = state.references.concat(state.candidates.map(function (_ref5) { - var path = _ref5.path; - return path; - })); - - state.deopted = state.deopted || !!node.shadow; - - var start = t.numericLiteral(node.params.length); - var key = scope.generateUidIdentifier("key"); - var len = scope.generateUidIdentifier("len"); - - var arrKey = key; - var arrLen = len; - if (node.params.length) { - arrKey = t.binaryExpression("-", key, start); - - arrLen = t.conditionalExpression(t.binaryExpression(">", len, start), t.binaryExpression("-", len, start), t.numericLiteral(0)); - } - - var loop = buildRest({ - ARGUMENTS: argsId, - ARRAY_KEY: arrKey, - ARRAY_LEN: arrLen, - START: start, - ARRAY: rest, - KEY: key, - LEN: len - }); - - if (state.deopted) { - loop._blockHoist = node.params.length + 1; - node.body.body.unshift(loop); - } else { - loop._blockHoist = 1; - - var target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent(); - - target.findParent(function (path) { - if (path.isLoop()) { - target = path; - } else { - return path.isFunction(); - } - }); - - target.insertBefore(loop); - } - } -}; -},{"babel-runtime/core-js/get-iterator":95,"babel-template":114,"babel-types":151}],86:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - visitor: { - ObjectMethod: function ObjectMethod(path) { - var node = path.node; - - if (node.kind === "method") { - var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); - func.returnType = node.returnType; - - path.replaceWith(t.objectProperty(node.key, func, node.computed)); - } - }, - ObjectProperty: function ObjectProperty(_ref) { - var node = _ref.node; - - if (node.shorthand) { - node.shorthand = false; - } - } - } - }; -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":151}],87:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (_ref) { - var t = _ref.types; - - function getSpreadLiteral(spread, scope, state) { - if (state.opts.loose && !t.isIdentifier(spread.argument, { name: "arguments" })) { - return spread.argument; - } else { - return scope.toArray(spread.argument, true); - } - } - - function hasSpread(nodes) { - for (var i = 0; i < nodes.length; i++) { - if (t.isSpreadElement(nodes[i])) { - return true; - } - } - return false; - } - - function build(props, scope, state) { - var nodes = []; - - var _props = []; - - function push() { - if (!_props.length) return; - nodes.push(t.arrayExpression(_props)); - _props = []; - } - - for (var _iterator = props, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var prop = _ref2; - - if (t.isSpreadElement(prop)) { - push(); - nodes.push(getSpreadLiteral(prop, scope, state)); - } else { - _props.push(prop); - } - } - - push(); - - return nodes; - } - - return { - visitor: { - ArrayExpression: function ArrayExpression(path, state) { - var node = path.node, - scope = path.scope; - - var elements = node.elements; - if (!hasSpread(elements)) return; - - var nodes = build(elements, scope, state); - var first = nodes.shift(); - - if (!t.isArrayExpression(first)) { - nodes.unshift(first); - first = t.arrayExpression([]); - } - - path.replaceWith(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); - }, - CallExpression: function CallExpression(path, state) { - var node = path.node, - scope = path.scope; - - - var args = node.arguments; - if (!hasSpread(args)) return; - - var calleePath = path.get("callee"); - if (calleePath.isSuper()) return; - - var contextLiteral = t.identifier("undefined"); - - node.arguments = []; - - var nodes = void 0; - if (args.length === 1 && args[0].argument.name === "arguments") { - nodes = [args[0].argument]; - } else { - nodes = build(args, scope, state); - } - - var first = nodes.shift(); - if (nodes.length) { - node.arguments.push(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); - } else { - node.arguments.push(first); - } - - var callee = node.callee; - - if (calleePath.isMemberExpression()) { - var temp = scope.maybeGenerateMemoised(callee.object); - if (temp) { - callee.object = t.assignmentExpression("=", temp, callee.object); - contextLiteral = temp; - } else { - contextLiteral = callee.object; - } - t.appendToMemberExpression(callee, t.identifier("apply")); - } else { - node.callee = t.memberExpression(node.callee, t.identifier("apply")); - } - - if (t.isSuper(contextLiteral)) { - contextLiteral = t.thisExpression(); - } - - node.arguments.unshift(contextLiteral); - }, - NewExpression: function NewExpression(path, state) { - var node = path.node, - scope = path.scope; - - var args = node.arguments; - if (!hasSpread(args)) return; - - var nodes = build(args, scope, state); - - var context = t.arrayExpression([t.nullLiteral()]); - - args = t.callExpression(t.memberExpression(context, t.identifier("concat")), nodes); - - path.replaceWith(t.newExpression(t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Function"), t.identifier("prototype")), t.identifier("bind")), t.identifier("apply")), [node.callee, args]), [])); - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],88:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - visitor: { - RegExpLiteral: function RegExpLiteral(path) { - var node = path.node; - - if (!regex.is(node, "y")) return; - - path.replaceWith(t.newExpression(t.identifier("RegExp"), [t.stringLiteral(node.pattern), t.stringLiteral(node.flags)])); - } - } - }; -}; - -var _babelHelperRegex = require("babel-helper-regex"); - -var regex = _interopRequireWildcard(_babelHelperRegex); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-helper-regex":57,"babel-types":151}],89:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (_ref) { - var t = _ref.types; - - function isString(node) { - return t.isLiteral(node) && typeof node.value === "string"; - } - - function buildBinaryExpression(left, right) { - return t.binaryExpression("+", left, right); - } - - return { - visitor: { - TaggedTemplateExpression: function TaggedTemplateExpression(path, state) { - var node = path.node; - - var quasi = node.quasi; - var args = []; - - var strings = []; - var raw = []; - - for (var _iterator = quasi.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var elem = _ref2; - - strings.push(t.stringLiteral(elem.value.cooked)); - raw.push(t.stringLiteral(elem.value.raw)); - } - - strings = t.arrayExpression(strings); - raw = t.arrayExpression(raw); - - var templateName = "taggedTemplateLiteral"; - if (state.opts.loose) templateName += "Loose"; - - var templateObject = state.file.addTemplateObject(templateName, strings, raw); - args.push(templateObject); - - args = args.concat(quasi.expressions); - - path.replaceWith(t.callExpression(node.tag, args)); - }, - TemplateLiteral: function TemplateLiteral(path, state) { - var nodes = []; - - var expressions = path.get("expressions"); - - for (var _iterator2 = path.node.quasis, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - var elem = _ref3; - - nodes.push(t.stringLiteral(elem.value.cooked)); - - var expr = expressions.shift(); - if (expr) { - if (state.opts.spec && !expr.isBaseType("string") && !expr.isBaseType("number")) { - nodes.push(t.callExpression(t.identifier("String"), [expr.node])); - } else { - nodes.push(expr.node); - } - } - } - - nodes = nodes.filter(function (n) { - return !t.isLiteral(n, { value: "" }); - }); - - if (!isString(nodes[0]) && !isString(nodes[1])) { - nodes.unshift(t.stringLiteral("")); - } - - if (nodes.length > 1) { - var root = buildBinaryExpression(nodes.shift(), nodes.shift()); - - for (var _iterator3 = nodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } - - var node = _ref4; - - root = buildBinaryExpression(root, node); - } - - path.replaceWith(root); - } else { - path.replaceWith(nodes[0]); - } - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],90:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (_ref) { - var t = _ref.types; - - var IGNORE = (0, _symbol2.default)(); - - return { - visitor: { - Scope: function Scope(_ref2) { - var scope = _ref2.scope; - - if (!scope.getBinding("Symbol")) { - return; - } - - scope.rename("Symbol"); - }, - UnaryExpression: function UnaryExpression(path) { - var node = path.node, - parent = path.parent; - - if (node[IGNORE]) return; - if (path.find(function (path) { - return path.node && !!path.node._generated; - })) return; - - if (path.parentPath.isBinaryExpression() && t.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) { - var opposite = path.getOpposite(); - if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") { - return; - } - } - - if (node.operator === "typeof") { - var call = t.callExpression(this.addHelper("typeof"), [node.argument]); - if (path.get("argument").isIdentifier()) { - var undefLiteral = t.stringLiteral("undefined"); - var unary = t.unaryExpression("typeof", node.argument); - unary[IGNORE] = true; - path.replaceWith(t.conditionalExpression(t.binaryExpression("===", unary, undefLiteral), undefLiteral, call)); - } else { - path.replaceWith(call); - } - } - } - } - }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/symbol":104}],91:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - visitor: { - RegExpLiteral: function RegExpLiteral(_ref) { - var node = _ref.node; - - if (!regex.is(node, "u")) return; - node.pattern = (0, _regexpuCore2.default)(node.pattern, node.flags); - regex.pullFlag(node, "u"); - } - } - }; -}; - -var _regexpuCore = require("regexpu-core"); - -var _regexpuCore2 = _interopRequireDefault(_regexpuCore); - -var _babelHelperRegex = require("babel-helper-regex"); - -var regex = _interopRequireWildcard(_babelHelperRegex); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-helper-regex":57,"regexpu-core":537}],92:[function(require,module,exports){ -"use strict"; - -module.exports = require("regenerator-transform"); -},{"regenerator-transform":529}],93:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function () { - return { - visitor: { - Program: function Program(path, state) { - if (state.opts.strict === false || state.opts.strictMode === false) return; - - var node = path.node; - - - for (var _iterator = node.directives, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var directive = _ref; - - if (directive.value.value === "use strict") return; - } - - path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict"))); - } - } - }; -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],94:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _babelPluginTransformEs2015TemplateLiterals = require("babel-plugin-transform-es2015-template-literals"); - -var _babelPluginTransformEs2015TemplateLiterals2 = _interopRequireDefault(_babelPluginTransformEs2015TemplateLiterals); - -var _babelPluginTransformEs2015Literals = require("babel-plugin-transform-es2015-literals"); - -var _babelPluginTransformEs2015Literals2 = _interopRequireDefault(_babelPluginTransformEs2015Literals); - -var _babelPluginTransformEs2015FunctionName = require("babel-plugin-transform-es2015-function-name"); - -var _babelPluginTransformEs2015FunctionName2 = _interopRequireDefault(_babelPluginTransformEs2015FunctionName); - -var _babelPluginTransformEs2015ArrowFunctions = require("babel-plugin-transform-es2015-arrow-functions"); - -var _babelPluginTransformEs2015ArrowFunctions2 = _interopRequireDefault(_babelPluginTransformEs2015ArrowFunctions); - -var _babelPluginTransformEs2015BlockScopedFunctions = require("babel-plugin-transform-es2015-block-scoped-functions"); - -var _babelPluginTransformEs2015BlockScopedFunctions2 = _interopRequireDefault(_babelPluginTransformEs2015BlockScopedFunctions); - -var _babelPluginTransformEs2015Classes = require("babel-plugin-transform-es2015-classes"); - -var _babelPluginTransformEs2015Classes2 = _interopRequireDefault(_babelPluginTransformEs2015Classes); - -var _babelPluginTransformEs2015ObjectSuper = require("babel-plugin-transform-es2015-object-super"); - -var _babelPluginTransformEs2015ObjectSuper2 = _interopRequireDefault(_babelPluginTransformEs2015ObjectSuper); - -var _babelPluginTransformEs2015ShorthandProperties = require("babel-plugin-transform-es2015-shorthand-properties"); - -var _babelPluginTransformEs2015ShorthandProperties2 = _interopRequireDefault(_babelPluginTransformEs2015ShorthandProperties); - -var _babelPluginTransformEs2015DuplicateKeys = require("babel-plugin-transform-es2015-duplicate-keys"); - -var _babelPluginTransformEs2015DuplicateKeys2 = _interopRequireDefault(_babelPluginTransformEs2015DuplicateKeys); - -var _babelPluginTransformEs2015ComputedProperties = require("babel-plugin-transform-es2015-computed-properties"); - -var _babelPluginTransformEs2015ComputedProperties2 = _interopRequireDefault(_babelPluginTransformEs2015ComputedProperties); - -var _babelPluginTransformEs2015ForOf = require("babel-plugin-transform-es2015-for-of"); - -var _babelPluginTransformEs2015ForOf2 = _interopRequireDefault(_babelPluginTransformEs2015ForOf); - -var _babelPluginTransformEs2015StickyRegex = require("babel-plugin-transform-es2015-sticky-regex"); - -var _babelPluginTransformEs2015StickyRegex2 = _interopRequireDefault(_babelPluginTransformEs2015StickyRegex); - -var _babelPluginTransformEs2015UnicodeRegex = require("babel-plugin-transform-es2015-unicode-regex"); - -var _babelPluginTransformEs2015UnicodeRegex2 = _interopRequireDefault(_babelPluginTransformEs2015UnicodeRegex); - -var _babelPluginCheckEs2015Constants = require("babel-plugin-check-es2015-constants"); - -var _babelPluginCheckEs2015Constants2 = _interopRequireDefault(_babelPluginCheckEs2015Constants); - -var _babelPluginTransformEs2015Spread = require("babel-plugin-transform-es2015-spread"); - -var _babelPluginTransformEs2015Spread2 = _interopRequireDefault(_babelPluginTransformEs2015Spread); - -var _babelPluginTransformEs2015Parameters = require("babel-plugin-transform-es2015-parameters"); - -var _babelPluginTransformEs2015Parameters2 = _interopRequireDefault(_babelPluginTransformEs2015Parameters); - -var _babelPluginTransformEs2015Destructuring = require("babel-plugin-transform-es2015-destructuring"); - -var _babelPluginTransformEs2015Destructuring2 = _interopRequireDefault(_babelPluginTransformEs2015Destructuring); - -var _babelPluginTransformEs2015BlockScoping = require("babel-plugin-transform-es2015-block-scoping"); - -var _babelPluginTransformEs2015BlockScoping2 = _interopRequireDefault(_babelPluginTransformEs2015BlockScoping); - -var _babelPluginTransformEs2015TypeofSymbol = require("babel-plugin-transform-es2015-typeof-symbol"); - -var _babelPluginTransformEs2015TypeofSymbol2 = _interopRequireDefault(_babelPluginTransformEs2015TypeofSymbol); - -var _babelPluginTransformEs2015ModulesCommonjs = require("babel-plugin-transform-es2015-modules-commonjs"); - -var _babelPluginTransformEs2015ModulesCommonjs2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesCommonjs); - -var _babelPluginTransformEs2015ModulesSystemjs = require("babel-plugin-transform-es2015-modules-systemjs"); - -var _babelPluginTransformEs2015ModulesSystemjs2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesSystemjs); - -var _babelPluginTransformEs2015ModulesAmd = require("babel-plugin-transform-es2015-modules-amd"); - -var _babelPluginTransformEs2015ModulesAmd2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesAmd); - -var _babelPluginTransformEs2015ModulesUmd = require("babel-plugin-transform-es2015-modules-umd"); - -var _babelPluginTransformEs2015ModulesUmd2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesUmd); - -var _babelPluginTransformRegenerator = require("babel-plugin-transform-regenerator"); - -var _babelPluginTransformRegenerator2 = _interopRequireDefault(_babelPluginTransformRegenerator); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function preset(context) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var moduleTypes = ["commonjs", "amd", "umd", "systemjs"]; - var loose = false; - var modules = "commonjs"; - var spec = false; - - if (opts !== undefined) { - if (opts.loose !== undefined) loose = opts.loose; - if (opts.modules !== undefined) modules = opts.modules; - if (opts.spec !== undefined) spec = opts.spec; - } - - if (typeof loose !== "boolean") throw new Error("Preset es2015 'loose' option must be a boolean."); - if (typeof spec !== "boolean") throw new Error("Preset es2015 'spec' option must be a boolean."); - if (modules !== false && moduleTypes.indexOf(modules) === -1) { - throw new Error("Preset es2015 'modules' option must be 'false' to indicate no modules\n" + "or a module type which be be one of: 'commonjs' (default), 'amd', 'umd', 'systemjs'"); - } - - var optsLoose = { loose: loose }; - - return { - plugins: [[_babelPluginTransformEs2015TemplateLiterals2.default, { loose: loose, spec: spec }], _babelPluginTransformEs2015Literals2.default, _babelPluginTransformEs2015FunctionName2.default, [_babelPluginTransformEs2015ArrowFunctions2.default, { spec: spec }], _babelPluginTransformEs2015BlockScopedFunctions2.default, [_babelPluginTransformEs2015Classes2.default, optsLoose], _babelPluginTransformEs2015ObjectSuper2.default, _babelPluginTransformEs2015ShorthandProperties2.default, _babelPluginTransformEs2015DuplicateKeys2.default, [_babelPluginTransformEs2015ComputedProperties2.default, optsLoose], [_babelPluginTransformEs2015ForOf2.default, optsLoose], _babelPluginTransformEs2015StickyRegex2.default, _babelPluginTransformEs2015UnicodeRegex2.default, _babelPluginCheckEs2015Constants2.default, [_babelPluginTransformEs2015Spread2.default, optsLoose], _babelPluginTransformEs2015Parameters2.default, [_babelPluginTransformEs2015Destructuring2.default, optsLoose], _babelPluginTransformEs2015BlockScoping2.default, _babelPluginTransformEs2015TypeofSymbol2.default, modules === "commonjs" && [_babelPluginTransformEs2015ModulesCommonjs2.default, optsLoose], modules === "systemjs" && [_babelPluginTransformEs2015ModulesSystemjs2.default, optsLoose], modules === "amd" && [_babelPluginTransformEs2015ModulesAmd2.default, optsLoose], modules === "umd" && [_babelPluginTransformEs2015ModulesUmd2.default, optsLoose], [_babelPluginTransformRegenerator2.default, { async: false, asyncGenerators: false }]].filter(Boolean) }; -} - -var oldConfig = preset({}); - -exports.default = oldConfig; - -Object.defineProperty(oldConfig, "buildPreset", { - configurable: true, - writable: true, - - enumerable: false, - value: preset -}); -module.exports = exports["default"]; -},{"babel-plugin-check-es2015-constants":62,"babel-plugin-transform-es2015-arrow-functions":64,"babel-plugin-transform-es2015-block-scoped-functions":65,"babel-plugin-transform-es2015-block-scoping":66,"babel-plugin-transform-es2015-classes":68,"babel-plugin-transform-es2015-computed-properties":71,"babel-plugin-transform-es2015-destructuring":72,"babel-plugin-transform-es2015-duplicate-keys":73,"babel-plugin-transform-es2015-for-of":74,"babel-plugin-transform-es2015-function-name":75,"babel-plugin-transform-es2015-literals":76,"babel-plugin-transform-es2015-modules-amd":77,"babel-plugin-transform-es2015-modules-commonjs":78,"babel-plugin-transform-es2015-modules-systemjs":79,"babel-plugin-transform-es2015-modules-umd":80,"babel-plugin-transform-es2015-object-super":81,"babel-plugin-transform-es2015-parameters":84,"babel-plugin-transform-es2015-shorthand-properties":86,"babel-plugin-transform-es2015-spread":87,"babel-plugin-transform-es2015-sticky-regex":88,"babel-plugin-transform-es2015-template-literals":89,"babel-plugin-transform-es2015-typeof-symbol":90,"babel-plugin-transform-es2015-unicode-regex":91,"babel-plugin-transform-regenerator":92}],95:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; -},{"core-js/library/fn/get-iterator":164}],96:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true }; -},{"core-js/library/fn/json/stringify":165}],97:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/map"), __esModule: true }; -},{"core-js/library/fn/map":166}],98:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/number/max-safe-integer"), __esModule: true }; -},{"core-js/library/fn/number/max-safe-integer":167}],99:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; -},{"core-js/library/fn/object/assign":168}],100:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; -},{"core-js/library/fn/object/create":169}],101:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/get-own-property-symbols"), __esModule: true }; -},{"core-js/library/fn/object/get-own-property-symbols":170}],102:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; -},{"core-js/library/fn/object/keys":171}],103:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; -},{"core-js/library/fn/object/set-prototype-of":172}],104:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; -},{"core-js/library/fn/symbol":174}],105:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/for"), __esModule: true }; -},{"core-js/library/fn/symbol/for":173}],106:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; -},{"core-js/library/fn/symbol/iterator":175}],107:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-map"), __esModule: true }; -},{"core-js/library/fn/weak-map":176}],108:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-set"), __esModule: true }; -},{"core-js/library/fn/weak-set":177}],109:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; -},{}],110:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _setPrototypeOf = require("../core-js/object/set-prototype-of"); - -var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); - -var _create = require("../core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _typeof2 = require("../helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); - } - - subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; -}; -},{"../core-js/object/create":100,"../core-js/object/set-prototype-of":103,"../helpers/typeof":113}],111:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (obj, keys) { - var target = {}; - - for (var i in obj) { - if (keys.indexOf(i) >= 0) continue; - if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; - target[i] = obj[i]; - } - - return target; -}; -},{}],112:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("../helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; -}; -},{"../helpers/typeof":113}],113:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _iterator = require("../core-js/symbol/iterator"); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _symbol = require("../core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { - return typeof obj === "undefined" ? "undefined" : _typeof(obj); -} : function (obj) { - return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); -}; -},{"../core-js/symbol":104,"../core-js/symbol/iterator":106}],114:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (code, opts) { - var stack = void 0; - try { - throw new Error(); - } catch (error) { - if (error.stack) { - stack = error.stack.split("\n").slice(1).join("\n"); - } - } - - opts = (0, _assign2.default)({ - allowReturnOutsideFunction: true, - allowSuperOutsideMethod: true, - preserveComments: false - }, opts); - - var _getAst = function getAst() { - var ast = void 0; - - try { - ast = babylon.parse(code, opts); - - ast = _babelTraverse2.default.removeProperties(ast, { preserveComments: opts.preserveComments }); - - _babelTraverse2.default.cheap(ast, function (node) { - node[FROM_TEMPLATE] = true; - }); - } catch (err) { - err.stack = err.stack + "from\n" + stack; - throw err; - } - - _getAst = function getAst() { - return ast; - }; - - return ast; - }; - - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return useTemplate(_getAst(), args); - }; -}; - -var _cloneDeep = require("lodash/cloneDeep"); - -var _cloneDeep2 = _interopRequireDefault(_cloneDeep); - -var _assign = require("lodash/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _has = require("lodash/has"); - -var _has2 = _interopRequireDefault(_has); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _babylon = require("babylon"); - -var babylon = _interopRequireWildcard(_babylon); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var FROM_TEMPLATE = "_fromTemplate"; -var TEMPLATE_SKIP = (0, _symbol2.default)(); - -function useTemplate(ast, nodes) { - ast = (0, _cloneDeep2.default)(ast); - var _ast = ast, - program = _ast.program; - - - if (nodes.length) { - (0, _babelTraverse2.default)(ast, templateVisitor, null, nodes); - } - - if (program.body.length > 1) { - return program.body; - } else { - return program.body[0]; - } -} - -var templateVisitor = { - noScope: true, - - enter: function enter(path, args) { - var node = path.node; - - if (node[TEMPLATE_SKIP]) return path.skip(); - - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - var replacement = void 0; - - if (t.isIdentifier(node) && node[FROM_TEMPLATE]) { - if ((0, _has2.default)(args[0], node.name)) { - replacement = args[0][node.name]; - } else if (node.name[0] === "$") { - var i = +node.name.slice(1); - if (args[i]) replacement = args[i]; - } - } - - if (replacement === null) { - path.remove(); - } - - if (replacement) { - replacement[TEMPLATE_SKIP] = true; - path.replaceInline(replacement); - } - }, - exit: function exit(_ref) { - var node = _ref.node; - - if (!node.loc) _babelTraverse2.default.clearNode(node); - } -}; -module.exports = exports["default"]; -},{"babel-runtime/core-js/symbol":104,"babel-traverse":118,"babel-types":151,"babylon":155,"lodash/assign":463,"lodash/cloneDeep":467,"lodash/has":479}],115:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.scope = exports.path = undefined; - -var _weakMap = require("babel-runtime/core-js/weak-map"); - -var _weakMap2 = _interopRequireDefault(_weakMap); - -exports.clear = clear; -exports.clearPath = clearPath; -exports.clearScope = clearScope; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var path = exports.path = new _weakMap2.default(); -var scope = exports.scope = new _weakMap2.default(); - -function clear() { - clearPath(); - clearScope(); -} - -function clearPath() { - exports.path = path = new _weakMap2.default(); -} - -function clearScope() { - exports.scope = scope = new _weakMap2.default(); -} -},{"babel-runtime/core-js/weak-map":107}],116:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _path2 = require("./path"); - -var _path3 = _interopRequireDefault(_path2); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var testing = process.env.NODE_ENV === "test"; - -var TraversalContext = function () { - function TraversalContext(scope, opts, state, parentPath) { - (0, _classCallCheck3.default)(this, TraversalContext); - this.queue = null; - - this.parentPath = parentPath; - this.scope = scope; - this.state = state; - this.opts = opts; - } - - TraversalContext.prototype.shouldVisit = function shouldVisit(node) { - var opts = this.opts; - if (opts.enter || opts.exit) return true; - - if (opts[node.type]) return true; - - var keys = t.VISITOR_KEYS[node.type]; - if (!keys || !keys.length) return false; - - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var key = _ref; - - if (node[key]) return true; - } - - return false; - }; - - TraversalContext.prototype.create = function create(node, obj, key, listKey) { - return _path3.default.get({ - parentPath: this.parentPath, - parent: node, - container: obj, - key: key, - listKey: listKey - }); - }; - - TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) { - if (this.trap) { - throw new Error("Infinite cycle detected"); - } - - if (this.queue) { - if (notPriority) { - this.queue.push(path); - } else { - this.priorityQueue.push(path); - } - } - }; - - TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { - if (container.length === 0) return false; - - var queue = []; - - for (var key = 0; key < container.length; key++) { - var node = container[key]; - if (node && this.shouldVisit(node)) { - queue.push(this.create(parent, container, key, listKey)); - } - } - - return this.visitQueue(queue); - }; - - TraversalContext.prototype.visitSingle = function visitSingle(node, key) { - if (this.shouldVisit(node[key])) { - return this.visitQueue([this.create(node, node, key)]); - } else { - return false; - } - }; - - TraversalContext.prototype.visitQueue = function visitQueue(queue) { - this.queue = queue; - this.priorityQueue = []; - - var visited = []; - var stop = false; - - for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var path = _ref2; - - path.resync(); - - if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { - path.pushContext(this); - } - - if (path.key === null) continue; - - if (testing && queue.length >= 10000) { - this.trap = true; - } - - if (visited.indexOf(path.node) >= 0) continue; - visited.push(path.node); - - if (path.visit()) { - stop = true; - break; - } - - if (this.priorityQueue.length) { - stop = this.visitQueue(this.priorityQueue); - this.priorityQueue = []; - this.queue = queue; - if (stop) break; - } - } - - for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var _path = _ref3; - - _path.popContext(); - } - - this.queue = null; - - return stop; - }; - - TraversalContext.prototype.visit = function visit(node, key) { - var nodes = node[key]; - if (!nodes) return false; - - if (Array.isArray(nodes)) { - return this.visitMultiple(nodes, node, key); - } else { - return this.visitSingle(node, key); - } - }; - - return TraversalContext; -}(); - -exports.default = TraversalContext; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./path":125,"_process":525,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],117:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Hub = function Hub(file, options) { - (0, _classCallCheck3.default)(this, Hub); - - this.file = file; - this.options = options; -}; - -exports.default = Hub; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109}],118:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _path = require("./path"); - -Object.defineProperty(exports, "NodePath", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_path).default; - } -}); - -var _scope = require("./scope"); - -Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_scope).default; - } -}); - -var _hub = require("./hub"); - -Object.defineProperty(exports, "Hub", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_hub).default; - } -}); -exports.default = traverse; - -var _context = require("./context"); - -var _context2 = _interopRequireDefault(_context); - -var _visitors = require("./visitors"); - -var visitors = _interopRequireWildcard(_visitors); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("./cache"); - -var cache = _interopRequireWildcard(_cache); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.visitors = visitors; -function traverse(parent, opts, scope, state, parentPath) { - if (!parent) return; - if (!opts) opts = {}; - - if (!opts.noScope && !scope) { - if (parent.type !== "Program" && parent.type !== "File") { - throw new Error(messages.get("traverseNeedsParent", parent.type)); - } - } - - visitors.explode(opts); - - traverse.node(parent, opts, scope, state, parentPath); -} - -traverse.visitors = visitors; -traverse.verify = visitors.verify; -traverse.explode = visitors.explode; - -traverse.NodePath = require("./path"); -traverse.Scope = require("./scope"); -traverse.Hub = require("./hub"); - -traverse.cheap = function (node, enter) { - return t.traverseFast(node, enter); -}; - -traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; - - var context = new _context2.default(scope, opts, state, parentPath); - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var key = _ref; - - if (skipKeys && skipKeys[key]) continue; - if (context.visit(node, key)) return; - } -}; - -traverse.clearNode = function (node, opts) { - t.removeProperties(node, opts); - - cache.path.delete(node); -}; - -traverse.removeProperties = function (tree, opts) { - t.traverseFast(tree, traverse.clearNode, opts); - return tree; -}; - -function hasBlacklistedType(path, state) { - if (path.node.type === state.type) { - state.has = true; - path.stop(); - } -} - -traverse.hasType = function (tree, scope, type, blacklistTypes) { - if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; - - if (tree.type === type) return true; - - var state = { - has: false, - type: type - }; - - traverse(tree, { - blacklist: blacklistTypes, - enter: hasBlacklistedType - }, scope, state); - - return state.has; -}; - -traverse.clearCache = function () { - cache.clear(); -}; - -traverse.clearCache.clearPath = cache.clearPath; -traverse.clearCache.clearScope = cache.clearScope; - -traverse.copyCache = function (source, destination) { - if (cache.path.has(source)) { - cache.path.set(destination, cache.path.get(source)); - } -}; -},{"./cache":115,"./context":116,"./hub":117,"./path":125,"./scope":137,"./visitors":139,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-types":151,"lodash/includes":482}],119:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.findParent = findParent; -exports.find = find; -exports.getFunctionParent = getFunctionParent; -exports.getStatementParent = getStatementParent; -exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; -exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; -exports.getAncestry = getAncestry; -exports.isAncestor = isAncestor; -exports.isDescendant = isDescendant; -exports.inType = inType; -exports.inShadow = inShadow; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function findParent(callback) { - var path = this; - while (path = path.parentPath) { - if (callback(path)) return path; - } - return null; -} - -function find(callback) { - var path = this; - do { - if (callback(path)) return path; - } while (path = path.parentPath); - return null; -} - -function getFunctionParent() { - return this.findParent(function (path) { - return path.isFunction() || path.isProgram(); - }); -} - -function getStatementParent() { - var path = this; - do { - if (Array.isArray(path.container)) { - return path; - } - } while (path = path.parentPath); -} - -function getEarliestCommonAncestorFrom(paths) { - return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { - var earliest = void 0; - var keys = t.VISITOR_KEYS[deepest.type]; - - for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var ancestry = _ref; - - var path = ancestry[i + 1]; - - if (!earliest) { - earliest = path; - continue; - } - - if (path.listKey && earliest.listKey === path.listKey) { - if (path.key < earliest.key) { - earliest = path; - continue; - } - } - - var earliestKeyIndex = keys.indexOf(earliest.parentKey); - var currentKeyIndex = keys.indexOf(path.parentKey); - if (earliestKeyIndex > currentKeyIndex) { - earliest = path; - } - } - - return earliest; - }); -} - -function getDeepestCommonAncestorFrom(paths, filter) { - var _this = this; - - if (!paths.length) { - return this; - } - - if (paths.length === 1) { - return paths[0]; - } - - var minDepth = Infinity; - - var lastCommonIndex = void 0, - lastCommon = void 0; - - var ancestries = paths.map(function (path) { - var ancestry = []; - - do { - ancestry.unshift(path); - } while ((path = path.parentPath) && path !== _this); - - if (ancestry.length < minDepth) { - minDepth = ancestry.length; - } - - return ancestry; - }); - - var first = ancestries[0]; - - depthLoop: for (var i = 0; i < minDepth; i++) { - var shouldMatch = first[i]; - - for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var ancestry = _ref2; - - if (ancestry[i] !== shouldMatch) { - break depthLoop; - } - } - - lastCommonIndex = i; - lastCommon = shouldMatch; - } - - if (lastCommon) { - if (filter) { - return filter(lastCommon, lastCommonIndex, ancestries); - } else { - return lastCommon; - } - } else { - throw new Error("Couldn't find intersection"); - } -} - -function getAncestry() { - var path = this; - var paths = []; - do { - paths.push(path); - } while (path = path.parentPath); - return paths; -} - -function isAncestor(maybeDescendant) { - return maybeDescendant.isDescendant(this); -} - -function isDescendant(maybeAncestor) { - return !!this.findParent(function (parent) { - return parent === maybeAncestor; - }); -} - -function inType() { - var path = this; - while (path) { - for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var type = _ref3; - - if (path.node.type === type) return true; - } - path = path.parentPath; - } - - return false; -} - -function inShadow(key) { - var parentFn = this.isFunction() ? this : this.findParent(function (p) { - return p.isFunction(); - }); - if (!parentFn) return; - - if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { - var shadow = parentFn.node.shadow; - - if (shadow && (!key || shadow[key] !== false)) { - return parentFn; - } - } else if (parentFn.isArrowFunctionExpression()) { - return parentFn; - } - - return null; -} -},{"./index":125,"babel-runtime/core-js/get-iterator":95,"babel-types":151}],120:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.shareCommentsWithSiblings = shareCommentsWithSiblings; -exports.addComment = addComment; -exports.addComments = addComments; -function shareCommentsWithSiblings() { - if (typeof this.key === "string") return; - - var node = this.node; - if (!node) return; - - var trailing = node.trailingComments; - var leading = node.leadingComments; - if (!trailing && !leading) return; - - var prev = this.getSibling(this.key - 1); - var next = this.getSibling(this.key + 1); - - if (!prev.node) prev = next; - if (!next.node) next = prev; - - prev.addComments("trailing", leading); - next.addComments("leading", trailing); -} - -function addComment(type, content, line) { - this.addComments(type, [{ - type: line ? "CommentLine" : "CommentBlock", - value: content - }]); -} - -function addComments(type, comments) { - if (!comments) return; - - var node = this.node; - if (!node) return; - - var key = type + "Comments"; - - if (node[key]) { - node[key] = node[key].concat(comments); - } else { - node[key] = comments; - } -} -},{}],121:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.call = call; -exports._call = _call; -exports.isBlacklisted = isBlacklisted; -exports.visit = visit; -exports.skip = skip; -exports.skipKey = skipKey; -exports.stop = stop; -exports.setScope = setScope; -exports.setContext = setContext; -exports.resync = resync; -exports._resyncParent = _resyncParent; -exports._resyncKey = _resyncKey; -exports._resyncList = _resyncList; -exports._resyncRemoved = _resyncRemoved; -exports.popContext = popContext; -exports.pushContext = pushContext; -exports.setup = setup; -exports.setKey = setKey; -exports.requeue = requeue; -exports._getQueueContexts = _getQueueContexts; - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function call(key) { - var opts = this.opts; - - this.debug(function () { - return key; - }); - - if (this.node) { - if (this._call(opts[key])) return true; - } - - if (this.node) { - return this._call(opts[this.node.type] && opts[this.node.type][key]); - } - - return false; -} - -function _call(fns) { - if (!fns) return false; - - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var fn = _ref; - - if (!fn) continue; - - var node = this.node; - if (!node) return true; - - var ret = fn.call(this.state, this, this.state); - if (ret) throw new Error("Unexpected return value from visitor method " + fn); - - if (this.node !== node) return true; - - if (this.shouldStop || this.shouldSkip || this.removed) return true; - } - - return false; -} - -function isBlacklisted() { - var blacklist = this.opts.blacklist; - return blacklist && blacklist.indexOf(this.node.type) > -1; -} - -function visit() { - if (!this.node) { - return false; - } - - if (this.isBlacklisted()) { - return false; - } - - if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { - return false; - } - - if (this.call("enter") || this.shouldSkip) { - this.debug(function () { - return "Skip..."; - }); - return this.shouldStop; - } - - this.debug(function () { - return "Recursing into..."; - }); - _index2.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys); - - this.call("exit"); - - return this.shouldStop; -} - -function skip() { - this.shouldSkip = true; -} - -function skipKey(key) { - this.skipKeys[key] = true; -} - -function stop() { - this.shouldStop = true; - this.shouldSkip = true; -} - -function setScope() { - if (this.opts && this.opts.noScope) return; - - var target = this.context && this.context.scope; - - if (!target) { - var path = this.parentPath; - while (path && !target) { - if (path.opts && path.opts.noScope) return; - - target = path.scope; - path = path.parentPath; - } - } - - this.scope = this.getScope(target); - if (this.scope) this.scope.init(); -} - -function setContext(context) { - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.skipKeys = {}; - - if (context) { - this.context = context; - this.state = context.state; - this.opts = context.opts; - } - - this.setScope(); - - return this; -} - -function resync() { - if (this.removed) return; - - this._resyncParent(); - this._resyncList(); - this._resyncKey(); -} - -function _resyncParent() { - if (this.parentPath) { - this.parent = this.parentPath.node; - } -} - -function _resyncKey() { - if (!this.container) return; - - if (this.node === this.container[this.key]) return; - - if (Array.isArray(this.container)) { - for (var i = 0; i < this.container.length; i++) { - if (this.container[i] === this.node) { - return this.setKey(i); - } - } - } else { - for (var key in this.container) { - if (this.container[key] === this.node) { - return this.setKey(key); - } - } - } - - this.key = null; -} - -function _resyncList() { - if (!this.parent || !this.inList) return; - - var newContainer = this.parent[this.listKey]; - if (this.container === newContainer) return; - - this.container = newContainer || null; -} - -function _resyncRemoved() { - if (this.key == null || !this.container || this.container[this.key] !== this.node) { - this._markRemoved(); - } -} - -function popContext() { - this.contexts.pop(); - this.setContext(this.contexts[this.contexts.length - 1]); -} - -function pushContext(context) { - this.contexts.push(context); - this.setContext(context); -} - -function setup(parentPath, container, listKey, key) { - this.inList = !!listKey; - this.listKey = listKey; - this.parentKey = listKey || key; - this.container = container; - - this.parentPath = parentPath || this.parentPath; - this.setKey(key); -} - -function setKey(key) { - this.key = key; - this.node = this.container[this.key]; - this.type = this.node && this.node.type; -} - -function requeue() { - var pathToQueue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this; - - if (pathToQueue.removed) return; - - var contexts = this.contexts; - - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var context = _ref2; - - context.maybeQueue(pathToQueue); - } -} - -function _getQueueContexts() { - var path = this; - var contexts = this.contexts; - while (!contexts.length) { - path = path.parentPath; - contexts = path.contexts; - } - return contexts; -} -},{"../index":118,"babel-runtime/core-js/get-iterator":95}],122:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.toComputedKey = toComputedKey; -exports.ensureBlock = ensureBlock; -exports.arrowFunctionToShadowed = arrowFunctionToShadowed; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function toComputedKey() { - var node = this.node; - - var key = void 0; - if (this.isMemberExpression()) { - key = node.property; - } else if (this.isProperty() || this.isMethod()) { - key = node.key; - } else { - throw new ReferenceError("todo"); - } - - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } - - return key; -} - -function ensureBlock() { - return t.ensureBlock(this.node); -} - -function arrowFunctionToShadowed() { - if (!this.isArrowFunctionExpression()) return; - - this.ensureBlock(); - - var node = this.node; - - node.expression = false; - node.type = "FunctionExpression"; - node.shadow = node.shadow || true; -} -},{"babel-types":151}],123:[function(require,module,exports){ -(function (global){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -exports.evaluateTruthy = evaluateTruthy; -exports.evaluate = evaluate; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var VALID_CALLEES = ["String", "Number", "Math"]; -var INVALID_METHODS = ["random"]; - -function evaluateTruthy() { - var res = this.evaluate(); - if (res.confident) return !!res.value; -} - -function evaluate() { - var confident = true; - var deoptPath = void 0; - var seen = new _map2.default(); - - function deopt(path) { - if (!confident) return; - deoptPath = path; - confident = false; - } - - var value = evaluate(this); - if (!confident) value = undefined; - return { - confident: confident, - deopt: deoptPath, - value: value - }; - - function evaluate(path) { - var node = path.node; - - - if (seen.has(node)) { - var existing = seen.get(node); - if (existing.resolved) { - return existing.value; - } else { - deopt(path); - return; - } - } else { - var item = { resolved: false }; - seen.set(node, item); - - var val = _evaluate(path); - if (confident) { - item.resolved = true; - item.value = val; - } - return val; - } - } - - function _evaluate(path) { - if (!confident) return; - - var node = path.node; - - - if (path.isSequenceExpression()) { - var exprs = path.get("expressions"); - return evaluate(exprs[exprs.length - 1]); - } - - if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { - return node.value; - } - - if (path.isNullLiteral()) { - return null; - } - - if (path.isTemplateLiteral()) { - var str = ""; - - var i = 0; - var _exprs = path.get("expressions"); - - for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var elem = _ref; - - if (!confident) break; - - str += elem.value.cooked; - - var expr = _exprs[i++]; - if (expr) str += String(evaluate(expr)); - } - - if (!confident) return; - return str; - } - - if (path.isConditionalExpression()) { - var testResult = evaluate(path.get("test")); - if (!confident) return; - if (testResult) { - return evaluate(path.get("consequent")); - } else { - return evaluate(path.get("alternate")); - } - } - - if (path.isExpressionWrapper()) { - return evaluate(path.get("expression")); - } - - if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { - var property = path.get("property"); - var object = path.get("object"); - - if (object.isLiteral() && property.isIdentifier()) { - var _value = object.node.value; - var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value); - if (type === "number" || type === "string") { - return _value[property.node.name]; - } - } - } - - if (path.isReferencedIdentifier()) { - var binding = path.scope.getBinding(node.name); - - if (binding && binding.constantViolations.length > 0) { - return deopt(binding.path); - } - - if (binding && path.node.start < binding.path.node.end) { - return deopt(binding.path); - } - - if (binding && binding.hasValue) { - return binding.value; - } else { - if (node.name === "undefined") { - return binding ? deopt(binding.path) : undefined; - } else if (node.name === "Infinity") { - return binding ? deopt(binding.path) : Infinity; - } else if (node.name === "NaN") { - return binding ? deopt(binding.path) : NaN; - } - - var resolved = path.resolve(); - if (resolved === path) { - return deopt(path); - } else { - return evaluate(resolved); - } - } - } - - if (path.isUnaryExpression({ prefix: true })) { - if (node.operator === "void") { - return undefined; - } - - var argument = path.get("argument"); - if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { - return "function"; - } - - var arg = evaluate(argument); - if (!confident) return; - switch (node.operator) { - case "!": - return !arg; - case "+": - return +arg; - case "-": - return -arg; - case "~": - return ~arg; - case "typeof": - return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg); - } - } - - if (path.isArrayExpression()) { - var arr = []; - var elems = path.get("elements"); - for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _elem = _ref2; - - _elem = _elem.evaluate(); - - if (_elem.confident) { - arr.push(_elem.value); - } else { - return deopt(_elem); - } - } - return arr; - } - - if (path.isObjectExpression()) { - var obj = {}; - var props = path.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var prop = _ref3; - - if (prop.isObjectMethod() || prop.isSpreadProperty()) { - return deopt(prop); - } - var keyPath = prop.get("key"); - var key = keyPath; - if (prop.node.computed) { - key = key.evaluate(); - if (!key.confident) { - return deopt(keyPath); - } - key = key.value; - } else if (key.isIdentifier()) { - key = key.node.name; - } else { - key = key.node.value; - } - var valuePath = prop.get("value"); - var _value2 = valuePath.evaluate(); - if (!_value2.confident) { - return deopt(valuePath); - } - _value2 = _value2.value; - obj[key] = _value2; - } - return obj; - } - - if (path.isLogicalExpression()) { - var wasConfident = confident; - var left = evaluate(path.get("left")); - var leftConfident = confident; - confident = wasConfident; - var right = evaluate(path.get("right")); - var rightConfident = confident; - confident = leftConfident && rightConfident; - - switch (node.operator) { - case "||": - if (left && leftConfident) { - confident = true; - return left; - } - - if (!confident) return; - - return left || right; - case "&&": - if (!left && leftConfident || !right && rightConfident) { - confident = true; - } - - if (!confident) return; - - return left && right; - } - } - - if (path.isBinaryExpression()) { - var _left = evaluate(path.get("left")); - if (!confident) return; - var _right = evaluate(path.get("right")); - if (!confident) return; - - switch (node.operator) { - case "-": - return _left - _right; - case "+": - return _left + _right; - case "/": - return _left / _right; - case "*": - return _left * _right; - case "%": - return _left % _right; - case "**": - return Math.pow(_left, _right); - case "<": - return _left < _right; - case ">": - return _left > _right; - case "<=": - return _left <= _right; - case ">=": - return _left >= _right; - case "==": - return _left == _right; - case "!=": - return _left != _right; - case "===": - return _left === _right; - case "!==": - return _left !== _right; - case "|": - return _left | _right; - case "&": - return _left & _right; - case "^": - return _left ^ _right; - case "<<": - return _left << _right; - case ">>": - return _left >> _right; - case ">>>": - return _left >>> _right; - } - } - - if (path.isCallExpression()) { - var callee = path.get("callee"); - var context = void 0; - var func = void 0; - - if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { - func = global[node.callee.name]; - } - - if (callee.isMemberExpression()) { - var _object = callee.get("object"); - var _property = callee.get("property"); - - if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) { - context = global[_object.node.name]; - func = context[_property.node.name]; - } - - if (_object.isLiteral() && _property.isIdentifier()) { - var _type = (0, _typeof3.default)(_object.node.value); - if (_type === "string" || _type === "number") { - context = _object.node.value; - func = context[_property.node.name]; - } - } - } - - if (func) { - var args = path.get("arguments").map(evaluate); - if (!confident) return; - - return func.apply(context, args); - } - } - - deopt(path); - } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/map":97,"babel-runtime/helpers/typeof":113}],124:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.getStatementParent = getStatementParent; -exports.getOpposite = getOpposite; -exports.getCompletionRecords = getCompletionRecords; -exports.getSibling = getSibling; -exports.getPrevSibling = getPrevSibling; -exports.getNextSibling = getNextSibling; -exports.getAllNextSiblings = getAllNextSiblings; -exports.getAllPrevSiblings = getAllPrevSiblings; -exports.get = get; -exports._getKey = _getKey; -exports._getPattern = _getPattern; -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; -exports.getBindingIdentifierPaths = getBindingIdentifierPaths; -exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getStatementParent() { - var path = this; - - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { - break; - } else { - path = path.parentPath; - } - } while (path); - - if (path && (path.isProgram() || path.isFile())) { - throw new Error("File/Program node, we can't possibly find a statement parent to this"); - } - - return path; -} - -function getOpposite() { - if (this.key === "left") { - return this.getSibling("right"); - } else if (this.key === "right") { - return this.getSibling("left"); - } -} - -function getCompletionRecords() { - var paths = []; - - var add = function add(path) { - if (path) paths = paths.concat(path.getCompletionRecords()); - }; - - if (this.isIfStatement()) { - add(this.get("consequent")); - add(this.get("alternate")); - } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { - add(this.get("body")); - } else if (this.isProgram() || this.isBlockStatement()) { - add(this.get("body").pop()); - } else if (this.isFunction()) { - return this.get("body").getCompletionRecords(); - } else if (this.isTryStatement()) { - add(this.get("block")); - add(this.get("handler")); - add(this.get("finalizer")); - } else { - paths.push(this); - } - - return paths; -} - -function getSibling(key) { - return _index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: key - }); -} - -function getPrevSibling() { - return this.getSibling(this.key - 1); -} - -function getNextSibling() { - return this.getSibling(this.key + 1); -} - -function getAllNextSiblings() { - var _key = this.key; - var sibling = this.getSibling(++_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(++_key); - } - return siblings; -} - -function getAllPrevSiblings() { - var _key = this.key; - var sibling = this.getSibling(--_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(--_key); - } - return siblings; -} - -function get(key, context) { - if (context === true) context = this.context; - var parts = key.split("."); - if (parts.length === 1) { - return this._getKey(key, context); - } else { - return this._getPattern(parts, context); - } -} - -function _getKey(key, context) { - var _this = this; - - var node = this.node; - var container = node[key]; - - if (Array.isArray(container)) { - return container.map(function (_, i) { - return _index2.default.get({ - listKey: key, - parentPath: _this, - parent: node, - container: container, - key: i - }).setContext(context); - }); - } else { - return _index2.default.get({ - parentPath: this, - parent: node, - container: node, - key: key - }).setContext(context); - } -} - -function _getPattern(parts, context) { - var path = this; - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var part = _ref; - - if (part === ".") { - path = path.parentPath; - } else { - if (Array.isArray(path)) { - path = path[part]; - } else { - path = path.get(part, context); - } - } - } - return path; -} - -function getBindingIdentifiers(duplicates) { - return t.getBindingIdentifiers(this.node, duplicates); -} - -function getOuterBindingIdentifiers(duplicates) { - return t.getOuterBindingIdentifiers(this.node, duplicates); -} - -function getBindingIdentifierPaths() { - var duplicates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var outerOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - var path = this; - var search = [].concat(path); - var ids = (0, _create2.default)(null); - - while (search.length) { - var id = search.shift(); - if (!id) continue; - if (!id.node) continue; - - var keys = t.getBindingIdentifiers.keys[id.node.type]; - - if (id.isIdentifier()) { - if (duplicates) { - var _ids = ids[id.node.name] = ids[id.node.name] || []; - _ids.push(id); - } else { - ids[id.node.name] = id; - } - continue; - } - - if (id.isExportDeclaration()) { - var declaration = id.get("declaration"); - if (declaration.isDeclaration()) { - search.push(declaration); - } - continue; - } - - if (outerOnly) { - if (id.isFunctionDeclaration()) { - search.push(id.get("id")); - continue; - } - if (id.isFunctionExpression()) { - continue; - } - } - - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = id.get(key); - if (Array.isArray(child) || child.node) { - search = search.concat(child); - } - } - } - } - - return ids; -} - -function getOuterBindingIdentifierPaths(duplicates) { - return this.getBindingIdentifierPaths(duplicates, true); -} -},{"./index":125,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-types":151}],125:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _virtualTypes = require("./lib/virtual-types"); - -var virtualTypes = _interopRequireWildcard(_virtualTypes); - -var _debug2 = require("debug"); - -var _debug3 = _interopRequireDefault(_debug2); - -var _invariant = require("invariant"); - -var _invariant2 = _interopRequireDefault(_invariant); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _assign = require("lodash/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _scope = require("../scope"); - -var _scope2 = _interopRequireDefault(_scope); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("../cache"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _debug = (0, _debug3.default)("babel"); - -var NodePath = function () { - function NodePath(hub, parent) { - (0, _classCallCheck3.default)(this, NodePath); - - this.parent = parent; - this.hub = hub; - this.contexts = []; - this.data = {}; - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.state = null; - this.opts = null; - this.skipKeys = null; - this.parentPath = null; - this.context = null; - this.container = null; - this.listKey = null; - this.inList = false; - this.parentKey = null; - this.key = null; - this.node = null; - this.scope = null; - this.type = null; - this.typeAnnotation = null; - } - - NodePath.get = function get(_ref) { - var hub = _ref.hub, - parentPath = _ref.parentPath, - parent = _ref.parent, - container = _ref.container, - listKey = _ref.listKey, - key = _ref.key; - - if (!hub && parentPath) { - hub = parentPath.hub; - } - - (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); - - var targetNode = container[key]; - - var paths = _cache.path.get(parent) || []; - if (!_cache.path.has(parent)) { - _cache.path.set(parent, paths); - } - - var path = void 0; - - for (var i = 0; i < paths.length; i++) { - var pathCheck = paths[i]; - if (pathCheck.node === targetNode) { - path = pathCheck; - break; - } - } - - if (!path) { - path = new NodePath(hub, parent); - paths.push(path); - } - - path.setup(parentPath, container, listKey, key); - - return path; - }; - - NodePath.prototype.getScope = function getScope(scope) { - var ourScope = scope; - - if (this.isScope()) { - ourScope = new _scope2.default(this, scope); - } - - return ourScope; - }; - - NodePath.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; - - NodePath.prototype.getData = function getData(key, def) { - var val = this.data[key]; - if (!val && def) val = this.data[key] = def; - return val; - }; - - NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { - var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError; - - return this.hub.file.buildCodeFrameError(this.node, msg, Error); - }; - - NodePath.prototype.traverse = function traverse(visitor, state) { - (0, _index2.default)(this.node, visitor, this.scope, state, this); - }; - - NodePath.prototype.mark = function mark(type, message) { - this.hub.file.metadata.marked.push({ - type: type, - message: message, - loc: this.node.loc - }); - }; - - NodePath.prototype.set = function set(key, node) { - t.validate(this.node, key, node); - this.node[key] = node; - }; - - NodePath.prototype.getPathLocation = function getPathLocation() { - var parts = []; - var path = this; - do { - var key = path.key; - if (path.inList) key = path.listKey + "[" + key + "]"; - parts.unshift(key); - } while (path = path.parentPath); - return parts.join("."); - }; - - NodePath.prototype.debug = function debug(buildMessage) { - if (!_debug.enabled) return; - _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); - }; - - return NodePath; -}(); - -exports.default = NodePath; - - -(0, _assign2.default)(NodePath.prototype, require("./ancestry")); -(0, _assign2.default)(NodePath.prototype, require("./inference")); -(0, _assign2.default)(NodePath.prototype, require("./replacement")); -(0, _assign2.default)(NodePath.prototype, require("./evaluation")); -(0, _assign2.default)(NodePath.prototype, require("./conversion")); -(0, _assign2.default)(NodePath.prototype, require("./introspection")); -(0, _assign2.default)(NodePath.prototype, require("./context")); -(0, _assign2.default)(NodePath.prototype, require("./removal")); -(0, _assign2.default)(NodePath.prototype, require("./modification")); -(0, _assign2.default)(NodePath.prototype, require("./family")); -(0, _assign2.default)(NodePath.prototype, require("./comments")); - -var _loop2 = function _loop2() { - if (_isArray) { - if (_i >= _iterator.length) return "break"; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) return "break"; - _ref2 = _i.value; - } - - var type = _ref2; - - var typeKey = "is" + type; - NodePath.prototype[typeKey] = function (opts) { - return t[typeKey](this.node, opts); - }; - - NodePath.prototype["assert" + type] = function (opts) { - if (!this[typeKey](opts)) { - throw new TypeError("Expected node path of type " + type); - } - }; -}; - -for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - var _ret2 = _loop2(); - - if (_ret2 === "break") break; -} - -var _loop = function _loop(type) { - if (type[0] === "_") return "continue"; - if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); - - var virtualType = virtualTypes[type]; - - NodePath.prototype["is" + type] = function (opts) { - return virtualType.checkPath(this, opts); - }; -}; - -for (var type in virtualTypes) { - var _ret = _loop(type); - - if (_ret === "continue") continue; -} -module.exports = exports["default"]; -},{"../cache":115,"../index":118,"../scope":137,"./ancestry":119,"./comments":120,"./context":121,"./conversion":122,"./evaluation":123,"./family":124,"./inference":126,"./introspection":129,"./lib/virtual-types":132,"./modification":133,"./removal":134,"./replacement":135,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-types":151,"debug":279,"invariant":292,"lodash/assign":463}],126:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.getTypeAnnotation = getTypeAnnotation; -exports._getTypeAnnotation = _getTypeAnnotation; -exports.isBaseType = isBaseType; -exports.couldBeBaseType = couldBeBaseType; -exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; -exports.isGenericType = isGenericType; - -var _inferers = require("./inferers"); - -var inferers = _interopRequireWildcard(_inferers); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getTypeAnnotation() { - if (this.typeAnnotation) return this.typeAnnotation; - - var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); - if (t.isTypeAnnotation(type)) type = type.typeAnnotation; - return this.typeAnnotation = type; -} - -function _getTypeAnnotation() { - var node = this.node; - - if (!node) { - if (this.key === "init" && this.parentPath.isVariableDeclarator()) { - var declar = this.parentPath.parentPath; - var declarParent = declar.parentPath; - - if (declar.key === "left" && declarParent.isForInStatement()) { - return t.stringTypeAnnotation(); - } - - if (declar.key === "left" && declarParent.isForOfStatement()) { - return t.anyTypeAnnotation(); - } - - return t.voidTypeAnnotation(); - } else { - return; - } - } - - if (node.typeAnnotation) { - return node.typeAnnotation; - } - - var inferer = inferers[node.type]; - if (inferer) { - return inferer.call(this, node); - } - - inferer = inferers[this.parentPath.type]; - if (inferer && inferer.validParent) { - return this.parentPath.getTypeAnnotation(); - } -} - -function isBaseType(baseName, soft) { - return _isBaseType(baseName, this.getTypeAnnotation(), soft); -} - -function _isBaseType(baseName, type, soft) { - if (baseName === "string") { - return t.isStringTypeAnnotation(type); - } else if (baseName === "number") { - return t.isNumberTypeAnnotation(type); - } else if (baseName === "boolean") { - return t.isBooleanTypeAnnotation(type); - } else if (baseName === "any") { - return t.isAnyTypeAnnotation(type); - } else if (baseName === "mixed") { - return t.isMixedTypeAnnotation(type); - } else if (baseName === "empty") { - return t.isEmptyTypeAnnotation(type); - } else if (baseName === "void") { - return t.isVoidTypeAnnotation(type); - } else { - if (soft) { - return false; - } else { - throw new Error("Unknown base type " + baseName); - } - } -} - -function couldBeBaseType(name) { - var type = this.getTypeAnnotation(); - if (t.isAnyTypeAnnotation(type)) return true; - - if (t.isUnionTypeAnnotation(type)) { - for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var type2 = _ref; - - if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { - return true; - } - } - return false; - } else { - return _isBaseType(name, type, true); - } -} - -function baseTypeStrictlyMatches(right) { - var left = this.getTypeAnnotation(); - right = right.getTypeAnnotation(); - - if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { - return right.type === left.type; - } -} - -function isGenericType(genericName) { - var type = this.getTypeAnnotation(); - return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); -} -},{"./inferers":128,"babel-runtime/core-js/get-iterator":95,"babel-types":151}],127:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (node) { - if (!this.isReferenced()) return; - - var binding = this.scope.getBinding(node.name); - if (binding) { - if (binding.identifier.typeAnnotation) { - return binding.identifier.typeAnnotation; - } else { - return getTypeAnnotationBindingConstantViolations(this, node.name); - } - } - - if (node.name === "undefined") { - return t.voidTypeAnnotation(); - } else if (node.name === "NaN" || node.name === "Infinity") { - return t.numberTypeAnnotation(); - } else if (node.name === "arguments") {} -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getTypeAnnotationBindingConstantViolations(path, name) { - var binding = path.scope.getBinding(name); - - var types = []; - path.typeAnnotation = t.unionTypeAnnotation(types); - - var functionConstantViolations = []; - var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); - - var testType = getConditionalAnnotation(path, name); - if (testType) { - var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); - - constantViolations = constantViolations.filter(function (path) { - return testConstantViolations.indexOf(path) < 0; - }); - - types.push(testType.typeAnnotation); - } - - if (constantViolations.length) { - constantViolations = constantViolations.concat(functionConstantViolations); - - for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var violation = _ref; - - types.push(violation.getTypeAnnotation()); - } - } - - if (types.length) { - return t.createUnionTypeAnnotation(types); - } -} - -function getConstantViolationsBefore(binding, path, functions) { - var violations = binding.constantViolations.slice(); - violations.unshift(binding.path); - return violations.filter(function (violation) { - violation = violation.resolve(); - var status = violation._guessExecutionStatusRelativeTo(path); - if (functions && status === "function") functions.push(violation); - return status === "before"; - }); -} - -function inferAnnotationFromBinaryExpression(name, path) { - var operator = path.node.operator; - - var right = path.get("right").resolve(); - var left = path.get("left").resolve(); - - var target = void 0; - if (left.isIdentifier({ name: name })) { - target = right; - } else if (right.isIdentifier({ name: name })) { - target = left; - } - if (target) { - if (operator === "===") { - return target.getTypeAnnotation(); - } else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else { - return; - } - } else { - if (operator !== "===") return; - } - - var typeofPath = void 0; - var typePath = void 0; - if (left.isUnaryExpression({ operator: "typeof" })) { - typeofPath = left; - typePath = right; - } else if (right.isUnaryExpression({ operator: "typeof" })) { - typeofPath = right; - typePath = left; - } - if (!typePath && !typeofPath) return; - - typePath = typePath.resolve(); - if (!typePath.isLiteral()) return; - - var typeValue = typePath.node.value; - if (typeof typeValue !== "string") return; - - if (!typeofPath.get("argument").isIdentifier({ name: name })) return; - - return t.createTypeAnnotationBasedOnTypeof(typePath.node.value); -} - -function getParentConditionalPath(path) { - var parentPath = void 0; - while (parentPath = path.parentPath) { - if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { - if (path.key === "test") { - return; - } else { - return parentPath; - } - } else { - path = parentPath; - } - } -} - -function getConditionalAnnotation(path, name) { - var ifStatement = getParentConditionalPath(path); - if (!ifStatement) return; - - var test = ifStatement.get("test"); - var paths = [test]; - var types = []; - - do { - var _path = paths.shift().resolve(); - - if (_path.isLogicalExpression()) { - paths.push(_path.get("left")); - paths.push(_path.get("right")); - } - - if (_path.isBinaryExpression()) { - var type = inferAnnotationFromBinaryExpression(name, _path); - if (type) types.push(type); - } - } while (paths.length); - - if (types.length) { - return { - typeAnnotation: t.createUnionTypeAnnotation(types), - ifStatement: ifStatement - }; - } else { - return getConditionalAnnotation(ifStatement, name); - } -} -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],128:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = exports.Identifier = undefined; - -var _infererReference = require("./inferer-reference"); - -Object.defineProperty(exports, "Identifier", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_infererReference).default; - } -}); -exports.VariableDeclarator = VariableDeclarator; -exports.TypeCastExpression = TypeCastExpression; -exports.NewExpression = NewExpression; -exports.TemplateLiteral = TemplateLiteral; -exports.UnaryExpression = UnaryExpression; -exports.BinaryExpression = BinaryExpression; -exports.LogicalExpression = LogicalExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.SequenceExpression = SequenceExpression; -exports.AssignmentExpression = AssignmentExpression; -exports.UpdateExpression = UpdateExpression; -exports.StringLiteral = StringLiteral; -exports.NumericLiteral = NumericLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.RegExpLiteral = RegExpLiteral; -exports.ObjectExpression = ObjectExpression; -exports.ArrayExpression = ArrayExpression; -exports.RestElement = RestElement; -exports.CallExpression = CallExpression; -exports.TaggedTemplateExpression = TaggedTemplateExpression; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function VariableDeclarator() { - var id = this.get("id"); - - if (id.isIdentifier()) { - return this.get("init").getTypeAnnotation(); - } else { - return; - } -} - -function TypeCastExpression(node) { - return node.typeAnnotation; -} - -TypeCastExpression.validParent = true; - -function NewExpression(node) { - if (this.get("callee").isIdentifier()) { - return t.genericTypeAnnotation(node.callee); - } -} - -function TemplateLiteral() { - return t.stringTypeAnnotation(); -} - -function UnaryExpression(node) { - var operator = node.operator; - - if (operator === "void") { - return t.voidTypeAnnotation(); - } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.stringTypeAnnotation(); - } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } -} - -function BinaryExpression(node) { - var operator = node.operator; - - if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } else if (operator === "+") { - var right = this.get("right"); - var left = this.get("left"); - - if (left.isBaseType("number") && right.isBaseType("number")) { - return t.numberTypeAnnotation(); - } else if (left.isBaseType("string") || right.isBaseType("string")) { - return t.stringTypeAnnotation(); - } - - return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]); - } -} - -function LogicalExpression() { - return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); -} - -function ConditionalExpression() { - return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); -} - -function SequenceExpression() { - return this.get("expressions").pop().getTypeAnnotation(); -} - -function AssignmentExpression() { - return this.get("right").getTypeAnnotation(); -} - -function UpdateExpression(node) { - var operator = node.operator; - if (operator === "++" || operator === "--") { - return t.numberTypeAnnotation(); - } -} - -function StringLiteral() { - return t.stringTypeAnnotation(); -} - -function NumericLiteral() { - return t.numberTypeAnnotation(); -} - -function BooleanLiteral() { - return t.booleanTypeAnnotation(); -} - -function NullLiteral() { - return t.nullLiteralTypeAnnotation(); -} - -function RegExpLiteral() { - return t.genericTypeAnnotation(t.identifier("RegExp")); -} - -function ObjectExpression() { - return t.genericTypeAnnotation(t.identifier("Object")); -} - -function ArrayExpression() { - return t.genericTypeAnnotation(t.identifier("Array")); -} - -function RestElement() { - return ArrayExpression(); -} - -RestElement.validParent = true; - -function Func() { - return t.genericTypeAnnotation(t.identifier("Function")); -} - -exports.FunctionExpression = Func; -exports.ArrowFunctionExpression = Func; -exports.FunctionDeclaration = Func; -exports.ClassExpression = Func; -exports.ClassDeclaration = Func; -function CallExpression() { - return resolveCall(this.get("callee")); -} - -function TaggedTemplateExpression() { - return resolveCall(this.get("tag")); -} - -function resolveCall(callee) { - callee = callee.resolve(); - - if (callee.isFunction()) { - if (callee.is("async")) { - if (callee.is("generator")) { - return t.genericTypeAnnotation(t.identifier("AsyncIterator")); - } else { - return t.genericTypeAnnotation(t.identifier("Promise")); - } - } else { - if (callee.node.returnType) { - return callee.node.returnType; - } else {} - } - } -} -},{"./inferer-reference":127,"babel-types":151}],129:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.is = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.matchesPattern = matchesPattern; -exports.has = has; -exports.isStatic = isStatic; -exports.isnt = isnt; -exports.equals = equals; -exports.isNodeType = isNodeType; -exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; -exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; -exports.isCompletionRecord = isCompletionRecord; -exports.isStatementOrBlock = isStatementOrBlock; -exports.referencesImport = referencesImport; -exports.getSource = getSource; -exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; -exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; -exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; -exports.resolve = resolve; -exports._resolve = _resolve; - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function matchesPattern(pattern, allowPartial) { - if (!this.isMemberExpression()) return false; - - var parts = pattern.split("."); - var search = [this.node]; - var i = 0; - - function matches(name) { - var part = parts[i]; - return part === "*" || name === part; - } - - while (search.length) { - var node = search.shift(); - - if (allowPartial && i === parts.length) { - return true; - } - - if (t.isIdentifier(node)) { - if (!matches(node.name)) return false; - } else if (t.isLiteral(node)) { - if (!matches(node.value)) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isLiteral(node.property)) { - return false; - } else { - search.unshift(node.property); - search.unshift(node.object); - continue; - } - } else if (t.isThisExpression(node)) { - if (!matches("this")) return false; - } else { - return false; - } - - if (++i > parts.length) { - return false; - } - } - - return i === parts.length; -} - -function has(key) { - var val = this.node && this.node[key]; - if (val && Array.isArray(val)) { - return !!val.length; - } else { - return !!val; - } -} - -function isStatic() { - return this.scope.isStatic(this.node); -} - -var is = exports.is = has; - -function isnt(key) { - return !this.has(key); -} - -function equals(key, value) { - return this.node[key] === value; -} - -function isNodeType(type) { - return t.isType(this.type, type); -} - -function canHaveVariableDeclarationOrExpression() { - return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); -} - -function canSwapBetweenExpressionAndStatement(replacement) { - if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { - return false; - } - - if (this.isExpression()) { - return t.isBlockStatement(replacement); - } else if (this.isBlockStatement()) { - return t.isExpression(replacement); - } - - return false; -} - -function isCompletionRecord(allowInsideFunction) { - var path = this; - var first = true; - - do { - var container = path.container; - - if (path.isFunction() && !first) { - return !!allowInsideFunction; - } - - first = false; - - if (Array.isArray(container) && path.key !== container.length - 1) { - return false; - } - } while ((path = path.parentPath) && !path.isProgram()); - - return true; -} - -function isStatementOrBlock() { - if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { - return false; - } else { - return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key); - } -} - -function referencesImport(moduleSource, importName) { - if (!this.isReferencedIdentifier()) return false; - - var binding = this.scope.getBinding(this.node.name); - if (!binding || binding.kind !== "module") return false; - - var path = binding.path; - var parent = path.parentPath; - if (!parent.isImportDeclaration()) return false; - - if (parent.node.source.value === moduleSource) { - if (!importName) return true; - } else { - return false; - } - - if (path.isImportDefaultSpecifier() && importName === "default") { - return true; - } - - if (path.isImportNamespaceSpecifier() && importName === "*") { - return true; - } - - if (path.isImportSpecifier() && path.node.imported.name === importName) { - return true; - } - - return false; -} - -function getSource() { - var node = this.node; - if (node.end) { - return this.hub.file.code.slice(node.start, node.end); - } else { - return ""; - } -} - -function willIMaybeExecuteBefore(target) { - return this._guessExecutionStatusRelativeTo(target) !== "after"; -} - -function _guessExecutionStatusRelativeTo(target) { - var targetFuncParent = target.scope.getFunctionParent(); - var selfFuncParent = this.scope.getFunctionParent(); - - if (targetFuncParent.node !== selfFuncParent.node) { - var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); - if (status) { - return status; - } else { - target = targetFuncParent.path; - } - } - - var targetPaths = target.getAncestry(); - if (targetPaths.indexOf(this) >= 0) return "after"; - - var selfPaths = this.getAncestry(); - - var commonPath = void 0; - var targetIndex = void 0; - var selfIndex = void 0; - for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { - var selfPath = selfPaths[selfIndex]; - targetIndex = targetPaths.indexOf(selfPath); - if (targetIndex >= 0) { - commonPath = selfPath; - break; - } - } - if (!commonPath) { - return "before"; - } - - var targetRelationship = targetPaths[targetIndex - 1]; - var selfRelationship = selfPaths[selfIndex - 1]; - if (!targetRelationship || !selfRelationship) { - return "before"; - } - - if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { - return targetRelationship.key > selfRelationship.key ? "before" : "after"; - } - - var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); - var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); - return targetKeyPosition > selfKeyPosition ? "before" : "after"; -} - -function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { - var targetFuncPath = targetFuncParent.path; - if (!targetFuncPath.isFunctionDeclaration()) return; - - var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); - - if (!binding.references) return "before"; - - var referencePaths = binding.referencePaths; - - for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var path = _ref; - - if (path.key !== "callee" || !path.parentPath.isCallExpression()) { - return; - } - } - - var allStatus = void 0; - - for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _path = _ref2; - - var childOfFunction = !!_path.find(function (path) { - return path.node === targetFuncPath.node; - }); - if (childOfFunction) continue; - - var status = this._guessExecutionStatusRelativeTo(_path); - - if (allStatus) { - if (allStatus !== status) return; - } else { - allStatus = status; - } - } - - return allStatus; -} - -function resolve(dangerous, resolved) { - return this._resolve(dangerous, resolved) || this; -} - -function _resolve(dangerous, resolved) { - if (resolved && resolved.indexOf(this) >= 0) return; - - resolved = resolved || []; - resolved.push(this); - - if (this.isVariableDeclarator()) { - if (this.get("id").isIdentifier()) { - return this.get("init").resolve(dangerous, resolved); - } else {} - } else if (this.isReferencedIdentifier()) { - var binding = this.scope.getBinding(this.node.name); - if (!binding) return; - - if (!binding.constant) return; - - if (binding.kind === "module") return; - - if (binding.path !== this) { - var ret = binding.path.resolve(dangerous, resolved); - - if (this.find(function (parent) { - return parent.node === ret.node; - })) return; - return ret; - } - } else if (this.isTypeCastExpression()) { - return this.get("expression").resolve(dangerous, resolved); - } else if (dangerous && this.isMemberExpression()) { - - var targetKey = this.toComputedKey(); - if (!t.isLiteral(targetKey)) return; - - var targetName = targetKey.value; - - var target = this.get("object").resolve(dangerous, resolved); - - if (target.isObjectExpression()) { - var props = target.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var prop = _ref3; - - if (!prop.isProperty()) continue; - - var key = prop.get("key"); - - var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); - - match = match || key.isLiteral({ value: targetName }); - - if (match) return prop.get("value").resolve(dangerous, resolved); - } - } else if (target.isArrayExpression() && !isNaN(+targetName)) { - var elems = target.get("elements"); - var elem = elems[targetName]; - if (elem) return elem.resolve(dangerous, resolved); - } - } -} -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151,"lodash/includes":482}],130:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var referenceVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) { - return; - } - - if (path.node.name === "this") { - var scope = path.scope; - do { - if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break; - } while (scope = scope.parent); - if (scope) state.breakOnScopePaths.push(scope.path); - } - - var binding = path.scope.getBinding(path.node.name); - if (!binding) return; - - if (binding !== state.scope.getBinding(path.node.name)) return; - - state.bindings[path.node.name] = binding; - } -}; - -var PathHoister = function () { - function PathHoister(path, scope) { - (0, _classCallCheck3.default)(this, PathHoister); - - this.breakOnScopePaths = []; - - this.bindings = {}; - - this.scopes = []; - - this.scope = scope; - this.path = path; - - this.attachAfter = false; - } - - PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { - for (var key in this.bindings) { - var binding = this.bindings[key]; - if (!scope.bindingIdentifierEquals(key, binding.identifier)) { - return false; - } - } - - return true; - }; - - PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { - var scope = this.path.scope; - do { - if (this.isCompatibleScope(scope)) { - this.scopes.push(scope); - } else { - break; - } - - if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { - break; - } - } while (scope = scope.parent); - }; - - PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { - var path = this._getAttachmentPath(); - if (!path) return; - - var targetScope = path.scope; - - if (targetScope.path === path) { - targetScope = path.scope.parent; - } - - if (targetScope.path.isProgram() || targetScope.path.isFunction()) { - for (var name in this.bindings) { - if (!targetScope.hasOwnBinding(name)) continue; - - var binding = this.bindings[name]; - - if (binding.kind === "param") continue; - - if (this.getAttachmentParentForPath(binding.path).key > path.key) { - this.attachAfter = true; - path = binding.path; - - for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var violationPath = _ref; - - if (this.getAttachmentParentForPath(violationPath).key > path.key) { - path = violationPath; - } - } - } - } - } - - if (path.parentPath.isExportDeclaration()) { - path = path.parentPath; - } - - return path; - }; - - PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { - var scopes = this.scopes; - - var scope = scopes.pop(); - - if (!scope) return; - - if (scope.path.isFunction()) { - if (this.hasOwnParamBindings(scope)) { - if (this.scope === scope) return; - - return scope.path.get("body").get("body")[0]; - } else { - return this.getNextScopeAttachmentParent(); - } - } else if (scope.path.isProgram()) { - return this.getNextScopeAttachmentParent(); - } - }; - - PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() { - var scope = this.scopes.pop(); - if (scope) return this.getAttachmentParentForPath(scope.path); - }; - - PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) { - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path; - } while (path = path.parentPath); - }; - - PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { - for (var name in this.bindings) { - if (!scope.hasOwnBinding(name)) continue; - - var binding = this.bindings[name]; - - if (binding.kind === "param" && binding.constant) return true; - } - return false; - }; - - PathHoister.prototype.run = function run() { - var node = this.path.node; - if (node._hoisted) return; - node._hoisted = true; - - this.path.traverse(referenceVisitor, this); - - this.getCompatibleScopes(); - - var attachTo = this.getAttachmentPath(); - if (!attachTo) return; - - if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; - - var uid = attachTo.scope.generateUidIdentifier("ref"); - var declarator = t.variableDeclarator(uid, this.path.node); - - var insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; - attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]); - - var parent = this.path.parentPath; - if (parent.isJSXElement() && this.path.container === parent.node.children) { - uid = t.JSXExpressionContainer(uid); - } - - this.path.replaceWith(uid); - }; - - return PathHoister; -}(); - -exports.default = PathHoister; -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],131:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -var hooks = exports.hooks = [function (self, parent) { - var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement(); - - if (removeParent) { - parent.remove(); - return true; - } -}, function (self, parent) { - if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { - parent.replaceWith(parent.node.expressions[0]); - return true; - } -}, function (self, parent) { - if (parent.isBinary()) { - if (self.key === "left") { - parent.replaceWith(parent.node.right); - } else { - parent.replaceWith(parent.node.left); - } - return true; - } -}, function (self, parent) { - if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) { - self.replaceWith({ - type: "BlockStatement", - body: [] - }); - return true; - } -}]; -},{}],132:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var ReferencedIdentifier = exports.ReferencedIdentifier = { - types: ["Identifier", "JSXIdentifier"], - checkPath: function checkPath(_ref, opts) { - var node = _ref.node, - parent = _ref.parent; - - if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { - if (t.isJSXIdentifier(node, opts)) { - if (_babelTypes.react.isCompatTag(node.name)) return false; - } else { - return false; - } - } - - return t.isReferenced(node, parent); - } -}; - -var ReferencedMemberExpression = exports.ReferencedMemberExpression = { - types: ["MemberExpression"], - checkPath: function checkPath(_ref2) { - var node = _ref2.node, - parent = _ref2.parent; - - return t.isMemberExpression(node) && t.isReferenced(node, parent); - } -}; - -var BindingIdentifier = exports.BindingIdentifier = { - types: ["Identifier"], - checkPath: function checkPath(_ref3) { - var node = _ref3.node, - parent = _ref3.parent; - - return t.isIdentifier(node) && t.isBinding(node, parent); - } -}; - -var Statement = exports.Statement = { - types: ["Statement"], - checkPath: function checkPath(_ref4) { - var node = _ref4.node, - parent = _ref4.parent; - - if (t.isStatement(node)) { - if (t.isVariableDeclaration(node)) { - if (t.isForXStatement(parent, { left: node })) return false; - if (t.isForStatement(parent, { init: node })) return false; - } - - return true; - } else { - return false; - } - } -}; - -var Expression = exports.Expression = { - types: ["Expression"], - checkPath: function checkPath(path) { - if (path.isIdentifier()) { - return path.isReferencedIdentifier(); - } else { - return t.isExpression(path.node); - } - } -}; - -var Scope = exports.Scope = { - types: ["Scopable"], - checkPath: function checkPath(path) { - return t.isScope(path.node, path.parent); - } -}; - -var Referenced = exports.Referenced = { - checkPath: function checkPath(path) { - return t.isReferenced(path.node, path.parent); - } -}; - -var BlockScoped = exports.BlockScoped = { - checkPath: function checkPath(path) { - return t.isBlockScoped(path.node); - } -}; - -var Var = exports.Var = { - types: ["VariableDeclaration"], - checkPath: function checkPath(path) { - return t.isVar(path.node); - } -}; - -var User = exports.User = { - checkPath: function checkPath(path) { - return path.node && !!path.node.loc; - } -}; - -var Generated = exports.Generated = { - checkPath: function checkPath(path) { - return !path.isUser(); - } -}; - -var Pure = exports.Pure = { - checkPath: function checkPath(path, opts) { - return path.scope.isPure(path.node, opts); - } -}; - -var Flow = exports.Flow = { - types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], - checkPath: function checkPath(_ref5) { - var node = _ref5.node; - - if (t.isFlow(node)) { - return true; - } else if (t.isImportDeclaration(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else if (t.isExportDeclaration(node)) { - return node.exportKind === "type"; - } else if (t.isImportSpecifier(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else { - return false; - } - } -}; -},{"babel-types":151}],133:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.insertBefore = insertBefore; -exports._containerInsert = _containerInsert; -exports._containerInsertBefore = _containerInsertBefore; -exports._containerInsertAfter = _containerInsertAfter; -exports._maybePopFromStatements = _maybePopFromStatements; -exports.insertAfter = insertAfter; -exports.updateSiblingKeys = updateSiblingKeys; -exports._verifyNodeList = _verifyNodeList; -exports.unshiftContainer = unshiftContainer; -exports.pushContainer = pushContainer; -exports.hoist = hoist; - -var _cache = require("../cache"); - -var _hoister = require("./lib/hoister"); - -var _hoister2 = _interopRequireDefault(_hoister); - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function insertBefore(nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertBefore(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) nodes.push(this.node); - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertBefore(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.push(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); - } - } - - return [this]; -} - -function _containerInsert(from, nodes) { - this.updateSiblingKeys(from, nodes.length); - - var paths = []; - - for (var i = 0; i < nodes.length; i++) { - var to = from + i; - var node = nodes[i]; - this.container.splice(to, 0, node); - - if (this.context) { - var path = this.context.create(this.parent, this.container, to, this.listKey); - - if (this.context.queue) path.pushContext(this.context); - paths.push(path); - } else { - paths.push(_index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: to - })); - } - } - - var contexts = this._getQueueContexts(); - - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _path = _ref; - - _path.setScope(); - _path.debug(function () { - return "Inserted."; - }); - - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var context = _ref2; - - context.maybeQueue(_path, true); - } - } - - return paths; -} - -function _containerInsertBefore(nodes) { - return this._containerInsert(this.key, nodes); -} - -function _containerInsertAfter(nodes) { - return this._containerInsert(this.key + 1, nodes); -} - -function _maybePopFromStatements(nodes) { - var last = nodes[nodes.length - 1]; - var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression); - - if (isIdentifier && !this.isCompletionRecord()) { - nodes.pop(); - } -} - -function insertAfter(nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertAfter(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) { - var temp = this.scope.generateDeclaredUidIdentifier(); - nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); - nodes.push(t.expressionStatement(temp)); - } - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertAfter(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.unshift(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); - } - } - - return [this]; -} - -function updateSiblingKeys(fromIndex, incrementBy) { - if (!this.parent) return; - - var paths = _cache.path.get(this.parent); - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (path.key >= fromIndex) { - path.key += incrementBy; - } - } -} - -function _verifyNodeList(nodes) { - if (!nodes) { - return []; - } - - if (nodes.constructor !== Array) { - nodes = [nodes]; - } - - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - var msg = void 0; - - if (!node) { - msg = "has falsy node"; - } else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") { - msg = "contains a non-object node"; - } else if (!node.type) { - msg = "without a type"; - } else if (node instanceof _index2.default) { - msg = "has a NodePath when it expected a raw object"; - } - - if (msg) { - var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node); - throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type); - } - } - - return nodes; -} - -function unshiftContainer(listKey, nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: this.node[listKey], - listKey: listKey, - key: 0 - }); - - return path.insertBefore(nodes); -} - -function pushContainer(listKey, nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - var container = this.node[listKey]; - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: container, - listKey: listKey, - key: container.length - }); - - return path.replaceWithMultiple(nodes); -} - -function hoist() { - var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scope; - - var hoister = new _hoister2.default(this, scope); - return hoister.run(); -} -},{"../cache":115,"./index":125,"./lib/hoister":130,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/typeof":113,"babel-types":151}],134:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.remove = remove; -exports._callRemovalHooks = _callRemovalHooks; -exports._remove = _remove; -exports._markRemoved = _markRemoved; -exports._assertUnremoved = _assertUnremoved; - -var _removalHooks = require("./lib/removal-hooks"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function remove() { - this._assertUnremoved(); - - this.resync(); - - if (this._callRemovalHooks()) { - this._markRemoved(); - return; - } - - this.shareCommentsWithSiblings(); - this._remove(); - this._markRemoved(); -} - -function _callRemovalHooks() { - for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var fn = _ref; - - if (fn(this, this.parentPath)) return true; - } -} - -function _remove() { - if (Array.isArray(this.container)) { - this.container.splice(this.key, 1); - this.updateSiblingKeys(this.key, -1); - } else { - this._replaceWith(null); - } -} - -function _markRemoved() { - this.shouldSkip = true; - this.removed = true; - this.node = null; -} - -function _assertUnremoved() { - if (this.removed) { - throw this.buildCodeFrameError("NodePath has been removed so is read-only."); - } -} -},{"./lib/removal-hooks":131,"babel-runtime/core-js/get-iterator":95}],135:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.replaceWithMultiple = replaceWithMultiple; -exports.replaceWithSourceString = replaceWithSourceString; -exports.replaceWith = replaceWith; -exports._replaceWith = _replaceWith; -exports.replaceExpressionWithStatements = replaceExpressionWithStatements; -exports.replaceInline = replaceInline; - -var _babelCodeFrame = require("babel-code-frame"); - -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _index3 = require("./index"); - -var _index4 = _interopRequireDefault(_index3); - -var _babylon = require("babylon"); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hoistVariablesVisitor = { - Function: function Function(path) { - path.skip(); - }, - VariableDeclaration: function VariableDeclaration(path) { - if (path.node.kind !== "var") return; - - var bindings = path.getBindingIdentifiers(); - for (var key in bindings) { - path.scope.push({ id: bindings[key] }); - } - - var exprs = []; - - for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var declar = _ref; - - if (declar.init) { - exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init))); - } - } - - path.replaceWithMultiple(exprs); - } -}; - -function replaceWithMultiple(nodes) { - this.resync(); - - nodes = this._verifyNodeList(nodes); - t.inheritLeadingComments(nodes[0], this.node); - t.inheritTrailingComments(nodes[nodes.length - 1], this.node); - this.node = this.container[this.key] = null; - this.insertAfter(nodes); - - if (this.node) { - this.requeue(); - } else { - this.remove(); - } -} - -function replaceWithSourceString(replacement) { - this.resync(); - - try { - replacement = "(" + replacement + ")"; - replacement = (0, _babylon.parse)(replacement); - } catch (err) { - var loc = err.loc; - if (loc) { - err.message += " - make sure this is an expression."; - err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1); - } - throw err; - } - - replacement = replacement.program.body[0].expression; - _index2.default.removeProperties(replacement); - return this.replaceWith(replacement); -} - -function replaceWith(replacement) { - this.resync(); - - if (this.removed) { - throw new Error("You can't replace this node, we've already removed it"); - } - - if (replacement instanceof _index4.default) { - replacement = replacement.node; - } - - if (!replacement) { - throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); - } - - if (this.node === replacement) { - return; - } - - if (this.isProgram() && !t.isProgram(replacement)) { - throw new Error("You can only replace a Program root node with another Program node"); - } - - if (Array.isArray(replacement)) { - throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); - } - - if (typeof replacement === "string") { - throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); - } - - if (this.isNodeType("Statement") && t.isExpression(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) { - replacement = t.expressionStatement(replacement); - } - } - - if (this.isNodeType("Expression") && t.isStatement(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { - return this.replaceExpressionWithStatements([replacement]); - } - } - - var oldNode = this.node; - if (oldNode) { - t.inheritsComments(replacement, oldNode); - t.removeComments(oldNode); - } - - this._replaceWith(replacement); - this.type = replacement.type; - - this.setScope(); - - this.requeue(); -} - -function _replaceWith(node) { - if (!this.container) { - throw new ReferenceError("Container is falsy"); - } - - if (this.inList) { - t.validate(this.parent, this.key, [node]); - } else { - t.validate(this.parent, this.key, node); - } - - this.debug(function () { - return "Replace with " + (node && node.type); - }); - - this.node = this.container[this.key] = node; -} - -function replaceExpressionWithStatements(nodes) { - this.resync(); - - var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); - - if (t.isSequenceExpression(toSequenceExpression)) { - var exprs = toSequenceExpression.expressions; - - if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { - this._maybePopFromStatements(exprs); - } - - if (exprs.length === 1) { - this.replaceWith(exprs[0]); - } else { - this.replaceWith(toSequenceExpression); - } - } else if (toSequenceExpression) { - this.replaceWith(toSequenceExpression); - } else { - var container = t.functionExpression(null, [], t.blockStatement(nodes)); - container.shadow = true; - - this.replaceWith(t.callExpression(container, [])); - this.traverse(hoistVariablesVisitor); - - var completionRecords = this.get("callee").getCompletionRecords(); - for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var path = _ref2; - - if (!path.isExpressionStatement()) continue; - - var loop = path.findParent(function (path) { - return path.isLoop(); - }); - if (loop) { - var uid = loop.getData("expressionReplacementReturnUid"); - - if (!uid) { - var callee = this.get("callee"); - uid = callee.scope.generateDeclaredUidIdentifier("ret"); - callee.get("body").pushContainer("body", t.returnStatement(uid)); - loop.setData("expressionReplacementReturnUid", uid); - } else { - uid = t.identifier(uid.name); - } - - path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression)); - } else { - path.replaceWith(t.returnStatement(path.node.expression)); - } - } - - return this.node; - } -} - -function replaceInline(nodes) { - this.resync(); - - if (Array.isArray(nodes)) { - if (Array.isArray(this.container)) { - nodes = this._verifyNodeList(nodes); - this._containerInsertAfter(nodes); - return this.remove(); - } else { - return this.replaceWithMultiple(nodes); - } - } else { - return this.replaceWith(nodes); - } -} -},{"../index":118,"./index":125,"babel-code-frame":4,"babel-runtime/core-js/get-iterator":95,"babel-types":151,"babylon":155}],136:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Binding = function () { - function Binding(_ref) { - var existing = _ref.existing, - identifier = _ref.identifier, - scope = _ref.scope, - path = _ref.path, - kind = _ref.kind; - (0, _classCallCheck3.default)(this, Binding); - - this.identifier = identifier; - this.scope = scope; - this.path = path; - this.kind = kind; - - this.constantViolations = []; - this.constant = true; - - this.referencePaths = []; - this.referenced = false; - this.references = 0; - - this.clearValue(); - - if (existing) { - this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations); - } - } - - Binding.prototype.deoptValue = function deoptValue() { - this.clearValue(); - this.hasDeoptedValue = true; - }; - - Binding.prototype.setValue = function setValue(value) { - if (this.hasDeoptedValue) return; - this.hasValue = true; - this.value = value; - }; - - Binding.prototype.clearValue = function clearValue() { - this.hasDeoptedValue = false; - this.hasValue = false; - this.value = null; - }; - - Binding.prototype.reassign = function reassign(path) { - this.constant = false; - if (this.constantViolations.indexOf(path) !== -1) { - return; - } - this.constantViolations.push(path); - }; - - Binding.prototype.reference = function reference(path) { - if (this.referencePaths.indexOf(path) !== -1) { - return; - } - this.referenced = true; - this.references++; - this.referencePaths.push(path); - }; - - Binding.prototype.dereference = function dereference() { - this.references--; - this.referenced = !!this.references; - }; - - return Binding; -}(); - -exports.default = Binding; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109}],137:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _repeat = require("lodash/repeat"); - -var _repeat2 = _interopRequireDefault(_repeat); - -var _renamer = require("./lib/renamer"); - -var _renamer2 = _interopRequireDefault(_renamer); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _defaults = require("lodash/defaults"); - -var _defaults2 = _interopRequireDefault(_defaults); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _binding2 = require("./binding"); - -var _binding3 = _interopRequireDefault(_binding2); - -var _globals = require("globals"); - -var _globals2 = _interopRequireDefault(_globals); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("../cache"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _crawlCallsCount = 0; - -function getCache(path, parentScope, self) { - var scopes = _cache.scope.get(path.node) || []; - - for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var scope = _ref; - - if (scope.parent === parentScope && scope.path === path) return scope; - } - - scopes.push(self); - - if (!_cache.scope.has(path.node)) { - _cache.scope.set(path.node, scopes); - } -} - -function gatherNodeParts(node, parts) { - if (t.isModuleDeclaration(node)) { - if (node.source) { - gatherNodeParts(node.source, parts); - } else if (node.specifiers && node.specifiers.length) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var specifier = _ref2; - - gatherNodeParts(specifier, parts); - } - } else if (node.declaration) { - gatherNodeParts(node.declaration, parts); - } - } else if (t.isModuleSpecifier(node)) { - gatherNodeParts(node.local, parts); - } else if (t.isMemberExpression(node)) { - gatherNodeParts(node.object, parts); - gatherNodeParts(node.property, parts); - } else if (t.isIdentifier(node)) { - parts.push(node.name); - } else if (t.isLiteral(node)) { - parts.push(node.value); - } else if (t.isCallExpression(node)) { - gatherNodeParts(node.callee, parts); - } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { - for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var prop = _ref3; - - gatherNodeParts(prop.key || prop.argument, parts); - } - } -} - -var collectorVisitor = { - For: function For(path) { - for (var _iterator4 = t.FOR_INIT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var key = _ref4; - - var declar = path.get(key); - if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); - } - }, - Declaration: function Declaration(path) { - if (path.isBlockScoped()) return; - - if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return; - - path.scope.getFunctionParent().registerDeclaration(path); - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - state.references.push(path); - }, - ForXStatement: function ForXStatement(path, state) { - var left = path.get("left"); - if (left.isPattern() || left.isIdentifier()) { - state.constantViolations.push(left); - } - }, - - - ExportDeclaration: { - exit: function exit(path) { - var node = path.node, - scope = path.scope; - - var declar = node.declaration; - if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { - var _id = declar.id; - if (!_id) return; - - var binding = scope.getBinding(_id.name); - if (binding) binding.reference(path); - } else if (t.isVariableDeclaration(declar)) { - for (var _iterator5 = declar.declarations, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var decl = _ref5; - - var ids = t.getBindingIdentifiers(decl); - for (var name in ids) { - var _binding = scope.getBinding(name); - if (_binding) _binding.reference(path); - } - } - } - } - }, - - LabeledStatement: function LabeledStatement(path) { - path.scope.getProgramParent().addGlobal(path.node); - path.scope.getBlockParent().registerDeclaration(path); - }, - AssignmentExpression: function AssignmentExpression(path, state) { - state.assignments.push(path); - }, - UpdateExpression: function UpdateExpression(path, state) { - state.constantViolations.push(path.get("argument")); - }, - UnaryExpression: function UnaryExpression(path, state) { - if (path.node.operator === "delete") { - state.constantViolations.push(path.get("argument")); - } - }, - BlockScoped: function BlockScoped(path) { - var scope = path.scope; - if (scope.path === path) scope = scope.parent; - scope.getBlockParent().registerDeclaration(path); - }, - ClassDeclaration: function ClassDeclaration(path) { - var id = path.node.id; - if (!id) return; - - var name = id.name; - path.scope.bindings[name] = path.scope.getBinding(name); - }, - Block: function Block(path) { - var paths = path.get("body"); - for (var _iterator6 = paths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } - - var bodyPath = _ref6; - - if (bodyPath.isFunctionDeclaration()) { - path.scope.getBlockParent().registerDeclaration(bodyPath); - } - } - } -}; - -var uid = 0; - -var Scope = function () { - function Scope(path, parentScope) { - (0, _classCallCheck3.default)(this, Scope); - - if (parentScope && parentScope.block === path.node) { - return parentScope; - } - - var cached = getCache(path, parentScope, this); - if (cached) return cached; - - this.uid = uid++; - this.parent = parentScope; - this.hub = path.hub; - - this.parentBlock = path.parent; - this.block = path.node; - this.path = path; - - this.labels = new _map2.default(); - } - - Scope.prototype.traverse = function traverse(node, opts, state) { - (0, _index2.default)(node, opts, this, state, this.path); - }; - - Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - var id = this.generateUidIdentifier(name); - this.push({ id: id }); - return id; - }; - - Scope.prototype.generateUidIdentifier = function generateUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - return t.identifier(this.generateUid(name)); - }; - - Scope.prototype.generateUid = function generateUid() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); - - var uid = void 0; - var i = 0; - do { - uid = this._generateUid(name, i); - i++; - } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); - - var program = this.getProgramParent(); - program.references[uid] = true; - program.uids[uid] = true; - - return uid; - }; - - Scope.prototype._generateUid = function _generateUid(name, i) { - var id = name; - if (i > 1) id += i; - return "_" + id; - }; - - Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) { - var node = parent; - - if (t.isAssignmentExpression(parent)) { - node = parent.left; - } else if (t.isVariableDeclarator(parent)) { - node = parent.id; - } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) { - node = node.key; - } - - var parts = []; - gatherNodeParts(node, parts); - - var id = parts.join("$"); - id = id.replace(/^_/, "") || defaultName || "ref"; - - return this.generateUidIdentifier(id.slice(0, 20)); - }; - - Scope.prototype.isStatic = function isStatic(node) { - if (t.isThisExpression(node) || t.isSuper(node)) { - return true; - } - - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding) { - return binding.constant; - } else { - return this.hasBinding(node.name); - } - } - - return false; - }; - - Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) { - if (this.isStatic(node)) { - return null; - } else { - var _id2 = this.generateUidIdentifierBasedOnNode(node); - if (!dontPush) this.push({ id: _id2 }); - return _id2; - } - }; - - Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) { - if (kind === "param") return; - - if (kind === "hoisted" && local.kind === "let") return; - - var duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); - - if (duplicate) { - throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError); - } - }; - - Scope.prototype.rename = function rename(oldName, newName, block) { - var binding = this.getBinding(oldName); - if (binding) { - newName = newName || this.generateUidIdentifier(oldName).name; - return new _renamer2.default(binding, oldName, newName).rename(block); - } - }; - - Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) { - if (map[oldName]) { - map[newName] = value; - map[oldName] = null; - } - }; - - Scope.prototype.dump = function dump() { - var sep = (0, _repeat2.default)("-", 60); - console.log(sep); - var scope = this; - do { - console.log("#", scope.block.type); - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - console.log(" -", name, { - constant: binding.constant, - references: binding.references, - violations: binding.constantViolations.length, - kind: binding.kind - }); - } - } while (scope = scope.parent); - console.log(sep); - }; - - Scope.prototype.toArray = function toArray(node, i) { - var file = this.hub.file; - - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding && binding.constant && binding.path.isGenericType("Array")) return node; - } - - if (t.isArrayExpression(node)) { - return node; - } - - if (t.isIdentifier(node, { name: "arguments" })) { - return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); - } - - var helperName = "toArray"; - var args = [node]; - if (i === true) { - helperName = "toConsumableArray"; - } else if (i) { - args.push(t.numericLiteral(i)); - helperName = "slicedToArray"; - } - return t.callExpression(file.addHelper(helperName), args); - }; - - Scope.prototype.hasLabel = function hasLabel(name) { - return !!this.getLabel(name); - }; - - Scope.prototype.getLabel = function getLabel(name) { - return this.labels.get(name); - }; - - Scope.prototype.registerLabel = function registerLabel(path) { - this.labels.set(path.node.label.name, path); - }; - - Scope.prototype.registerDeclaration = function registerDeclaration(path) { - if (path.isLabeledStatement()) { - this.registerLabel(path); - } else if (path.isFunctionDeclaration()) { - this.registerBinding("hoisted", path.get("id"), path); - } else if (path.isVariableDeclaration()) { - var declarations = path.get("declarations"); - for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } - - var declar = _ref7; - - this.registerBinding(path.node.kind, declar); - } - } else if (path.isClassDeclaration()) { - this.registerBinding("let", path); - } else if (path.isImportDeclaration()) { - var specifiers = path.get("specifiers"); - for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; - - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } - - var specifier = _ref8; - - this.registerBinding("module", specifier); - } - } else if (path.isExportDeclaration()) { - var _declar = path.get("declaration"); - if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) { - this.registerDeclaration(_declar); - } - } else { - this.registerBinding("unknown", path); - } - }; - - Scope.prototype.buildUndefinedNode = function buildUndefinedNode() { - if (this.hasBinding("undefined")) { - return t.unaryExpression("void", t.numericLiteral(0), true); - } else { - return t.identifier("undefined"); - } - }; - - Scope.prototype.registerConstantViolation = function registerConstantViolation(path) { - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = this.getBinding(name); - if (binding) binding.reassign(path); - } - }; - - Scope.prototype.registerBinding = function registerBinding(kind, path) { - var bindingPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : path; - - if (!kind) throw new ReferenceError("no `kind`"); - - if (path.isVariableDeclaration()) { - var declarators = path.get("declarations"); - for (var _iterator9 = declarators, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; - - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } - - var declar = _ref9; - - this.registerBinding(kind, declar); - } - return; - } - - var parent = this.getProgramParent(); - var ids = path.getBindingIdentifiers(true); - - for (var name in ids) { - for (var _iterator10 = ids[name], _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; - } - - var _id3 = _ref10; - - var local = this.getOwnBinding(name); - if (local) { - if (local.identifier === _id3) continue; - - this.checkBlockScopedCollisions(local, kind, name, _id3); - } - - if (local && local.path.isFlow()) local = null; - - parent.references[name] = true; - - this.bindings[name] = new _binding3.default({ - identifier: _id3, - existing: local, - scope: this, - path: bindingPath, - kind: kind - }); - } - } - }; - - Scope.prototype.addGlobal = function addGlobal(node) { - this.globals[node.name] = node; - }; - - Scope.prototype.hasUid = function hasUid(name) { - var scope = this; - - do { - if (scope.uids[name]) return true; - } while (scope = scope.parent); - - return false; - }; - - Scope.prototype.hasGlobal = function hasGlobal(name) { - var scope = this; - - do { - if (scope.globals[name]) return true; - } while (scope = scope.parent); - - return false; - }; - - Scope.prototype.hasReference = function hasReference(name) { - var scope = this; - - do { - if (scope.references[name]) return true; - } while (scope = scope.parent); - - return false; - }; - - Scope.prototype.isPure = function isPure(node, constantsOnly) { - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (!binding) return false; - if (constantsOnly) return binding.constant; - return true; - } else if (t.isClass(node)) { - if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false; - return this.isPure(node.body, constantsOnly); - } else if (t.isClassBody(node)) { - for (var _iterator11 = node.body, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : (0, _getIterator3.default)(_iterator11);;) { - var _ref11; - - if (_isArray11) { - if (_i11 >= _iterator11.length) break; - _ref11 = _iterator11[_i11++]; - } else { - _i11 = _iterator11.next(); - if (_i11.done) break; - _ref11 = _i11.value; - } - - var method = _ref11; - - if (!this.isPure(method, constantsOnly)) return false; - } - return true; - } else if (t.isBinary(node)) { - return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); - } else if (t.isArrayExpression(node)) { - for (var _iterator12 = node.elements, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : (0, _getIterator3.default)(_iterator12);;) { - var _ref12; - - if (_isArray12) { - if (_i12 >= _iterator12.length) break; - _ref12 = _iterator12[_i12++]; - } else { - _i12 = _iterator12.next(); - if (_i12.done) break; - _ref12 = _i12.value; - } - - var elem = _ref12; - - if (!this.isPure(elem, constantsOnly)) return false; - } - return true; - } else if (t.isObjectExpression(node)) { - for (var _iterator13 = node.properties, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : (0, _getIterator3.default)(_iterator13);;) { - var _ref13; - - if (_isArray13) { - if (_i13 >= _iterator13.length) break; - _ref13 = _iterator13[_i13++]; - } else { - _i13 = _iterator13.next(); - if (_i13.done) break; - _ref13 = _i13.value; - } - - var prop = _ref13; - - if (!this.isPure(prop, constantsOnly)) return false; - } - return true; - } else if (t.isClassMethod(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - if (node.kind === "get" || node.kind === "set") return false; - return true; - } else if (t.isClassProperty(node) || t.isObjectProperty(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - return this.isPure(node.value, constantsOnly); - } else if (t.isUnaryExpression(node)) { - return this.isPure(node.argument, constantsOnly); - } else { - return t.isPureish(node); - } - }; - - Scope.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; - - Scope.prototype.getData = function getData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) return data; - } while (scope = scope.parent); - }; - - Scope.prototype.removeData = function removeData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) scope.data[key] = null; - } while (scope = scope.parent); - }; - - Scope.prototype.init = function init() { - if (!this.references) this.crawl(); - }; - - Scope.prototype.crawl = function crawl() { - _crawlCallsCount++; - this._crawl(); - _crawlCallsCount--; - }; - - Scope.prototype._crawl = function _crawl() { - var path = this.path; - - this.references = (0, _create2.default)(null); - this.bindings = (0, _create2.default)(null); - this.globals = (0, _create2.default)(null); - this.uids = (0, _create2.default)(null); - this.data = (0, _create2.default)(null); - - if (path.isLoop()) { - for (var _iterator14 = t.FOR_INIT_KEYS, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : (0, _getIterator3.default)(_iterator14);;) { - var _ref14; - - if (_isArray14) { - if (_i14 >= _iterator14.length) break; - _ref14 = _iterator14[_i14++]; - } else { - _i14 = _iterator14.next(); - if (_i14.done) break; - _ref14 = _i14.value; - } - - var key = _ref14; - - var node = path.get(key); - if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); - } - } - - if (path.isFunctionExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path.get("id"), path); - } - } - - if (path.isClassExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path); - } - } - - if (path.isFunction()) { - var params = path.get("params"); - for (var _iterator15 = params, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : (0, _getIterator3.default)(_iterator15);;) { - var _ref15; - - if (_isArray15) { - if (_i15 >= _iterator15.length) break; - _ref15 = _iterator15[_i15++]; - } else { - _i15 = _iterator15.next(); - if (_i15.done) break; - _ref15 = _i15.value; - } - - var param = _ref15; - - this.registerBinding("param", param); - } - } - - if (path.isCatchClause()) { - this.registerBinding("let", path); - } - - var parent = this.getProgramParent(); - if (parent.crawling) return; - - var state = { - references: [], - constantViolations: [], - assignments: [] - }; - - this.crawling = true; - path.traverse(collectorVisitor, state); - this.crawling = false; - - for (var _iterator16 = state.assignments, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : (0, _getIterator3.default)(_iterator16);;) { - var _ref16; - - if (_isArray16) { - if (_i16 >= _iterator16.length) break; - _ref16 = _iterator16[_i16++]; - } else { - _i16 = _iterator16.next(); - if (_i16.done) break; - _ref16 = _i16.value; - } - - var _path = _ref16; - - var ids = _path.getBindingIdentifiers(); - var programParent = void 0; - for (var name in ids) { - if (_path.scope.getBinding(name)) continue; - - programParent = programParent || _path.scope.getProgramParent(); - programParent.addGlobal(ids[name]); - } - - _path.scope.registerConstantViolation(_path); - } - - for (var _iterator17 = state.references, _isArray17 = Array.isArray(_iterator17), _i17 = 0, _iterator17 = _isArray17 ? _iterator17 : (0, _getIterator3.default)(_iterator17);;) { - var _ref17; - - if (_isArray17) { - if (_i17 >= _iterator17.length) break; - _ref17 = _iterator17[_i17++]; - } else { - _i17 = _iterator17.next(); - if (_i17.done) break; - _ref17 = _i17.value; - } - - var ref = _ref17; - - var binding = ref.scope.getBinding(ref.node.name); - if (binding) { - binding.reference(ref); - } else { - ref.scope.getProgramParent().addGlobal(ref.node); - } - } - - for (var _iterator18 = state.constantViolations, _isArray18 = Array.isArray(_iterator18), _i18 = 0, _iterator18 = _isArray18 ? _iterator18 : (0, _getIterator3.default)(_iterator18);;) { - var _ref18; - - if (_isArray18) { - if (_i18 >= _iterator18.length) break; - _ref18 = _iterator18[_i18++]; - } else { - _i18 = _iterator18.next(); - if (_i18.done) break; - _ref18 = _i18.value; - } - - var _path2 = _ref18; - - _path2.scope.registerConstantViolation(_path2); - } - }; - - Scope.prototype.push = function push(opts) { - var path = this.path; - - if (!path.isBlockStatement() && !path.isProgram()) { - path = this.getBlockParent().path; - } - - if (path.isSwitchStatement()) { - path = this.getFunctionParent().path; - } - - if (path.isLoop() || path.isCatchClause() || path.isFunction()) { - t.ensureBlock(path.node); - path = path.get("body"); - } - - var unique = opts.unique; - var kind = opts.kind || "var"; - var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; - - var dataKey = "declaration:" + kind + ":" + blockHoist; - var declarPath = !unique && path.getData(dataKey); - - if (!declarPath) { - var declar = t.variableDeclaration(kind, []); - declar._generated = true; - declar._blockHoist = blockHoist; - - var _path$unshiftContaine = path.unshiftContainer("body", [declar]); - - declarPath = _path$unshiftContaine[0]; - - if (!unique) path.setData(dataKey, declarPath); - } - - var declarator = t.variableDeclarator(opts.id, opts.init); - declarPath.node.declarations.push(declarator); - this.registerBinding(kind, declarPath.get("declarations").pop()); - }; - - Scope.prototype.getProgramParent = function getProgramParent() { - var scope = this; - do { - if (scope.path.isProgram()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; - - Scope.prototype.getFunctionParent = function getFunctionParent() { - var scope = this; - do { - if (scope.path.isFunctionParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; - - Scope.prototype.getBlockParent = function getBlockParent() { - var scope = this; - do { - if (scope.path.isBlockParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); - }; - - Scope.prototype.getAllBindings = function getAllBindings() { - var ids = (0, _create2.default)(null); - - var scope = this; - do { - (0, _defaults2.default)(ids, scope.bindings); - scope = scope.parent; - } while (scope); - - return ids; - }; - - Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind() { - var ids = (0, _create2.default)(null); - - for (var _iterator19 = arguments, _isArray19 = Array.isArray(_iterator19), _i19 = 0, _iterator19 = _isArray19 ? _iterator19 : (0, _getIterator3.default)(_iterator19);;) { - var _ref19; - - if (_isArray19) { - if (_i19 >= _iterator19.length) break; - _ref19 = _iterator19[_i19++]; - } else { - _i19 = _iterator19.next(); - if (_i19.done) break; - _ref19 = _i19.value; - } - - var kind = _ref19; - - var scope = this; - do { - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - if (binding.kind === kind) ids[name] = binding; - } - scope = scope.parent; - } while (scope); - } - - return ids; - }; - - Scope.prototype.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) { - return this.getBindingIdentifier(name) === node; - }; - - Scope.prototype.warnOnFlowBinding = function warnOnFlowBinding(binding) { - if (_crawlCallsCount === 0 && binding && binding.path.isFlow()) { - console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 7. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "); - } - return binding; - }; - - Scope.prototype.getBinding = function getBinding(name) { - var scope = this; - - do { - var binding = scope.getOwnBinding(name); - if (binding) return this.warnOnFlowBinding(binding); - } while (scope = scope.parent); - }; - - Scope.prototype.getOwnBinding = function getOwnBinding(name) { - return this.warnOnFlowBinding(this.bindings[name]); - }; - - Scope.prototype.getBindingIdentifier = function getBindingIdentifier(name) { - var info = this.getBinding(name); - return info && info.identifier; - }; - - Scope.prototype.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) { - var binding = this.bindings[name]; - return binding && binding.identifier; - }; - - Scope.prototype.hasOwnBinding = function hasOwnBinding(name) { - return !!this.getOwnBinding(name); - }; - - Scope.prototype.hasBinding = function hasBinding(name, noGlobals) { - if (!name) return false; - if (this.hasOwnBinding(name)) return true; - if (this.parentHasBinding(name, noGlobals)) return true; - if (this.hasUid(name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.globals, name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.contextVariables, name)) return true; - return false; - }; - - Scope.prototype.parentHasBinding = function parentHasBinding(name, noGlobals) { - return this.parent && this.parent.hasBinding(name, noGlobals); - }; - - Scope.prototype.moveBindingTo = function moveBindingTo(name, scope) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - info.scope = scope; - scope.bindings[name] = info; - } - }; - - Scope.prototype.removeOwnBinding = function removeOwnBinding(name) { - delete this.bindings[name]; - }; - - Scope.prototype.removeBinding = function removeBinding(name) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - } - - var scope = this; - do { - if (scope.uids[name]) { - scope.uids[name] = false; - } - } while (scope = scope.parent); - }; - - return Scope; -}(); - -Scope.globals = (0, _keys2.default)(_globals2.default.builtin); -Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; -exports.default = Scope; -module.exports = exports["default"]; -},{"../cache":115,"../index":118,"./binding":136,"./lib/renamer":138,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/map":97,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/classCallCheck":109,"babel-types":151,"globals":289,"lodash/defaults":470,"lodash/includes":482,"lodash/repeat":507}],138:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _binding = require("../binding"); - -var _binding2 = _interopRequireDefault(_binding); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var renameVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { - var node = _ref.node; - - if (node.name === state.oldName) { - node.name = state.newName; - } - }, - Scope: function Scope(path, state) { - if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { - path.skip(); - } - }, - "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { - var ids = path.getOuterBindingIdentifiers(); - - for (var name in ids) { - if (name === state.oldName) ids[name].name = state.newName; - } - } -}; - -var Renamer = function () { - function Renamer(binding, oldName, newName) { - (0, _classCallCheck3.default)(this, Renamer); - - this.newName = newName; - this.oldName = oldName; - this.binding = binding; - } - - Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { - var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; - if (!exportDeclar) return; - - var isDefault = exportDeclar.isExportDefaultDeclaration(); - - if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { - parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); - } - - var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); - var specifiers = []; - - for (var name in bindingIdentifiers) { - var localName = name === this.oldName ? this.newName : name; - var exportedName = isDefault ? "default" : name; - specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); - } - - if (specifiers.length) { - var aliasDeclar = t.exportNamedDeclaration(null, specifiers); - - if (parentDeclar.isFunctionDeclaration()) { - aliasDeclar._blockHoist = 3; - } - - exportDeclar.insertAfter(aliasDeclar); - exportDeclar.replaceWith(parentDeclar.node); - } - }; - - Renamer.prototype.rename = function rename(block) { - var binding = this.binding, - oldName = this.oldName, - newName = this.newName; - var scope = binding.scope, - path = binding.path; - - - var parentDeclar = path.find(function (path) { - return path.isDeclaration() || path.isFunctionExpression(); - }); - if (parentDeclar) { - this.maybeConvertFromExportDeclaration(parentDeclar); - } - - scope.traverse(block || scope.block, renameVisitor, this); - - if (!block) { - scope.removeOwnBinding(oldName); - scope.bindings[newName] = binding; - this.binding.identifier.name = newName; - } - - if (binding.type === "hoisted") {} - }; - - return Renamer; -}(); - -exports.default = Renamer; -module.exports = exports["default"]; -},{"../binding":136,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],139:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.explode = explode; -exports.verify = verify; -exports.merge = merge; - -var _virtualTypes = require("./path/lib/virtual-types"); - -var virtualTypes = _interopRequireWildcard(_virtualTypes); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function explode(visitor) { - if (visitor._exploded) return visitor; - visitor._exploded = true; - - for (var nodeType in visitor) { - if (shouldIgnoreKey(nodeType)) continue; - - var parts = nodeType.split("|"); - if (parts.length === 1) continue; - - var fns = visitor[nodeType]; - delete visitor[nodeType]; - - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var part = _ref; - - visitor[part] = fns; - } - } - - verify(visitor); - - delete visitor.__esModule; - - ensureEntranceObjects(visitor); - - ensureCallbackArrays(visitor); - - for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _nodeType3 = _ref2; - - if (shouldIgnoreKey(_nodeType3)) continue; - - var wrapper = virtualTypes[_nodeType3]; - if (!wrapper) continue; - - var _fns2 = visitor[_nodeType3]; - for (var type in _fns2) { - _fns2[type] = wrapCheck(wrapper, _fns2[type]); - } - - delete visitor[_nodeType3]; - - if (wrapper.types) { - for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var _type = _ref4; - - if (visitor[_type]) { - mergePair(visitor[_type], _fns2); - } else { - visitor[_type] = _fns2; - } - } - } else { - mergePair(visitor, _fns2); - } - } - - for (var _nodeType in visitor) { - if (shouldIgnoreKey(_nodeType)) continue; - - var _fns = visitor[_nodeType]; - - var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; - - var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; - if (deprecratedKey) { - console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); - aliases = [deprecratedKey]; - } - - if (!aliases) continue; - - delete visitor[_nodeType]; - - for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var alias = _ref3; - - var existing = visitor[alias]; - if (existing) { - mergePair(existing, _fns); - } else { - visitor[alias] = (0, _clone2.default)(_fns); - } - } - } - - for (var _nodeType2 in visitor) { - if (shouldIgnoreKey(_nodeType2)) continue; - - ensureCallbackArrays(visitor[_nodeType2]); - } - - return visitor; -} - -function verify(visitor) { - if (visitor._verified) return; - - if (typeof visitor === "function") { - throw new Error(messages.get("traverseVerifyRootFunction")); - } - - for (var nodeType in visitor) { - if (nodeType === "enter" || nodeType === "exit") { - validateVisitorMethods(nodeType, visitor[nodeType]); - } - - if (shouldIgnoreKey(nodeType)) continue; - - if (t.TYPES.indexOf(nodeType) < 0) { - throw new Error(messages.get("traverseVerifyNodeType", nodeType)); - } - - var visitors = visitor[nodeType]; - if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { - for (var visitorKey in visitors) { - if (visitorKey === "enter" || visitorKey === "exit") { - validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); - } else { - throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); - } - } - } - } - - visitor._verified = true; -} - -function validateVisitorMethods(path, val) { - var fns = [].concat(val); - for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var fn = _ref5; - - if (typeof fn !== "function") { - throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); - } - } -} - -function merge(visitors) { - var states = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var wrapper = arguments[2]; - - var rootVisitor = {}; - - for (var i = 0; i < visitors.length; i++) { - var visitor = visitors[i]; - var state = states[i]; - - explode(visitor); - - for (var type in visitor) { - var visitorType = visitor[type]; - - if (state || wrapper) { - visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); - } - - var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; - mergePair(nodeVisitor, visitorType); - } - } - - return rootVisitor; -} - -function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { - var newVisitor = {}; - - var _loop = function _loop(key) { - var fns = oldVisitor[key]; - - if (!Array.isArray(fns)) return "continue"; - - fns = fns.map(function (fn) { - var newFn = fn; - - if (state) { - newFn = function newFn(path) { - return fn.call(state, path, state); - }; - } - - if (wrapper) { - newFn = wrapper(state.key, key, newFn); - } - - return newFn; - }); - - newVisitor[key] = fns; - }; - - for (var key in oldVisitor) { - var _ret = _loop(key); - - if (_ret === "continue") continue; - } - - return newVisitor; -} - -function ensureEntranceObjects(obj) { - for (var key in obj) { - if (shouldIgnoreKey(key)) continue; - - var fns = obj[key]; - if (typeof fns === "function") { - obj[key] = { enter: fns }; - } - } -} - -function ensureCallbackArrays(obj) { - if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; - if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; -} - -function wrapCheck(wrapper, fn) { - var newFn = function newFn(path) { - if (wrapper.checkPath(path)) { - return fn.apply(this, arguments); - } - }; - newFn.toString = function () { - return fn.toString(); - }; - return newFn; -} - -function shouldIgnoreKey(key) { - if (key[0] === "_") return true; - - if (key === "enter" || key === "exit" || key === "shouldSkip") return true; - - if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; - - return false; -} - -function mergePair(dest, src) { - for (var key in src) { - dest[key] = [].concat(dest[key] || [], src[key]); - } -} -},{"./path/lib/virtual-types":132,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/typeof":113,"babel-types":151,"lodash/clone":466}],140:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; - -var _for = require("babel-runtime/core-js/symbol/for"); - -var _for2 = _interopRequireDefault(_for); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var STATEMENT_OR_BLOCK_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; -var FLATTENABLE_KEYS = exports.FLATTENABLE_KEYS = ["body", "expressions"]; -var FOR_INIT_KEYS = exports.FOR_INIT_KEYS = ["left", "init"]; -var COMMENT_KEYS = exports.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; - -var LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = ["||", "&&"]; -var UPDATE_OPERATORS = exports.UPDATE_OPERATORS = ["++", "--"]; - -var BOOLEAN_NUMBER_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; -var EQUALITY_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; -var COMPARISON_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = [].concat(EQUALITY_BINARY_OPERATORS, ["in", "instanceof"]); -var BOOLEAN_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); -var NUMBER_BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; -var BINARY_OPERATORS = exports.BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS); - -var BOOLEAN_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; -var NUMBER_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; -var STRING_UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = ["typeof"]; -var UNARY_OPERATORS = exports.UNARY_OPERATORS = ["void"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS); - -var INHERIT_KEYS = exports.INHERIT_KEYS = { - optional: ["typeAnnotation", "typeParameters", "returnType"], - force: ["start", "loc", "end"] -}; - -var BLOCK_SCOPED_SYMBOL = exports.BLOCK_SCOPED_SYMBOL = (0, _for2.default)("var used to be block scoped"); -var NOT_LOCAL_BINDING = exports.NOT_LOCAL_BINDING = (0, _for2.default)("should not be considered a local binding"); -},{"babel-runtime/core-js/symbol/for":105}],141:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _maxSafeInteger = require("babel-runtime/core-js/number/max-safe-integer"); - -var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.toComputedKey = toComputedKey; -exports.toSequenceExpression = toSequenceExpression; -exports.toKeyAlias = toKeyAlias; -exports.toIdentifier = toIdentifier; -exports.toBindingIdentifierName = toBindingIdentifierName; -exports.toStatement = toStatement; -exports.toExpression = toExpression; -exports.toBlock = toBlock; -exports.valueToNode = valueToNode; - -var _isPlainObject = require("lodash/isPlainObject"); - -var _isPlainObject2 = _interopRequireDefault(_isPlainObject); - -var _isRegExp = require("lodash/isRegExp"); - -var _isRegExp2 = _interopRequireDefault(_isRegExp); - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toComputedKey(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key || node.property; - - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } - return key; -} - -function gatherSequenceExpressions(nodes, scope, declars) { - var exprs = []; - var ensureLastUndefined = true; - - for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var node = _ref; - - ensureLastUndefined = false; - - if (t.isExpression(node)) { - exprs.push(node); - } else if (t.isExpressionStatement(node)) { - exprs.push(node.expression); - } else if (t.isVariableDeclaration(node)) { - if (node.kind !== "var") return; - - for (var _iterator2 = node.declarations, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var declar = _ref2; - - var bindings = t.getBindingIdentifiers(declar); - for (var key in bindings) { - declars.push({ - kind: node.kind, - id: bindings[key] - }); - } - - if (declar.init) { - exprs.push(t.assignmentExpression("=", declar.id, declar.init)); - } - } - - ensureLastUndefined = true; - } else if (t.isIfStatement(node)) { - var consequent = node.consequent ? gatherSequenceExpressions([node.consequent], scope, declars) : scope.buildUndefinedNode(); - var alternate = node.alternate ? gatherSequenceExpressions([node.alternate], scope, declars) : scope.buildUndefinedNode(); - if (!consequent || !alternate) return; - - exprs.push(t.conditionalExpression(node.test, consequent, alternate)); - } else if (t.isBlockStatement(node)) { - var body = gatherSequenceExpressions(node.body, scope, declars); - if (!body) return; - - exprs.push(body); - } else if (t.isEmptyStatement(node)) { - ensureLastUndefined = true; - } else { - return; - } - } - - if (ensureLastUndefined) { - exprs.push(scope.buildUndefinedNode()); - } - - if (exprs.length === 1) { - return exprs[0]; - } else { - return t.sequenceExpression(exprs); - } -} - -function toSequenceExpression(nodes, scope) { - if (!nodes || !nodes.length) return; - - var declars = []; - var result = gatherSequenceExpressions(nodes, scope, declars); - if (!result) return; - - for (var _iterator3 = declars, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var declar = _ref3; - - scope.push(declar); - } - - return result; -} - -function toKeyAlias(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key; - - var alias = void 0; - - if (node.kind === "method") { - return toKeyAlias.increment() + ""; - } else if (t.isIdentifier(key)) { - alias = key.name; - } else if (t.isStringLiteral(key)) { - alias = (0, _stringify2.default)(key.value); - } else { - alias = (0, _stringify2.default)(t.removePropertiesDeep(t.cloneDeep(key))); - } - - if (node.computed) { - alias = "[" + alias + "]"; - } - - if (node.static) { - alias = "static:" + alias; - } - - return alias; -} - -toKeyAlias.uid = 0; - -toKeyAlias.increment = function () { - if (toKeyAlias.uid >= _maxSafeInteger2.default) { - return toKeyAlias.uid = 0; - } else { - return toKeyAlias.uid++; - } -}; - -function toIdentifier(name) { - name = name + ""; - - name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); - - name = name.replace(/^[-0-9]+/, ""); - - name = name.replace(/[-\s]+(.)?/g, function (match, c) { - return c ? c.toUpperCase() : ""; - }); - - if (!t.isValidIdentifier(name)) { - name = "_" + name; - } - - return name || "_"; -} - -function toBindingIdentifierName(name) { - name = toIdentifier(name); - if (name === "eval" || name === "arguments") name = "_" + name; - return name; -} - -function toStatement(node, ignore) { - if (t.isStatement(node)) { - return node; - } - - var mustHaveId = false; - var newType = void 0; - - if (t.isClass(node)) { - mustHaveId = true; - newType = "ClassDeclaration"; - } else if (t.isFunction(node)) { - mustHaveId = true; - newType = "FunctionDeclaration"; - } else if (t.isAssignmentExpression(node)) { - return t.expressionStatement(node); - } - - if (mustHaveId && !node.id) { - newType = false; - } - - if (!newType) { - if (ignore) { - return false; - } else { - throw new Error("cannot turn " + node.type + " to a statement"); - } - } - - node.type = newType; - - return node; -} - -function toExpression(node) { - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - if (t.isExpression(node)) { - return node; - } - - if (t.isClass(node)) { - node.type = "ClassExpression"; - } else if (t.isFunction(node)) { - node.type = "FunctionExpression"; - } - - if (!t.isExpression(node)) { - throw new Error("cannot turn " + node.type + " to an expression"); - } - - return node; -} - -function toBlock(node, parent) { - if (t.isBlockStatement(node)) { - return node; - } - - if (t.isEmptyStatement(node)) { - node = []; - } - - if (!Array.isArray(node)) { - if (!t.isStatement(node)) { - if (t.isFunction(parent)) { - node = t.returnStatement(node); - } else { - node = t.expressionStatement(node); - } - } - - node = [node]; - } - - return t.blockStatement(node); -} - -function valueToNode(value) { - if (value === undefined) { - return t.identifier("undefined"); - } - - if (value === true || value === false) { - return t.booleanLiteral(value); - } - - if (value === null) { - return t.nullLiteral(); - } - - if (typeof value === "string") { - return t.stringLiteral(value); - } - - if (typeof value === "number") { - return t.numericLiteral(value); - } - - if ((0, _isRegExp2.default)(value)) { - var pattern = value.source; - var flags = value.toString().match(/\/([a-z]+|)$/)[1]; - return t.regExpLiteral(pattern, flags); - } - - if (Array.isArray(value)) { - return t.arrayExpression(value.map(t.valueToNode)); - } - - if ((0, _isPlainObject2.default)(value)) { - var props = []; - for (var key in value) { - var nodeKey = void 0; - if (t.isValidIdentifier(key)) { - nodeKey = t.identifier(key); - } else { - nodeKey = t.stringLiteral(key); - } - props.push(t.objectProperty(nodeKey, t.valueToNode(value[key]))); - } - return t.objectExpression(props); - } - - throw new Error("don't know how to turn this value into a node"); -} -},{"./index":151,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/number/max-safe-integer":98,"lodash/isPlainObject":493,"lodash/isRegExp":494}],142:[function(require,module,exports){ -"use strict"; - -var _index = require("../index"); - -var t = _interopRequireWildcard(_index); - -var _constants = require("../constants"); - -var _index2 = require("./index"); - -var _index3 = _interopRequireDefault(_index2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -(0, _index3.default)("ArrayExpression", { - fields: { - elements: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), - default: [] - } - }, - visitor: ["elements"], - aliases: ["Expression"] -}); - -(0, _index3.default)("AssignmentExpression", { - fields: { - operator: { - validate: (0, _index2.assertValueType)("string") - }, - left: { - validate: (0, _index2.assertNodeType)("LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Expression"] -}); - -(0, _index3.default)("BinaryExpression", { - builder: ["operator", "left", "right"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.BINARY_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - visitor: ["left", "right"], - aliases: ["Binary", "Expression"] -}); - -(0, _index3.default)("Directive", { - visitor: ["value"], - fields: { - value: { - validate: (0, _index2.assertNodeType)("DirectiveLiteral") - } - } -}); - -(0, _index3.default)("DirectiveLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } - } -}); - -(0, _index3.default)("BlockStatement", { - builder: ["body", "directives"], - visitor: ["directives", "body"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "Statement"] -}); - -(0, _index3.default)("BreakStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); - -(0, _index3.default)("CallExpression", { - visitor: ["callee", "arguments"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) - } - }, - aliases: ["Expression"] -}); - -(0, _index3.default)("CatchClause", { - visitor: ["param", "body"], - fields: { - param: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - } - }, - aliases: ["Scopable"] -}); - -(0, _index3.default)("ConditionalExpression", { - visitor: ["test", "consequent", "alternate"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Expression") - }, - alternate: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Expression", "Conditional"] -}); - -(0, _index3.default)("ContinueStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); - -(0, _index3.default)("DebuggerStatement", { - aliases: ["Statement"] -}); - -(0, _index3.default)("DoWhileStatement", { - visitor: ["test", "body"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - }, - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] -}); - -(0, _index3.default)("EmptyStatement", { - aliases: ["Statement"] -}); - -(0, _index3.default)("ExpressionStatement", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Statement", "ExpressionWrapper"] -}); - -(0, _index3.default)("File", { - builder: ["program", "comments", "tokens"], - visitor: ["program"], - fields: { - program: { - validate: (0, _index2.assertNodeType)("Program") - } - } -}); - -(0, _index3.default)("ForInStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("ForStatement", { - visitor: ["init", "test", "update", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], - fields: { - init: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "Expression"), - optional: true - }, - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - update: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("FunctionDeclaration", { - builder: ["id", "params", "body", "generator", "async"], - visitor: ["id", "params", "body", "returnType", "typeParameters"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] -}); - -(0, _index3.default)("FunctionExpression", { - inherits: "FunctionDeclaration", - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - } -}); - -(0, _index3.default)("Identifier", { - builder: ["name"], - visitor: ["typeAnnotation"], - aliases: ["Expression", "LVal"], - fields: { - name: { - validate: function validate(node, key, val) { - if (!t.isValidIdentifier(val)) {} - } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index3.default)("IfStatement", { - visitor: ["test", "consequent", "alternate"], - aliases: ["Statement", "Conditional"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Statement") - }, - alternate: { - optional: true, - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("LabeledStatement", { - visitor: ["label", "body"], - aliases: ["Statement"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("StringLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("NumericLiteral", { - builder: ["value"], - deprecatedAlias: "NumberLiteral", - fields: { - value: { - validate: (0, _index2.assertValueType)("number") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("NullLiteral", { - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("BooleanLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("RegExpLiteral", { - builder: ["pattern", "flags"], - deprecatedAlias: "RegexLiteral", - aliases: ["Expression", "Literal"], - fields: { - pattern: { - validate: (0, _index2.assertValueType)("string") - }, - flags: { - validate: (0, _index2.assertValueType)("string"), - default: "" - } - } -}); - -(0, _index3.default)("LogicalExpression", { - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Binary", "Expression"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.LOGICAL_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); - -(0, _index3.default)("MemberExpression", { - builder: ["object", "property", "computed"], - visitor: ["object", "property"], - aliases: ["Expression", "LVal"], - fields: { - object: { - validate: (0, _index2.assertNodeType)("Expression") - }, - property: { - validate: function validate(node, key, val) { - var expectedType = node.computed ? "Expression" : "Identifier"; - (0, _index2.assertNodeType)(expectedType)(node, key, val); - } - }, - computed: { - default: false - } - } -}); - -(0, _index3.default)("NewExpression", { - visitor: ["callee", "arguments"], - aliases: ["Expression"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) - } - } -}); - -(0, _index3.default)("Program", { - visitor: ["directives", "body"], - builder: ["body", "directives"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "FunctionParent"] -}); - -(0, _index3.default)("ObjectExpression", { - visitor: ["properties"], - aliases: ["Expression"], - fields: { - properties: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadProperty"))) - } - } -}); - -(0, _index3.default)("ObjectMethod", { - builder: ["kind", "key", "params", "body", "computed"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("method", "get", "set")), - default: "method" - }, - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] -}); - -(0, _index3.default)("ObjectProperty", { - builder: ["key", "value", "computed", "shorthand", "decorators"], - fields: { - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - value: { - validate: (0, _index2.assertNodeType)("Expression", "Pattern", "RestElement") - }, - shorthand: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))), - optional: true - } - }, - visitor: ["key", "value", "decorators"], - aliases: ["UserWhitespacable", "Property", "ObjectMember"] -}); - -(0, _index3.default)("RestElement", { - visitor: ["argument", "typeAnnotation"], - aliases: ["LVal"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("LVal") - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index3.default)("ReturnStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - } - } -}); - -(0, _index3.default)("SequenceExpression", { - visitor: ["expressions"], - fields: { - expressions: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression"))) - } - }, - aliases: ["Expression"] -}); - -(0, _index3.default)("SwitchCase", { - visitor: ["test", "consequent"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - consequent: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - } -}); - -(0, _index3.default)("SwitchStatement", { - visitor: ["discriminant", "cases"], - aliases: ["Statement", "BlockParent", "Scopable"], - fields: { - discriminant: { - validate: (0, _index2.assertNodeType)("Expression") - }, - cases: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("SwitchCase"))) - } - } -}); - -(0, _index3.default)("ThisExpression", { - aliases: ["Expression"] -}); - -(0, _index3.default)("ThrowStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); - -(0, _index3.default)("TryStatement", { - visitor: ["block", "handler", "finalizer"], - aliases: ["Statement"], - fields: { - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - handler: { - optional: true, - handler: (0, _index2.assertNodeType)("BlockStatement") - }, - finalizer: { - optional: true, - validate: (0, _index2.assertNodeType)("BlockStatement") - } - } -}); - -(0, _index3.default)("UnaryExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: true - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UNARY_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["UnaryLike", "Expression"] -}); - -(0, _index3.default)("UpdateExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: false - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UPDATE_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["Expression"] -}); - -(0, _index3.default)("VariableDeclaration", { - builder: ["kind", "declarations"], - visitor: ["declarations"], - aliases: ["Statement", "Declaration"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("var", "let", "const")) - }, - declarations: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("VariableDeclarator"))) - } - } -}); - -(0, _index3.default)("VariableDeclarator", { - visitor: ["id", "init"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("LVal") - }, - init: { - optional: true, - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); - -(0, _index3.default)("WhileStatement", { - visitor: ["test", "body"], - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } - } -}); - -(0, _index3.default)("WithStatement", { - visitor: ["object", "body"], - aliases: ["Statement"], - fields: { - object: { - object: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } - } -}); -},{"../constants":140,"../index":151,"./index":146}],143:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("AssignmentPattern", { - visitor: ["left", "right"], - aliases: ["Pattern", "LVal"], - fields: { - left: { - validate: (0, _index.assertNodeType)("Identifier") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ArrayPattern", { - visitor: ["elements", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - elements: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Identifier", "Pattern", "RestElement"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ArrowFunctionExpression", { - builder: ["params", "body", "async"], - visitor: ["params", "body", "returnType", "typeParameters"], - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement", "Expression") - }, - async: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); - -(0, _index2.default)("ClassBody", { - visitor: ["body"], - fields: { - body: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ClassMethod", "ClassProperty"))) - } - } -}); - -(0, _index2.default)("ClassDeclaration", { - builder: ["id", "superClass", "body", "decorators"], - visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], - aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], - fields: { - id: { - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ClassExpression", { - inherits: "ClassDeclaration", - aliases: ["Scopable", "Class", "Expression", "Pureish"], - fields: { - id: { - optional: true, - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ExportAllDeclaration", { - visitor: ["source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); - -(0, _index2.default)("ExportDefaultDeclaration", { - visitor: ["declaration"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("FunctionDeclaration", "ClassDeclaration", "Expression") - } - } -}); - -(0, _index2.default)("ExportNamedDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("Declaration"), - optional: true - }, - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ExportSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral"), - optional: true - } - } -}); - -(0, _index2.default)("ExportSpecifier", { - visitor: ["local", "exported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ForOfStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); - -(0, _index2.default)("ImportDeclaration", { - visitor: ["specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration"], - fields: { - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); - -(0, _index2.default)("ImportDefaultSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ImportNamespaceSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ImportSpecifier", { - visitor: ["local", "imported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - imported: { - validate: (0, _index.assertNodeType)("Identifier") - }, - importKind: { - validate: (0, _index.assertOneOf)(null, "type", "typeof") - } - } -}); - -(0, _index2.default)("MetaProperty", { - visitor: ["meta", "property"], - aliases: ["Expression"], - fields: { - meta: { - validate: (0, _index.assertValueType)("string") - }, - property: { - validate: (0, _index.assertValueType)("string") - } - } -}); - -(0, _index2.default)("ClassMethod", { - aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], - builder: ["kind", "key", "params", "body", "computed", "static"], - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - fields: { - kind: { - validate: (0, _index.chain)((0, _index.assertValueType)("string"), (0, _index.assertOneOf)("get", "set", "method", "constructor")), - default: "method" - }, - computed: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - static: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index.assertValueType)("boolean") - } - } -}); - -(0, _index2.default)("ObjectPattern", { - visitor: ["properties", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - properties: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("RestProperty", "Property"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("SpreadElement", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("Super", { - aliases: ["Expression"] -}); - -(0, _index2.default)("TaggedTemplateExpression", { - visitor: ["tag", "quasi"], - aliases: ["Expression"], - fields: { - tag: { - validate: (0, _index.assertNodeType)("Expression") - }, - quasi: { - validate: (0, _index.assertNodeType)("TemplateLiteral") - } - } -}); - -(0, _index2.default)("TemplateElement", { - builder: ["value", "tail"], - fields: { - value: {}, - tail: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); - -(0, _index2.default)("TemplateLiteral", { - visitor: ["quasis", "expressions"], - aliases: ["Expression", "Literal"], - fields: { - quasis: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("TemplateElement"))) - }, - expressions: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) - } - } -}); - -(0, _index2.default)("YieldExpression", { - builder: ["argument", "delegate"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - delegate: { - validate: (0, _index.assertValueType)("boolean"), - default: false - }, - argument: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":146}],144:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("AwaitExpression", { - builder: ["argument"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("ForAwaitStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); - -(0, _index2.default)("BindExpression", { - visitor: ["object", "callee"], - aliases: ["Expression"], - fields: {} -}); - -(0, _index2.default)("Import", { - aliases: ["Expression"] -}); - -(0, _index2.default)("Decorator", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("DoExpression", { - visitor: ["body"], - aliases: ["Expression"], - fields: { - body: { - validate: (0, _index.assertNodeType)("BlockStatement") - } - } -}); - -(0, _index2.default)("ExportDefaultSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ExportNamespaceSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("RestProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("LVal") - } - } -}); - -(0, _index2.default)("SpreadProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":146}],145:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("AnyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("ArrayTypeAnnotation", { - visitor: ["elementType"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("BooleanTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("BooleanLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("NullLiteralTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("ClassImplements", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("ClassProperty", { - visitor: ["key", "value", "typeAnnotation", "decorators"], - builder: ["key", "value", "typeAnnotation", "decorators", "computed"], - aliases: ["Property"], - fields: { - computed: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); - -(0, _index2.default)("DeclareClass", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareFunction", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareInterface", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareModule", { - visitor: ["id", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareModuleExports", { - visitor: ["typeAnnotation"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareTypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareOpaqueType", { - visitor: ["id", "typeParameters", "supertype"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareVariable", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareExportDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("ExistentialTypeParam", { - aliases: ["Flow"] -}); - -(0, _index2.default)("FunctionTypeAnnotation", { - visitor: ["typeParameters", "params", "rest", "returnType"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("FunctionTypeParam", { - visitor: ["name", "typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("GenericTypeAnnotation", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("InterfaceExtends", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("InterfaceDeclaration", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("IntersectionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("MixedTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); - -(0, _index2.default)("EmptyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); - -(0, _index2.default)("NullableTypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("NumericLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("NumberTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("StringLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("StringTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("ThisTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("TupleTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeofTypeAnnotation", { - visitor: ["argument"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("OpaqueType", { - visitor: ["id", "typeParameters", "impltype", "supertype"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("TypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeCastExpression", { - visitor: ["expression", "typeAnnotation"], - aliases: ["Flow", "ExpressionWrapper", "Expression"], - fields: {} -}); - -(0, _index2.default)("TypeParameter", { - visitor: ["bound"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeParameterDeclaration", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeParameterInstantiation", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeAnnotation", { - visitor: ["properties", "indexers", "callProperties"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeCallProperty", { - visitor: ["value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeIndexer", { - visitor: ["id", "key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeProperty", { - visitor: ["key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeSpreadProperty", { - visitor: ["argument"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("QualifiedTypeIdentifier", { - visitor: ["id", "qualification"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("UnionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("VoidTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -},{"./index":146}],146:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -exports.assertEach = assertEach; -exports.assertOneOf = assertOneOf; -exports.assertNodeType = assertNodeType; -exports.assertNodeOrValueType = assertNodeOrValueType; -exports.assertValueType = assertValueType; -exports.chain = chain; -exports.default = defineType; - -var _index = require("../index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var VISITOR_KEYS = exports.VISITOR_KEYS = {}; -var ALIAS_KEYS = exports.ALIAS_KEYS = {}; -var NODE_FIELDS = exports.NODE_FIELDS = {}; -var BUILDER_KEYS = exports.BUILDER_KEYS = {}; -var DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {}; - -function getType(val) { - if (Array.isArray(val)) { - return "array"; - } else if (val === null) { - return "null"; - } else if (val === undefined) { - return "undefined"; - } else { - return typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val); - } -} - -function assertEach(callback) { - function validator(node, key, val) { - if (!Array.isArray(val)) return; - - for (var i = 0; i < val.length; i++) { - callback(node, key + "[" + i + "]", val[i]); - } - } - validator.each = callback; - return validator; -} - -function assertOneOf() { - for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) { - vals[_key] = arguments[_key]; - } - - function validate(node, key, val) { - if (vals.indexOf(val) < 0) { - throw new TypeError("Property " + key + " expected value to be one of " + (0, _stringify2.default)(vals) + " but got " + (0, _stringify2.default)(val)); - } - } - - validate.oneOf = vals; - - return validate; -} - -function assertNodeType() { - for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - types[_key2] = arguments[_key2]; - } - - function validate(node, key, val) { - var valid = false; - - for (var _iterator = types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var type = _ref; - - if (t.is(type, val)) { - valid = true; - break; - } - } - - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); - } - } - - validate.oneOfNodeTypes = types; - - return validate; -} - -function assertNodeOrValueType() { - for (var _len3 = arguments.length, types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - types[_key3] = arguments[_key3]; - } - - function validate(node, key, val) { - var valid = false; - - for (var _iterator2 = types, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var type = _ref2; - - if (getType(val) === type || t.is(type, val)) { - valid = true; - break; - } - } - - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); - } - } - - validate.oneOfNodeOrValueTypes = types; - - return validate; -} - -function assertValueType(type) { - function validate(node, key, val) { - var valid = getType(val) === type; - - if (!valid) { - throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); - } - } - - validate.type = type; - - return validate; -} - -function chain() { - for (var _len4 = arguments.length, fns = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - fns[_key4] = arguments[_key4]; - } - - function validate() { - for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var fn = _ref3; - - fn.apply(undefined, arguments); - } - } - validate.chainOf = fns; - return validate; -} - -function defineType(type) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var inherits = opts.inherits && store[opts.inherits] || {}; - - opts.fields = opts.fields || inherits.fields || {}; - opts.visitor = opts.visitor || inherits.visitor || []; - opts.aliases = opts.aliases || inherits.aliases || []; - opts.builder = opts.builder || inherits.builder || opts.visitor || []; - - if (opts.deprecatedAlias) { - DEPRECATED_KEYS[opts.deprecatedAlias] = type; - } - - for (var _iterator4 = opts.visitor.concat(opts.builder), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var _key5 = _ref4; - - opts.fields[_key5] = opts.fields[_key5] || {}; - } - - for (var key in opts.fields) { - var field = opts.fields[key]; - - if (opts.builder.indexOf(key) === -1) { - field.optional = true; - } - if (field.default === undefined) { - field.default = null; - } else if (!field.validate) { - field.validate = assertValueType(getType(field.default)); - } - } - - VISITOR_KEYS[type] = opts.visitor; - BUILDER_KEYS[type] = opts.builder; - NODE_FIELDS[type] = opts.fields; - ALIAS_KEYS[type] = opts.aliases; - - store[type] = opts; -} - -var store = {}; -},{"../index":151,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/helpers/typeof":113}],147:[function(require,module,exports){ -"use strict"; - -require("./index"); - -require("./core"); - -require("./es2015"); - -require("./flow"); - -require("./jsx"); - -require("./misc"); - -require("./experimental"); -},{"./core":142,"./es2015":143,"./experimental":144,"./flow":145,"./index":146,"./jsx":148,"./misc":149}],148:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("JSXAttribute", { - visitor: ["name", "value"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXNamespacedName") - }, - value: { - optional: true, - validate: (0, _index.assertNodeType)("JSXElement", "StringLiteral", "JSXExpressionContainer") - } - } -}); - -(0, _index2.default)("JSXClosingElement", { - visitor: ["name"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - } - } -}); - -(0, _index2.default)("JSXElement", { - builder: ["openingElement", "closingElement", "children", "selfClosing"], - visitor: ["openingElement", "children", "closingElement"], - aliases: ["JSX", "Immutable", "Expression"], - fields: { - openingElement: { - validate: (0, _index.assertNodeType)("JSXOpeningElement") - }, - closingElement: { - optional: true, - validate: (0, _index.assertNodeType)("JSXClosingElement") - }, - children: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement"))) - } - } -}); - -(0, _index2.default)("JSXEmptyExpression", { - aliases: ["JSX", "Expression"] -}); - -(0, _index2.default)("JSXExpressionContainer", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("JSXSpreadChild", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("JSXIdentifier", { - builder: ["name"], - aliases: ["JSX", "Expression"], - fields: { - name: { - validate: (0, _index.assertValueType)("string") - } - } -}); - -(0, _index2.default)("JSXMemberExpression", { - visitor: ["object", "property"], - aliases: ["JSX", "Expression"], - fields: { - object: { - validate: (0, _index.assertNodeType)("JSXMemberExpression", "JSXIdentifier") - }, - property: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } - } -}); - -(0, _index2.default)("JSXNamespacedName", { - visitor: ["namespace", "name"], - aliases: ["JSX"], - fields: { - namespace: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - }, - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } - } -}); - -(0, _index2.default)("JSXOpeningElement", { - builder: ["name", "attributes", "selfClosing"], - visitor: ["name", "attributes"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - }, - selfClosing: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - attributes: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) - } - } -}); - -(0, _index2.default)("JSXSpreadAttribute", { - visitor: ["argument"], - aliases: ["JSX"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("JSXText", { - aliases: ["JSX", "Immutable"], - builder: ["value"], - fields: { - value: { - validate: (0, _index.assertValueType)("string") - } - } -}); -},{"./index":146}],149:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("Noop", { - visitor: [] -}); - -(0, _index2.default)("ParenthesizedExpression", { - visitor: ["expression"], - aliases: ["Expression", "ExpressionWrapper"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":146}],150:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.createUnionTypeAnnotation = createUnionTypeAnnotation; -exports.removeTypeDuplicates = removeTypeDuplicates; -exports.createTypeAnnotationBasedOnTypeof = createTypeAnnotationBasedOnTypeof; - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function createUnionTypeAnnotation(types) { - var flattened = removeTypeDuplicates(types); - - if (flattened.length === 1) { - return flattened[0]; - } else { - return t.unionTypeAnnotation(flattened); - } -} - -function removeTypeDuplicates(nodes) { - var generics = {}; - var bases = {}; - - var typeGroups = []; - - var types = []; - - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; - - if (types.indexOf(node) >= 0) { - continue; - } - - if (t.isAnyTypeAnnotation(node)) { - return [node]; - } - - if (t.isFlowBaseAnnotation(node)) { - bases[node.type] = node; - continue; - } - - if (t.isUnionTypeAnnotation(node)) { - if (typeGroups.indexOf(node.types) < 0) { - nodes = nodes.concat(node.types); - typeGroups.push(node.types); - } - continue; - } - - if (t.isGenericTypeAnnotation(node)) { - var name = node.id.name; - - if (generics[name]) { - var existing = generics[name]; - if (existing.typeParameters) { - if (node.typeParameters) { - existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); - } - } else { - existing = node.typeParameters; - } - } else { - generics[name] = node; - } - - continue; - } - - types.push(node); - } - - for (var type in bases) { - types.push(bases[type]); - } - - for (var _name in generics) { - types.push(generics[_name]); - } - - return types; -} - -function createTypeAnnotationBasedOnTypeof(type) { - if (type === "string") { - return t.stringTypeAnnotation(); - } else if (type === "number") { - return t.numberTypeAnnotation(); - } else if (type === "undefined") { - return t.voidTypeAnnotation(); - } else if (type === "boolean") { - return t.booleanTypeAnnotation(); - } else if (type === "function") { - return t.genericTypeAnnotation(t.identifier("Function")); - } else if (type === "object") { - return t.genericTypeAnnotation(t.identifier("Object")); - } else if (type === "symbol") { - return t.genericTypeAnnotation(t.identifier("Symbol")); - } else { - throw new Error("Invalid typeof value"); - } -} -},{"./index":151}],151:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.createTypeAnnotationBasedOnTypeof = exports.removeTypeDuplicates = exports.createUnionTypeAnnotation = exports.valueToNode = exports.toBlock = exports.toExpression = exports.toStatement = exports.toBindingIdentifierName = exports.toIdentifier = exports.toKeyAlias = exports.toSequenceExpression = exports.toComputedKey = exports.isNodesEquivalent = exports.isImmutable = exports.isScope = exports.isSpecifierDefault = exports.isVar = exports.isBlockScoped = exports.isLet = exports.isValidIdentifier = exports.isReferenced = exports.isBinding = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.TYPES = exports.react = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; - -var _getOwnPropertySymbols = require("babel-runtime/core-js/object/get-own-property-symbols"); - -var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _constants = require("./constants"); - -Object.defineProperty(exports, "STATEMENT_OR_BLOCK_KEYS", { - enumerable: true, - get: function get() { - return _constants.STATEMENT_OR_BLOCK_KEYS; - } -}); -Object.defineProperty(exports, "FLATTENABLE_KEYS", { - enumerable: true, - get: function get() { - return _constants.FLATTENABLE_KEYS; - } -}); -Object.defineProperty(exports, "FOR_INIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.FOR_INIT_KEYS; - } -}); -Object.defineProperty(exports, "COMMENT_KEYS", { - enumerable: true, - get: function get() { - return _constants.COMMENT_KEYS; - } -}); -Object.defineProperty(exports, "LOGICAL_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.LOGICAL_OPERATORS; - } -}); -Object.defineProperty(exports, "UPDATE_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UPDATE_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "EQUALITY_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.EQUALITY_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "COMPARISON_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.COMPARISON_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "STRING_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.STRING_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "INHERIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.INHERIT_KEYS; - } -}); -Object.defineProperty(exports, "BLOCK_SCOPED_SYMBOL", { - enumerable: true, - get: function get() { - return _constants.BLOCK_SCOPED_SYMBOL; - } -}); -Object.defineProperty(exports, "NOT_LOCAL_BINDING", { - enumerable: true, - get: function get() { - return _constants.NOT_LOCAL_BINDING; - } -}); -exports.is = is; -exports.isType = isType; -exports.validate = validate; -exports.shallowEqual = shallowEqual; -exports.appendToMemberExpression = appendToMemberExpression; -exports.prependToMemberExpression = prependToMemberExpression; -exports.ensureBlock = ensureBlock; -exports.clone = clone; -exports.cloneWithoutLoc = cloneWithoutLoc; -exports.cloneDeep = cloneDeep; -exports.buildMatchMemberExpression = buildMatchMemberExpression; -exports.removeComments = removeComments; -exports.inheritsComments = inheritsComments; -exports.inheritTrailingComments = inheritTrailingComments; -exports.inheritLeadingComments = inheritLeadingComments; -exports.inheritInnerComments = inheritInnerComments; -exports.inherits = inherits; -exports.assertNode = assertNode; -exports.isNode = isNode; -exports.traverseFast = traverseFast; -exports.removeProperties = removeProperties; -exports.removePropertiesDeep = removePropertiesDeep; - -var _retrievers = require("./retrievers"); - -Object.defineProperty(exports, "getBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getBindingIdentifiers; - } -}); -Object.defineProperty(exports, "getOuterBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getOuterBindingIdentifiers; - } -}); - -var _validators = require("./validators"); - -Object.defineProperty(exports, "isBinding", { - enumerable: true, - get: function get() { - return _validators.isBinding; - } -}); -Object.defineProperty(exports, "isReferenced", { - enumerable: true, - get: function get() { - return _validators.isReferenced; - } -}); -Object.defineProperty(exports, "isValidIdentifier", { - enumerable: true, - get: function get() { - return _validators.isValidIdentifier; - } -}); -Object.defineProperty(exports, "isLet", { - enumerable: true, - get: function get() { - return _validators.isLet; - } -}); -Object.defineProperty(exports, "isBlockScoped", { - enumerable: true, - get: function get() { - return _validators.isBlockScoped; - } -}); -Object.defineProperty(exports, "isVar", { - enumerable: true, - get: function get() { - return _validators.isVar; - } -}); -Object.defineProperty(exports, "isSpecifierDefault", { - enumerable: true, - get: function get() { - return _validators.isSpecifierDefault; - } -}); -Object.defineProperty(exports, "isScope", { - enumerable: true, - get: function get() { - return _validators.isScope; - } -}); -Object.defineProperty(exports, "isImmutable", { - enumerable: true, - get: function get() { - return _validators.isImmutable; - } -}); -Object.defineProperty(exports, "isNodesEquivalent", { - enumerable: true, - get: function get() { - return _validators.isNodesEquivalent; - } -}); - -var _converters = require("./converters"); - -Object.defineProperty(exports, "toComputedKey", { - enumerable: true, - get: function get() { - return _converters.toComputedKey; - } -}); -Object.defineProperty(exports, "toSequenceExpression", { - enumerable: true, - get: function get() { - return _converters.toSequenceExpression; - } -}); -Object.defineProperty(exports, "toKeyAlias", { - enumerable: true, - get: function get() { - return _converters.toKeyAlias; - } -}); -Object.defineProperty(exports, "toIdentifier", { - enumerable: true, - get: function get() { - return _converters.toIdentifier; - } -}); -Object.defineProperty(exports, "toBindingIdentifierName", { - enumerable: true, - get: function get() { - return _converters.toBindingIdentifierName; - } -}); -Object.defineProperty(exports, "toStatement", { - enumerable: true, - get: function get() { - return _converters.toStatement; - } -}); -Object.defineProperty(exports, "toExpression", { - enumerable: true, - get: function get() { - return _converters.toExpression; - } -}); -Object.defineProperty(exports, "toBlock", { - enumerable: true, - get: function get() { - return _converters.toBlock; - } -}); -Object.defineProperty(exports, "valueToNode", { - enumerable: true, - get: function get() { - return _converters.valueToNode; - } -}); - -var _flow = require("./flow"); - -Object.defineProperty(exports, "createUnionTypeAnnotation", { - enumerable: true, - get: function get() { - return _flow.createUnionTypeAnnotation; - } -}); -Object.defineProperty(exports, "removeTypeDuplicates", { - enumerable: true, - get: function get() { - return _flow.removeTypeDuplicates; - } -}); -Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { - enumerable: true, - get: function get() { - return _flow.createTypeAnnotationBasedOnTypeof; - } -}); - -var _toFastProperties = require("to-fast-properties"); - -var _toFastProperties2 = _interopRequireDefault(_toFastProperties); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -var _uniq = require("lodash/uniq"); - -var _uniq2 = _interopRequireDefault(_uniq); - -require("./definitions/init"); - -var _definitions = require("./definitions"); - -var _react2 = require("./react"); - -var _react = _interopRequireWildcard(_react2); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var t = exports; - -function registerType(type) { - var is = t["is" + type]; - if (!is) { - is = t["is" + type] = function (node, opts) { - return t.is(type, node, opts); - }; - } - - t["assert" + type] = function (node, opts) { - opts = opts || {}; - if (!is(node, opts)) { - throw new Error("Expected type " + (0, _stringify2.default)(type) + " with option " + (0, _stringify2.default)(opts)); - } - }; -} - -exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; -exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; -exports.NODE_FIELDS = _definitions.NODE_FIELDS; -exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; -exports.DEPRECATED_KEYS = _definitions.DEPRECATED_KEYS; -exports.react = _react; - - -for (var type in t.VISITOR_KEYS) { - registerType(type); -} - -t.FLIPPED_ALIAS_KEYS = {}; - -(0, _keys2.default)(t.ALIAS_KEYS).forEach(function (type) { - t.ALIAS_KEYS[type].forEach(function (alias) { - var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; - types.push(type); - }); -}); - -(0, _keys2.default)(t.FLIPPED_ALIAS_KEYS).forEach(function (type) { - t[type.toUpperCase() + "_TYPES"] = t.FLIPPED_ALIAS_KEYS[type]; - registerType(type); -}); - -var TYPES = exports.TYPES = (0, _keys2.default)(t.VISITOR_KEYS).concat((0, _keys2.default)(t.FLIPPED_ALIAS_KEYS)).concat((0, _keys2.default)(t.DEPRECATED_KEYS)); - -function is(type, node, opts) { - if (!node) return false; - - var matches = isType(node.type, type); - if (!matches) return false; - - if (typeof opts === "undefined") { - return true; - } else { - return t.shallowEqual(node, opts); - } -} - -function isType(nodeType, targetType) { - if (nodeType === targetType) return true; - - if (t.ALIAS_KEYS[targetType]) return false; - - var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; - if (aliases) { - if (aliases[0] === nodeType) return true; - - for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var alias = _ref; - - if (nodeType === alias) return true; - } - } - - return false; -} - -(0, _keys2.default)(t.BUILDER_KEYS).forEach(function (type) { - var keys = t.BUILDER_KEYS[type]; - - function builder() { - if (arguments.length > keys.length) { - throw new Error("t." + type + ": Too many arguments passed. Received " + arguments.length + " but can receive " + ("no more than " + keys.length)); - } - - var node = {}; - node.type = type; - - var i = 0; - - for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _key = _ref2; - - var field = t.NODE_FIELDS[type][_key]; - - var arg = arguments[i++]; - if (arg === undefined) arg = (0, _clone2.default)(field.default); - - node[_key] = arg; - } - - for (var key in node) { - validate(node, key, node[key]); - } - - return node; - } - - t[type] = builder; - t[type[0].toLowerCase() + type.slice(1)] = builder; -}); - -var _loop = function _loop(_type) { - var newType = t.DEPRECATED_KEYS[_type]; - - function proxy(fn) { - return function () { - console.trace("The node type " + _type + " has been renamed to " + newType); - return fn.apply(this, arguments); - }; - } - - t[_type] = t[_type[0].toLowerCase() + _type.slice(1)] = proxy(t[newType]); - t["is" + _type] = proxy(t["is" + newType]); - t["assert" + _type] = proxy(t["assert" + newType]); -}; - -for (var _type in t.DEPRECATED_KEYS) { - _loop(_type); -} - -function validate(node, key, val) { - if (!node) return; - - var fields = t.NODE_FIELDS[node.type]; - if (!fields) return; - - var field = fields[key]; - if (!field || !field.validate) return; - if (field.optional && val == null) return; - - field.validate(node, key, val); -} - -function shallowEqual(actual, expected) { - var keys = (0, _keys2.default)(expected); - - for (var _iterator3 = keys, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var key = _ref3; - - if (actual[key] !== expected[key]) { - return false; - } - } - - return true; -} - -function appendToMemberExpression(member, append, computed) { - member.object = t.memberExpression(member.object, member.property, member.computed); - member.property = append; - member.computed = !!computed; - return member; -} - -function prependToMemberExpression(member, prepend) { - member.object = t.memberExpression(prepend, member.object); - return member; -} - -function ensureBlock(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "body"; - - return node[key] = t.toBlock(node[key], node); -} - -function clone(node) { - if (!node) return node; - var newNode = {}; - for (var key in node) { - if (key[0] === "_") continue; - newNode[key] = node[key]; - } - return newNode; -} - -function cloneWithoutLoc(node) { - var newNode = clone(node); - delete newNode.loc; - return newNode; -} - -function cloneDeep(node) { - if (!node) return node; - var newNode = {}; - - for (var key in node) { - if (key[0] === "_") continue; - - var val = node[key]; - - if (val) { - if (val.type) { - val = t.cloneDeep(val); - } else if (Array.isArray(val)) { - val = val.map(t.cloneDeep); - } - } - - newNode[key] = val; - } - - return newNode; -} - -function buildMatchMemberExpression(match, allowPartial) { - var parts = match.split("."); - - return function (member) { - if (!t.isMemberExpression(member)) return false; - - var search = [member]; - var i = 0; - - while (search.length) { - var node = search.shift(); - - if (allowPartial && i === parts.length) { - return true; - } - - if (t.isIdentifier(node)) { - if (parts[i] !== node.name) return false; - } else if (t.isStringLiteral(node)) { - if (parts[i] !== node.value) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isStringLiteral(node.property)) { - return false; - } else { - search.push(node.object); - search.push(node.property); - continue; - } - } else { - return false; - } - - if (++i > parts.length) { - return false; - } - } - - return true; - }; -} - -function removeComments(node) { - for (var _iterator4 = t.COMMENT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var key = _ref4; - - delete node[key]; - } - return node; -} - -function inheritsComments(child, parent) { - inheritTrailingComments(child, parent); - inheritLeadingComments(child, parent); - inheritInnerComments(child, parent); - return child; -} - -function inheritTrailingComments(child, parent) { - _inheritComments("trailingComments", child, parent); -} - -function inheritLeadingComments(child, parent) { - _inheritComments("leadingComments", child, parent); -} - -function inheritInnerComments(child, parent) { - _inheritComments("innerComments", child, parent); -} - -function _inheritComments(key, child, parent) { - if (child && parent) { - child[key] = (0, _uniq2.default)([].concat(child[key], parent[key]).filter(Boolean)); - } -} - -function inherits(child, parent) { - if (!child || !parent) return child; - - for (var _iterator5 = t.INHERIT_KEYS.optional, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var _key2 = _ref5; - - if (child[_key2] == null) { - child[_key2] = parent[_key2]; - } - } - - for (var key in parent) { - if (key[0] === "_") child[key] = parent[key]; - } - - for (var _iterator6 = t.INHERIT_KEYS.force, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } - - var _key3 = _ref6; - - child[_key3] = parent[_key3]; - } - - t.inheritsComments(child, parent); - - return child; -} - -function assertNode(node) { - if (!isNode(node)) { - throw new TypeError("Not a valid node " + (node && node.type)); - } -} - -function isNode(node) { - return !!(node && _definitions.VISITOR_KEYS[node.type]); -} - -(0, _toFastProperties2.default)(t); -(0, _toFastProperties2.default)(t.VISITOR_KEYS); - -function traverseFast(node, enter, opts) { - if (!node) return; - - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; - - opts = opts || {}; - enter(node, opts); - - for (var _iterator7 = keys, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } - - var key = _ref7; - - var subNode = node[key]; - - if (Array.isArray(subNode)) { - for (var _iterator8 = subNode, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; - - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } - - var _node = _ref8; - - traverseFast(_node, enter, opts); - } - } else { - traverseFast(subNode, enter, opts); - } - } -} - -var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; - -var CLEAR_KEYS_PLUS_COMMENTS = t.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); - -function removeProperties(node, opts) { - opts = opts || {}; - var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; - for (var _iterator9 = map, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; - - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } - - var _key4 = _ref9; - - if (node[_key4] != null) node[_key4] = undefined; - } - - for (var key in node) { - if (key[0] === "_" && node[key] != null) node[key] = undefined; - } - - var syms = (0, _getOwnPropertySymbols2.default)(node); - for (var _iterator10 = syms, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; - } - - var sym = _ref10; - - node[sym] = null; - } -} - -function removePropertiesDeep(tree, opts) { - traverseFast(tree, removeProperties, opts); - return tree; -} -},{"./constants":140,"./converters":141,"./definitions":146,"./definitions/init":147,"./flow":150,"./react":152,"./retrievers":153,"./validators":154,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/object/get-own-property-symbols":101,"babel-runtime/core-js/object/keys":102,"lodash/clone":466,"lodash/uniq":517,"to-fast-properties":555}],152:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.isReactComponent = undefined; -exports.isCompatTag = isCompatTag; -exports.buildChildren = buildChildren; - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var isReactComponent = exports.isReactComponent = t.buildMatchMemberExpression("React.Component"); - -function isCompatTag(tagName) { - return !!tagName && /^[a-z]|\-/.test(tagName); -} - -function cleanJSXElementLiteralChild(child, args) { - var lines = child.value.split(/\r\n|\n|\r/); - - var lastNonEmptyLine = 0; - - for (var i = 0; i < lines.length; i++) { - if (lines[i].match(/[^ \t]/)) { - lastNonEmptyLine = i; - } - } - - var str = ""; - - for (var _i = 0; _i < lines.length; _i++) { - var line = lines[_i]; - - var isFirstLine = _i === 0; - var isLastLine = _i === lines.length - 1; - var isLastNonEmptyLine = _i === lastNonEmptyLine; - - var trimmedLine = line.replace(/\t/g, " "); - - if (!isFirstLine) { - trimmedLine = trimmedLine.replace(/^[ ]+/, ""); - } - - if (!isLastLine) { - trimmedLine = trimmedLine.replace(/[ ]+$/, ""); - } - - if (trimmedLine) { - if (!isLastNonEmptyLine) { - trimmedLine += " "; - } - - str += trimmedLine; - } - } - - if (str) args.push(t.stringLiteral(str)); -} - -function buildChildren(node) { - var elems = []; - - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i]; - - if (t.isJSXText(child)) { - cleanJSXElementLiteralChild(child, elems); - continue; - } - - if (t.isJSXExpressionContainer(child)) child = child.expression; - if (t.isJSXEmptyExpression(child)) continue; - - elems.push(child); - } - - return elems; -} -},{"./index":151}],153:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getBindingIdentifiers(node, duplicates, outerOnly) { - var search = [].concat(node); - var ids = (0, _create2.default)(null); - - while (search.length) { - var id = search.shift(); - if (!id) continue; - - var keys = t.getBindingIdentifiers.keys[id.type]; - - if (t.isIdentifier(id)) { - if (duplicates) { - var _ids = ids[id.name] = ids[id.name] || []; - _ids.push(id); - } else { - ids[id.name] = id; - } - continue; - } - - if (t.isExportDeclaration(id)) { - if (t.isDeclaration(id.declaration)) { - search.push(id.declaration); - } - continue; - } - - if (outerOnly) { - if (t.isFunctionDeclaration(id)) { - search.push(id.id); - continue; - } - - if (t.isFunctionExpression(id)) { - continue; - } - } - - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (id[key]) { - search = search.concat(id[key]); - } - } - } - } - - return ids; -} - -getBindingIdentifiers.keys = { - DeclareClass: ["id"], - DeclareFunction: ["id"], - DeclareModule: ["id"], - DeclareVariable: ["id"], - InterfaceDeclaration: ["id"], - TypeAlias: ["id"], - OpaqueType: ["id"], - - CatchClause: ["param"], - LabeledStatement: ["label"], - UnaryExpression: ["argument"], - AssignmentExpression: ["left"], - - ImportSpecifier: ["local"], - ImportNamespaceSpecifier: ["local"], - ImportDefaultSpecifier: ["local"], - ImportDeclaration: ["specifiers"], - - ExportSpecifier: ["exported"], - ExportNamespaceSpecifier: ["exported"], - ExportDefaultSpecifier: ["exported"], - - FunctionDeclaration: ["id", "params"], - FunctionExpression: ["id", "params"], - - ClassDeclaration: ["id"], - ClassExpression: ["id"], - - RestElement: ["argument"], - UpdateExpression: ["argument"], - - RestProperty: ["argument"], - ObjectProperty: ["value"], - - AssignmentPattern: ["left"], - ArrayPattern: ["elements"], - ObjectPattern: ["properties"], - - VariableDeclaration: ["declarations"], - VariableDeclarator: ["id"] -}; - -function getOuterBindingIdentifiers(node, duplicates) { - return getBindingIdentifiers(node, duplicates, true); -} -},{"./index":151,"babel-runtime/core-js/object/create":100}],154:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.isBinding = isBinding; -exports.isReferenced = isReferenced; -exports.isValidIdentifier = isValidIdentifier; -exports.isLet = isLet; -exports.isBlockScoped = isBlockScoped; -exports.isVar = isVar; -exports.isSpecifierDefault = isSpecifierDefault; -exports.isScope = isScope; -exports.isImmutable = isImmutable; -exports.isNodesEquivalent = isNodesEquivalent; - -var _retrievers = require("./retrievers"); - -var _esutils = require("esutils"); - -var _esutils2 = _interopRequireDefault(_esutils); - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -var _constants = require("./constants"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isBinding(node, parent) { - var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var val = parent[key]; - if (Array.isArray(val)) { - if (val.indexOf(node) >= 0) return true; - } else { - if (val === node) return true; - } - } - } - - return false; -} - -function isReferenced(node, parent) { - switch (parent.type) { - case "BindExpression": - return parent.object === node || parent.callee === node; - - case "MemberExpression": - case "JSXMemberExpression": - if (parent.property === node && parent.computed) { - return true; - } else if (parent.object === node) { - return true; - } else { - return false; - } - - case "MetaProperty": - return false; - - case "ObjectProperty": - if (parent.key === node) { - return parent.computed; - } - - case "VariableDeclarator": - return parent.id !== node; - - case "ArrowFunctionExpression": - case "FunctionDeclaration": - case "FunctionExpression": - for (var _iterator = parent.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var param = _ref; - - if (param === node) return false; - } - - return parent.id !== node; - - case "ExportSpecifier": - if (parent.source) { - return false; - } else { - return parent.local === node; - } - - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return false; - - case "JSXAttribute": - return parent.name !== node; - - case "ClassProperty": - if (parent.key === node) { - return parent.computed; - } else { - return parent.value === node; - } - - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "ImportSpecifier": - return false; - - case "ClassDeclaration": - case "ClassExpression": - return parent.id !== node; - - case "ClassMethod": - case "ObjectMethod": - return parent.key === node && parent.computed; - - case "LabeledStatement": - return false; - - case "CatchClause": - return parent.param !== node; - - case "RestElement": - return false; - - case "AssignmentExpression": - return parent.right === node; - - case "AssignmentPattern": - return parent.right === node; - - case "ObjectPattern": - case "ArrayPattern": - return false; - } - - return true; -} - -function isValidIdentifier(name) { - if (typeof name !== "string" || _esutils2.default.keyword.isReservedWordES6(name, true)) { - return false; - } else if (name === "await") { - return false; - } else { - return _esutils2.default.keyword.isIdentifierNameES6(name); - } -} - -function isLet(node) { - return t.isVariableDeclaration(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); -} - -function isBlockScoped(node) { - return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node); -} - -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; -} - -function isSpecifierDefault(specifier) { - return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); -} - -function isScope(node, parent) { - if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { - return false; - } - - return t.isScopable(node); -} - -function isImmutable(node) { - if (t.isType(node.type, "Immutable")) return true; - - if (t.isIdentifier(node)) { - if (node.name === "undefined") { - return true; - } else { - return false; - } - } - - return false; -} - -function isNodesEquivalent(a, b) { - if ((typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || (typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || a == null || b == null) { - return a === b; - } - - if (a.type !== b.type) { - return false; - } - - var fields = (0, _keys2.default)(t.NODE_FIELDS[a.type] || a.type); - - for (var _iterator2 = fields, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var field = _ref2; - - if ((0, _typeof3.default)(a[field]) !== (0, _typeof3.default)(b[field])) { - return false; - } - - if (Array.isArray(a[field])) { - if (!Array.isArray(b[field])) { - return false; - } - if (a[field].length !== b[field].length) { - return false; - } - - for (var i = 0; i < a[field].length; i++) { - if (!isNodesEquivalent(a[field][i], b[field][i])) { - return false; - } - } - continue; - } - - if (!isNodesEquivalent(a[field], b[field])) { - return false; - } - } - - return true; -} -},{"./constants":140,"./index":151,"./retrievers":153,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/typeof":113,"esutils":287}],155:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -/* eslint max-len: 0 */ - -// This is a trick taken from Esprima. It turns out that, on -// non-Chrome browsers, to check whether a string is in a set, a -// predicate containing a big ugly `switch` statement is faster than -// a regular expression, and on Chrome the two are about on par. -// This function uses `eval` (non-lexical) to produce such a -// predicate from a space-separated string of words. -// -// It starts by sorting the words by length. - -function makePredicate(words) { - words = words.split(" "); - return function (str) { - return words.indexOf(str) >= 0; - }; -} - -// Reserved word lists for various dialects of the language - -var reservedWords = { - 6: makePredicate("enum await"), - strict: makePredicate("implements interface let package private protected public static yield"), - strictBind: makePredicate("eval arguments") -}; - -// And the keywords - -var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super"); - -// ## Character categories - -// Big ugly regular expressions that match characters in the -// whitespace, identifier, and identifier-start categories. These -// are only applied when a character is found to actually have a -// code point above 128. -// Generated by `bin/generate-identifier-regex.js`. - -var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; -var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA900-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F"; - -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - -// These are a run-length and offset encoded representation of the -// >0xffff code points that are a valid part of identifiers. The -// offset starts at 0x10000, and each pair of numbers represents an -// offset to the next range, and then a size of the range. They were -// generated by `bin/generate-identifier-regex.js`. -// eslint-disable-next-line comma-spacing -var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 785, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 25, 391, 63, 32, 0, 449, 56, 264, 8, 2, 36, 18, 0, 50, 29, 881, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 65, 0, 32, 6124, 20, 754, 9486, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 60, 67, 1213, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 10591, 541]; -// eslint-disable-next-line comma-spacing -var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 10, 2, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 87, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 423, 9, 838, 7, 2, 7, 17, 9, 57, 21, 2, 13, 19882, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239]; - -// This has a complexity linear to the value of the code. The -// assumption is that looking up astral identifier characters is -// rare. -function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) return false; - - pos += set[i + 1]; - if (pos >= code) return true; - } -} - -// Test whether a given character code starts an identifier. - -function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes); -} - -// Test whether a given character is part of an identifier. - -function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); -} - -// A second optional argument can be given to further configure -var defaultOptions = { - // Source type ("script" or "module") for different semantics - sourceType: "script", - // Source filename. - sourceFilename: undefined, - // Line from which to start counting source. Useful for - // integration with other tools. - startLine: 1, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // TODO - allowSuperOutsideMethod: false, - // An array of plugins to enable - plugins: [], - // TODO - strictMode: null -}; - -// Interpret and default an options object - -function getOptions(opts) { - var options = {}; - for (var key in defaultOptions) { - options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; - } - return options; -} - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; -} : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; - - - - - - - - - - - -var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; - - - - - - - - - - - -var inherits = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; -}; - - - - - - - - - - - -var possibleConstructorReturn = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return call && (typeof call === "object" || typeof call === "function") ? call : self; -}; - -// ## Token types - -// The assignment of fine-grained, information-carrying type objects -// allows the tokenizer to store the information it has about a -// token in a way that is very cheap for the parser to look up. - -// All token type variables start with an underscore, to make them -// easy to recognize. - -// The `beforeExpr` property is used to disambiguate between regular -// expressions and divisions. It is set on all token types that can -// be followed by an expression (thus, a slash after them would be a -// regular expression). -// -// `isLoop` marks a keyword as starting a loop, which is important -// to know when parsing a label, in order to allow or disallow -// continue jumps to that label. - -var beforeExpr = true; -var startsExpr = true; -var isLoop = true; -var isAssign = true; -var prefix = true; -var postfix = true; - -var TokenType = function TokenType(label) { - var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, TokenType); - - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.rightAssociative = !!conf.rightAssociative; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; -}; - -var KeywordTokenType = function (_TokenType) { - inherits(KeywordTokenType, _TokenType); - - function KeywordTokenType(name) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, KeywordTokenType); - - options.keyword = name; - - return possibleConstructorReturn(this, _TokenType.call(this, name, options)); - } - - return KeywordTokenType; -}(TokenType); - -var BinopTokenType = function (_TokenType2) { - inherits(BinopTokenType, _TokenType2); - - function BinopTokenType(name, prec) { - classCallCheck(this, BinopTokenType); - return possibleConstructorReturn(this, _TokenType2.call(this, name, { beforeExpr: beforeExpr, binop: prec })); - } - - return BinopTokenType; -}(TokenType); - -var types = { - num: new TokenType("num", { startsExpr: startsExpr }), - regexp: new TokenType("regexp", { startsExpr: startsExpr }), - string: new TokenType("string", { startsExpr: startsExpr }), - name: new TokenType("name", { startsExpr: startsExpr }), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - bracketR: new TokenType("]"), - braceL: new TokenType("{", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceBarL: new TokenType("{|", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceR: new TokenType("}"), - braceBarR: new TokenType("|}"), - parenL: new TokenType("(", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - parenR: new TokenType(")"), - comma: new TokenType(",", { beforeExpr: beforeExpr }), - semi: new TokenType(";", { beforeExpr: beforeExpr }), - colon: new TokenType(":", { beforeExpr: beforeExpr }), - doubleColon: new TokenType("::", { beforeExpr: beforeExpr }), - dot: new TokenType("."), - question: new TokenType("?", { beforeExpr: beforeExpr }), - arrow: new TokenType("=>", { beforeExpr: beforeExpr }), - template: new TokenType("template"), - ellipsis: new TokenType("...", { beforeExpr: beforeExpr }), - backQuote: new TokenType("`", { startsExpr: startsExpr }), - dollarBraceL: new TokenType("${", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - at: new TokenType("@"), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", { beforeExpr: beforeExpr, isAssign: isAssign }), - assign: new TokenType("_=", { beforeExpr: beforeExpr, isAssign: isAssign }), - incDec: new TokenType("++/--", { prefix: prefix, postfix: postfix, startsExpr: startsExpr }), - prefix: new TokenType("prefix", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - logicalOR: new BinopTokenType("||", 1), - logicalAND: new BinopTokenType("&&", 2), - bitwiseOR: new BinopTokenType("|", 3), - bitwiseXOR: new BinopTokenType("^", 4), - bitwiseAND: new BinopTokenType("&", 5), - equality: new BinopTokenType("==/!=", 6), - relational: new BinopTokenType("", 7), - bitShift: new BinopTokenType("<>", 8), - plusMin: new TokenType("+/-", { beforeExpr: beforeExpr, binop: 9, prefix: prefix, startsExpr: startsExpr }), - modulo: new BinopTokenType("%", 10), - star: new BinopTokenType("*", 10), - slash: new BinopTokenType("/", 10), - exponent: new TokenType("**", { beforeExpr: beforeExpr, binop: 11, rightAssociative: true }) -}; - -var keywords = { - "break": new KeywordTokenType("break"), - "case": new KeywordTokenType("case", { beforeExpr: beforeExpr }), - "catch": new KeywordTokenType("catch"), - "continue": new KeywordTokenType("continue"), - "debugger": new KeywordTokenType("debugger"), - "default": new KeywordTokenType("default", { beforeExpr: beforeExpr }), - "do": new KeywordTokenType("do", { isLoop: isLoop, beforeExpr: beforeExpr }), - "else": new KeywordTokenType("else", { beforeExpr: beforeExpr }), - "finally": new KeywordTokenType("finally"), - "for": new KeywordTokenType("for", { isLoop: isLoop }), - "function": new KeywordTokenType("function", { startsExpr: startsExpr }), - "if": new KeywordTokenType("if"), - "return": new KeywordTokenType("return", { beforeExpr: beforeExpr }), - "switch": new KeywordTokenType("switch"), - "throw": new KeywordTokenType("throw", { beforeExpr: beforeExpr }), - "try": new KeywordTokenType("try"), - "var": new KeywordTokenType("var"), - "let": new KeywordTokenType("let"), - "const": new KeywordTokenType("const"), - "while": new KeywordTokenType("while", { isLoop: isLoop }), - "with": new KeywordTokenType("with"), - "new": new KeywordTokenType("new", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "this": new KeywordTokenType("this", { startsExpr: startsExpr }), - "super": new KeywordTokenType("super", { startsExpr: startsExpr }), - "class": new KeywordTokenType("class"), - "extends": new KeywordTokenType("extends", { beforeExpr: beforeExpr }), - "export": new KeywordTokenType("export"), - "import": new KeywordTokenType("import", { startsExpr: startsExpr }), - "yield": new KeywordTokenType("yield", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "null": new KeywordTokenType("null", { startsExpr: startsExpr }), - "true": new KeywordTokenType("true", { startsExpr: startsExpr }), - "false": new KeywordTokenType("false", { startsExpr: startsExpr }), - "in": new KeywordTokenType("in", { beforeExpr: beforeExpr, binop: 7 }), - "instanceof": new KeywordTokenType("instanceof", { beforeExpr: beforeExpr, binop: 7 }), - "typeof": new KeywordTokenType("typeof", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "void": new KeywordTokenType("void", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "delete": new KeywordTokenType("delete", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }) -}; - -// Map keyword names to token types. -Object.keys(keywords).forEach(function (name) { - types["_" + name] = keywords[name]; -}); - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -var lineBreak = /\r\n?|\n|\u2028|\u2029/; -var lineBreakG = new RegExp(lineBreak.source, "g"); - -function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029; -} - -var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - -// The algorithm used to determine whether a regexp can appear at a -// given point in the program is loosely based on sweet.js' approach. -// See https://github.com/mozilla/sweet.js/wiki/design - -var TokContext = function TokContext(token, isExpr, preserveSpace, override) { - classCallCheck(this, TokContext); - - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; -}; - -var types$1 = { - braceStatement: new TokContext("{", false), - braceExpression: new TokContext("{", true), - templateQuasi: new TokContext("${", true), - parenStatement: new TokContext("(", false), - parenExpression: new TokContext("(", true), - template: new TokContext("`", true, true, function (p) { - return p.readTmplToken(); - }), - functionExpression: new TokContext("function", true) -}; - -// Token-specific context update code - -types.parenR.updateContext = types.braceR.updateContext = function () { - if (this.state.context.length === 1) { - this.state.exprAllowed = true; - return; - } - - var out = this.state.context.pop(); - if (out === types$1.braceStatement && this.curContext() === types$1.functionExpression) { - this.state.context.pop(); - this.state.exprAllowed = false; - } else if (out === types$1.templateQuasi) { - this.state.exprAllowed = true; - } else { - this.state.exprAllowed = !out.isExpr; - } -}; - -types.name.updateContext = function (prevType) { - this.state.exprAllowed = false; - - if (prevType === types._let || prevType === types._const || prevType === types._var) { - if (lineBreak.test(this.input.slice(this.state.end))) { - this.state.exprAllowed = true; - } - } -}; - -types.braceL.updateContext = function (prevType) { - this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); - this.state.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function () { - this.state.context.push(types$1.templateQuasi); - this.state.exprAllowed = true; -}; - -types.parenL.updateContext = function (prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); - this.state.exprAllowed = true; -}; - -types.incDec.updateContext = function () { - // tokExprAllowed stays unchanged -}; - -types._function.updateContext = function () { - if (this.curContext() !== types$1.braceStatement) { - this.state.context.push(types$1.functionExpression); - } - - this.state.exprAllowed = false; -}; - -types.backQuote.updateContext = function () { - if (this.curContext() === types$1.template) { - this.state.context.pop(); - } else { - this.state.context.push(types$1.template); - } - this.state.exprAllowed = false; -}; - -// These are used when `options.locations` is on, for the -// `startLoc` and `endLoc` properties. - -var Position = function Position(line, col) { - classCallCheck(this, Position); - - this.line = line; - this.column = col; -}; - -var SourceLocation = function SourceLocation(start, end) { - classCallCheck(this, SourceLocation); - - this.start = start; - this.end = end; -}; - -// The `getLineInfo` function is mostly useful when the -// `locations` option is off (for performance reasons) and you -// want to find the line/column position for a given character -// offset. `input` should be the code string that the offset refers -// into. - -function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur); - } - } -} - -var State = function () { - function State() { - classCallCheck(this, State); - } - - State.prototype.init = function init(options, input) { - this.strict = options.strictMode === false ? false : options.sourceType === "module"; - - this.input = input; - - this.potentialArrowAt = -1; - - this.inMethod = this.inFunction = this.inGenerator = this.inAsync = this.inPropertyName = this.inType = this.inClassProperty = this.noAnonFunctionType = false; - - this.labels = []; - - this.decorators = []; - - this.tokens = []; - - this.comments = []; - - this.trailingComments = []; - this.leadingComments = []; - this.commentStack = []; - - this.pos = this.lineStart = 0; - this.curLine = options.startLine; - - this.type = types.eof; - this.value = null; - this.start = this.end = this.pos; - this.startLoc = this.endLoc = this.curPosition(); - - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; - - this.context = [types$1.braceStatement]; - this.exprAllowed = true; - - this.containsEsc = this.containsOctal = false; - this.octalPosition = null; - - this.invalidTemplateEscapePosition = null; - - this.exportedIdentifiers = []; - - return this; - }; - - // TODO - - - // TODO - - - // Used to signify the start of a potential arrow function - - - // Flags to track whether we are in a function, a generator. - - - // Labels in scope. - - - // Leading decorators. - - - // Token store. - - - // Comment store. - - - // Comment attachment store - - - // The current position of the tokenizer in the input. - - - // Properties of the current token: - // Its type - - - // For tokens that include more information than their type, the value - - - // Its start and end offset - - - // And, if locations are used, the {line, column} object - // corresponding to those offsets - - - // Position information for the previous token - - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - - - // TODO - - - // Names of exports store. `default` is stored as a name for both - // `export default foo;` and `export { foo as default };`. - - - State.prototype.curPosition = function curPosition() { - return new Position(this.curLine, this.pos - this.lineStart); - }; - - State.prototype.clone = function clone(skipArrays) { - var state = new State(); - for (var key in this) { - var val = this[key]; - - if ((!skipArrays || key === "context") && Array.isArray(val)) { - val = val.slice(); - } - - state[key] = val; - } - return state; - }; - - return State; -}(); - -// Object type used to represent tokens. Note that normally, tokens -// simply exist as properties on the parser object. This is only -// used for the onToken callback and the external tokenizer. - -var Token = function Token(state) { - classCallCheck(this, Token); - - this.type = state.type; - this.value = state.value; - this.start = state.start; - this.end = state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); -}; - -// ## Tokenizer - -function codePointToString(code) { - // UTF-16 Decoding - if (code <= 0xFFFF) { - return String.fromCharCode(code); - } else { - return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00); - } -} - -var Tokenizer = function () { - function Tokenizer(options, input) { - classCallCheck(this, Tokenizer); - - this.state = new State(); - this.state.init(options, input); - } - - // Move to the next token - - Tokenizer.prototype.next = function next() { - if (!this.isLookahead) { - this.state.tokens.push(new Token(this.state)); - } - - this.state.lastTokEnd = this.state.end; - this.state.lastTokStart = this.state.start; - this.state.lastTokEndLoc = this.state.endLoc; - this.state.lastTokStartLoc = this.state.startLoc; - this.nextToken(); - }; - - // TODO - - Tokenizer.prototype.eat = function eat(type) { - if (this.match(type)) { - this.next(); - return true; - } else { - return false; - } - }; - - // TODO - - Tokenizer.prototype.match = function match(type) { - return this.state.type === type; - }; - - // TODO - - Tokenizer.prototype.isKeyword = function isKeyword$$1(word) { - return isKeyword(word); - }; - - // TODO - - Tokenizer.prototype.lookahead = function lookahead() { - var old = this.state; - this.state = old.clone(true); - - this.isLookahead = true; - this.next(); - this.isLookahead = false; - - var curr = this.state.clone(true); - this.state = old; - return curr; - }; - - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - Tokenizer.prototype.setStrict = function setStrict(strict) { - this.state.strict = strict; - if (!this.match(types.num) && !this.match(types.string)) return; - this.state.pos = this.state.start; - while (this.state.pos < this.state.lineStart) { - this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; - --this.state.curLine; - } - this.nextToken(); - }; - - Tokenizer.prototype.curContext = function curContext() { - return this.state.context[this.state.context.length - 1]; - }; - - // Read a single token, updating the parser object's token-related - // properties. - - Tokenizer.prototype.nextToken = function nextToken() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) this.skipSpace(); - - this.state.containsOctal = false; - this.state.octalPosition = null; - this.state.start = this.state.pos; - this.state.startLoc = this.state.curPosition(); - if (this.state.pos >= this.input.length) return this.finishToken(types.eof); - - if (curContext.override) { - return curContext.override(this); - } else { - return this.readToken(this.fullCharCodeAtPos()); - } - }; - - Tokenizer.prototype.readToken = function readToken(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code) || code === 92 /* '\' */) { - return this.readWord(); - } else { - return this.getTokenFromCode(code); - } - }; - - Tokenizer.prototype.fullCharCodeAtPos = function fullCharCodeAtPos() { - var code = this.input.charCodeAt(this.state.pos); - if (code <= 0xd7ff || code >= 0xe000) return code; - - var next = this.input.charCodeAt(this.state.pos + 1); - return (code << 10) + next - 0x35fdc00; - }; - - Tokenizer.prototype.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "CommentBlock" : "CommentLine", - value: text, - start: start, - end: end, - loc: new SourceLocation(startLoc, endLoc) - }; - - if (!this.isLookahead) { - this.state.tokens.push(comment); - this.state.comments.push(comment); - this.addComment(comment); - } - }; - - Tokenizer.prototype.skipBlockComment = function skipBlockComment() { - var startLoc = this.state.curPosition(); - var start = this.state.pos; - var end = this.input.indexOf("*/", this.state.pos += 2); - if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); - - this.state.pos = end + 2; - lineBreakG.lastIndex = start; - var match = void 0; - while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { - ++this.state.curLine; - this.state.lineStart = match.index + match[0].length; - } - - this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); - }; - - Tokenizer.prototype.skipLineComment = function skipLineComment(startSkip) { - var start = this.state.pos; - var startLoc = this.state.curPosition(); - var ch = this.input.charCodeAt(this.state.pos += startSkip); - while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++this.state.pos; - ch = this.input.charCodeAt(this.state.pos); - } - - this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); - }; - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - Tokenizer.prototype.skipSpace = function skipSpace() { - loop: while (this.state.pos < this.input.length) { - var ch = this.input.charCodeAt(this.state.pos); - switch (ch) { - case 32:case 160: - // ' ' - ++this.state.pos; - break; - - case 13: - if (this.input.charCodeAt(this.state.pos + 1) === 10) { - ++this.state.pos; - } - - case 10:case 8232:case 8233: - ++this.state.pos; - ++this.state.curLine; - this.state.lineStart = this.state.pos; - break; - - case 47: - // '/' - switch (this.input.charCodeAt(this.state.pos + 1)) { - case 42: - // '*' - this.skipBlockComment(); - break; - - case 47: - this.skipLineComment(2); - break; - - default: - break loop; - } - break; - - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.state.pos; - } else { - break loop; - } - } - } - }; - - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. - - Tokenizer.prototype.finishToken = function finishToken(type, val) { - this.state.end = this.state.pos; - this.state.endLoc = this.state.curPosition(); - var prevType = this.state.type; - this.state.type = type; - this.state.value = val; - - this.updateContext(prevType); - }; - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - - - Tokenizer.prototype.readToken_dot = function readToken_dot() { - var next = this.input.charCodeAt(this.state.pos + 1); - if (next >= 48 && next <= 57) { - return this.readNumber(true); - } - - var next2 = this.input.charCodeAt(this.state.pos + 2); - if (next === 46 && next2 === 46) { - // 46 = dot '.' - this.state.pos += 3; - return this.finishToken(types.ellipsis); - } else { - ++this.state.pos; - return this.finishToken(types.dot); - } - }; - - Tokenizer.prototype.readToken_slash = function readToken_slash() { - // '/' - if (this.state.exprAllowed) { - ++this.state.pos; - return this.readRegexp(); - } - - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.slash, 1); - } - }; - - Tokenizer.prototype.readToken_mult_modulo = function readToken_mult_modulo(code) { - // '%*' - var type = code === 42 ? types.star : types.modulo; - var width = 1; - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === 42) { - // '*' - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = types.exponent; - } - - if (next === 61) { - width++; - type = types.assign; - } - - return this.finishOp(type, width); - }; - - Tokenizer.prototype.readToken_pipe_amp = function readToken_pipe_amp(code) { - // '|&' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === code) return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); - if (next === 61) return this.finishOp(types.assign, 2); - if (code === 124 && next === 125 && this.hasPlugin("flow")) return this.finishOp(types.braceBarR, 2); - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); - }; - - Tokenizer.prototype.readToken_caret = function readToken_caret() { - // '^' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.bitwiseXOR, 1); - } - }; - - Tokenizer.prototype.readToken_plus_min = function readToken_plus_min(code) { - // '+-' - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === code) { - if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken(); - } - return this.finishOp(types.incDec, 2); - } - - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.plusMin, 1); - } - }; - - Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) { - // '<>' - var next = this.input.charCodeAt(this.state.pos + 1); - var size = 1; - - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(types.assign, size + 1); - return this.finishOp(types.bitShift, size); - } - - if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { - if (this.inModule) this.unexpected(); - // ` regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - - this.debug(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) - - this.debug(this.pattern, set) - - this.set = set -} - -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - - if (options.nonegate) return - - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} - -Minimatch.prototype.braceExpand = braceExpand - -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } - - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - return expand(pattern) -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } - - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter - - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} - -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} - -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} - -},{"brace-expansion":158,"path":522}],520:[function(require,module,exports){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -},{}],521:[function(require,module,exports){ -'use strict'; -module.exports = Number.isNaN || function (x) { - return x !== x; -}; - -},{}],522:[function(require,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; - - -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; - -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; - -}).call(this,require('_process')) -},{"_process":525}],523:[function(require,module,exports){ -(function (process){ -'use strict'; - -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; - -}).call(this,require('_process')) -},{"_process":525}],524:[function(require,module,exports){ -"use strict"; - -var originalObject = Object; -var originalDefProp = Object.defineProperty; -var originalCreate = Object.create; - -function defProp(obj, name, value) { - if (originalDefProp) try { - originalDefProp.call(originalObject, obj, name, { value: value }); - } catch (definePropertyIsBrokenInIE8) { - obj[name] = value; - } else { - obj[name] = value; - } -} - -// For functions that will be invoked using .call or .apply, we need to -// define those methods on the function objects themselves, rather than -// inheriting them from Function.prototype, so that a malicious or clumsy -// third party cannot interfere with the functionality of this module by -// redefining Function.prototype.call or .apply. -function makeSafeToCall(fun) { - if (fun) { - defProp(fun, "call", fun.call); - defProp(fun, "apply", fun.apply); - } - return fun; -} - -makeSafeToCall(originalDefProp); -makeSafeToCall(originalCreate); - -var hasOwn = makeSafeToCall(Object.prototype.hasOwnProperty); -var numToStr = makeSafeToCall(Number.prototype.toString); -var strSlice = makeSafeToCall(String.prototype.slice); - -var cloner = function(){}; -function create(prototype) { - if (originalCreate) { - return originalCreate.call(originalObject, prototype); - } - cloner.prototype = prototype || null; - return new cloner; -} - -var rand = Math.random; -var uniqueKeys = create(null); - -function makeUniqueKey() { - // Collisions are highly unlikely, but this module is in the business of - // making guarantees rather than safe bets. - do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2)); - while (hasOwn.call(uniqueKeys, uniqueKey)); - return uniqueKeys[uniqueKey] = uniqueKey; -} - -function internString(str) { - var obj = {}; - obj[str] = true; - return Object.keys(obj)[0]; -} - -// External users might find this function useful, but it is not necessary -// for the typical use of this module. -exports.makeUniqueKey = makeUniqueKey; - -// Object.getOwnPropertyNames is the only way to enumerate non-enumerable -// properties, so if we wrap it to ignore our secret keys, there should be -// no way (except guessing) to access those properties. -var originalGetOPNs = Object.getOwnPropertyNames; -Object.getOwnPropertyNames = function getOwnPropertyNames(object) { - for (var names = originalGetOPNs(object), - src = 0, - dst = 0, - len = names.length; - src < len; - ++src) { - if (!hasOwn.call(uniqueKeys, names[src])) { - if (src > dst) { - names[dst] = names[src]; - } - ++dst; - } - } - names.length = dst; - return names; -}; - -function defaultCreatorFn(object) { - return create(null); -} - -function makeAccessor(secretCreatorFn) { - var brand = makeUniqueKey(); - var passkey = create(null); - - secretCreatorFn = secretCreatorFn || defaultCreatorFn; - - function register(object) { - var secret; // Created lazily. - - function vault(key, forget) { - // Only code that has access to the passkey can retrieve (or forget) - // the secret object. - if (key === passkey) { - return forget - ? secret = null - : secret || (secret = secretCreatorFn(object)); - } - } - - defProp(object, brand, vault); - } - - function accessor(object) { - if (!hasOwn.call(object, brand)) - register(object); - return object[brand](passkey); - } - - accessor.forget = function(object) { - if (hasOwn.call(object, brand)) - object[brand](passkey, true); - }; - - return accessor; -} - -exports.makeAccessor = makeAccessor; - -},{}],525:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],526:[function(require,module,exports){ -(function (global){ -/*! https://mths.be/regenerate v1.3.3 by @mathias | MIT license */ -;(function(root) { - - // Detect free variables `exports`. - var freeExports = typeof exports == 'object' && exports; - - // Detect free variable `module`. - var freeModule = typeof module == 'object' && module && - module.exports == freeExports && module; - - // Detect free variable `global`, from Node.js/io.js or Browserified code, - // and use it as `root`. - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - var ERRORS = { - 'rangeOrder': 'A range\u2019s `stop` value must be greater than or equal ' + - 'to the `start` value.', - 'codePointRange': 'Invalid code point value. Code points range from ' + - 'U+000000 to U+10FFFF.' - }; - - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs - var HIGH_SURROGATE_MIN = 0xD800; - var HIGH_SURROGATE_MAX = 0xDBFF; - var LOW_SURROGATE_MIN = 0xDC00; - var LOW_SURROGATE_MAX = 0xDFFF; - - // In Regenerate output, `\0` is never preceded by `\` because we sort by - // code point value, so let’s keep this regular expression simple. - var regexNull = /\\x00([^0123456789]|$)/g; - - var object = {}; - var hasOwnProperty = object.hasOwnProperty; - var extend = function(destination, source) { - var key; - for (key in source) { - if (hasOwnProperty.call(source, key)) { - destination[key] = source[key]; - } - } - return destination; - }; - - var forEach = function(array, callback) { - var index = -1; - var length = array.length; - while (++index < length) { - callback(array[index], index); - } - }; - - var toString = object.toString; - var isArray = function(value) { - return toString.call(value) == '[object Array]'; - }; - var isNumber = function(value) { - return typeof value == 'number' || - toString.call(value) == '[object Number]'; - }; - - // This assumes that `number` is a positive integer that `toString()`s nicely - // (which is the case for all code point values). - var zeroes = '0000'; - var pad = function(number, totalCharacters) { - var string = String(number); - return string.length < totalCharacters - ? (zeroes + string).slice(-totalCharacters) - : string; - }; - - var hex = function(number) { - return Number(number).toString(16).toUpperCase(); - }; - - var slice = [].slice; - - /*--------------------------------------------------------------------------*/ - - var dataFromCodePoints = function(codePoints) { - var index = -1; - var length = codePoints.length; - var max = length - 1; - var result = []; - var isStart = true; - var tmp; - var previous = 0; - while (++index < length) { - tmp = codePoints[index]; - if (isStart) { - result.push(tmp); - previous = tmp; - isStart = false; - } else { - if (tmp == previous + 1) { - if (index != max) { - previous = tmp; - continue; - } else { - isStart = true; - result.push(tmp + 1); - } - } else { - // End the previous range and start a new one. - result.push(previous + 1, tmp); - previous = tmp; - } - } - } - if (!isStart) { - result.push(tmp + 1); - } - return result; - }; - - var dataRemove = function(data, codePoint) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1]; - if (codePoint >= start && codePoint < end) { - // Modify this pair. - if (codePoint == start) { - if (end == start + 1) { - // Just remove `start` and `end`. - data.splice(index, 2); - return data; - } else { - // Just replace `start` with a new value. - data[index] = codePoint + 1; - return data; - } - } else if (codePoint == end - 1) { - // Just replace `end` with a new value. - data[index + 1] = codePoint; - return data; - } else { - // Replace `[start, end]` with `[startA, endA, startB, endB]`. - data.splice(index, 2, start, codePoint, codePoint + 1, end); - return data; - } - } - index += 2; - } - return data; - }; - - var dataRemoveRange = function(data, rangeStart, rangeEnd) { - if (rangeEnd < rangeStart) { - throw Error(ERRORS.rangeOrder); - } - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - while (index < data.length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - - // Exit as soon as no more matching pairs can be found. - if (start > rangeEnd) { - return data; - } - - // Check if this range pair is equal to, or forms a subset of, the range - // to be removed. - // E.g. we have `[0, 11, 40, 51]` and want to remove 0-10 → `[40, 51]`. - // E.g. we have `[40, 51]` and want to remove 0-100 → `[]`. - if (rangeStart <= start && rangeEnd >= end) { - // Remove this pair. - data.splice(index, 2); - continue; - } - - // Check if both `rangeStart` and `rangeEnd` are within the bounds of - // this pair. - // E.g. we have `[0, 11]` and want to remove 4-6 → `[0, 4, 7, 11]`. - if (rangeStart >= start && rangeEnd < end) { - if (rangeStart == start) { - // Replace `[start, end]` with `[startB, endB]`. - data[index] = rangeEnd + 1; - data[index + 1] = end + 1; - return data; - } - // Replace `[start, end]` with `[startA, endA, startB, endB]`. - data.splice(index, 2, start, rangeStart, rangeEnd + 1, end + 1); - return data; - } - - // Check if only `rangeStart` is within the bounds of this pair. - // E.g. we have `[0, 11]` and want to remove 4-20 → `[0, 4]`. - if (rangeStart >= start && rangeStart <= end) { - // Replace `end` with `rangeStart`. - data[index + 1] = rangeStart; - // Note: we cannot `return` just yet, in case any following pairs still - // contain matching code points. - // E.g. we have `[0, 11, 14, 31]` and want to remove 4-20 - // → `[0, 4, 21, 31]`. - } - - // Check if only `rangeEnd` is within the bounds of this pair. - // E.g. we have `[14, 31]` and want to remove 4-20 → `[21, 31]`. - else if (rangeEnd >= start && rangeEnd <= end) { - // Just replace `start`. - data[index] = rangeEnd + 1; - return data; - } - - index += 2; - } - return data; - }; - - var dataAdd = function(data, codePoint) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var lastIndex = null; - var length = data.length; - if (codePoint < 0x0 || codePoint > 0x10FFFF) { - throw RangeError(ERRORS.codePointRange); - } - while (index < length) { - start = data[index]; - end = data[index + 1]; - - // Check if the code point is already in the set. - if (codePoint >= start && codePoint < end) { - return data; - } - - if (codePoint == start - 1) { - // Just replace `start` with a new value. - data[index] = codePoint; - return data; - } - - // At this point, if `start` is `greater` than `codePoint`, insert a new - // `[start, end]` pair before the current pair, or after the current pair - // if there is a known `lastIndex`. - if (start > codePoint) { - data.splice( - lastIndex != null ? lastIndex + 2 : 0, - 0, - codePoint, - codePoint + 1 - ); - return data; - } - - if (codePoint == end) { - // Check if adding this code point causes two separate ranges to become - // a single range, e.g. `dataAdd([0, 4, 5, 10], 4)` → `[0, 10]`. - if (codePoint + 1 == data[index + 2]) { - data.splice(index, 4, start, data[index + 3]); - return data; - } - // Else, just replace `end` with a new value. - data[index + 1] = codePoint + 1; - return data; - } - lastIndex = index; - index += 2; - } - // The loop has finished; add the new pair to the end of the data set. - data.push(codePoint, codePoint + 1); - return data; - }; - - var dataAddData = function(dataA, dataB) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var data = dataA.slice(); - var length = dataB.length; - while (index < length) { - start = dataB[index]; - end = dataB[index + 1] - 1; - if (start == end) { - data = dataAdd(data, start); - } else { - data = dataAddRange(data, start, end); - } - index += 2; - } - return data; - }; - - var dataRemoveData = function(dataA, dataB) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var data = dataA.slice(); - var length = dataB.length; - while (index < length) { - start = dataB[index]; - end = dataB[index + 1] - 1; - if (start == end) { - data = dataRemove(data, start); - } else { - data = dataRemoveRange(data, start, end); - } - index += 2; - } - return data; - }; - - var dataAddRange = function(data, rangeStart, rangeEnd) { - if (rangeEnd < rangeStart) { - throw Error(ERRORS.rangeOrder); - } - if ( - rangeStart < 0x0 || rangeStart > 0x10FFFF || - rangeEnd < 0x0 || rangeEnd > 0x10FFFF - ) { - throw RangeError(ERRORS.codePointRange); - } - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var added = false; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1]; - - if (added) { - // The range has already been added to the set; at this point, we just - // need to get rid of the following ranges in case they overlap. - - // Check if this range can be combined with the previous range. - if (start == rangeEnd + 1) { - data.splice(index - 1, 2); - return data; - } - - // Exit as soon as no more possibly overlapping pairs can be found. - if (start > rangeEnd) { - return data; - } - - // E.g. `[0, 11, 12, 16]` and we’ve added 5-15, so we now have - // `[0, 16, 12, 16]`. Remove the `12,16` part, as it lies within the - // `0,16` range that was previously added. - if (start >= rangeStart && start <= rangeEnd) { - // `start` lies within the range that was previously added. - - if (end > rangeStart && end - 1 <= rangeEnd) { - // `end` lies within the range that was previously added as well, - // so remove this pair. - data.splice(index, 2); - index -= 2; - // Note: we cannot `return` just yet, as there may still be other - // overlapping pairs. - } else { - // `start` lies within the range that was previously added, but - // `end` doesn’t. E.g. `[0, 11, 12, 31]` and we’ve added 5-15, so - // now we have `[0, 16, 12, 31]`. This must be written as `[0, 31]`. - // Remove the previously added `end` and the current `start`. - data.splice(index - 1, 2); - index -= 2; - } - - // Note: we cannot return yet. - } - - } - - else if (start == rangeEnd + 1) { - data[index] = rangeStart; - return data; - } - - // Check if a new pair must be inserted *before* the current one. - else if (start > rangeEnd) { - data.splice(index, 0, rangeStart, rangeEnd + 1); - return data; - } - - else if (rangeStart >= start && rangeStart < end && rangeEnd + 1 <= end) { - // The new range lies entirely within an existing range pair. No action - // needed. - return data; - } - - else if ( - // E.g. `[0, 11]` and you add 5-15 → `[0, 16]`. - (rangeStart >= start && rangeStart < end) || - // E.g. `[0, 3]` and you add 3-6 → `[0, 7]`. - end == rangeStart - ) { - // Replace `end` with the new value. - data[index + 1] = rangeEnd + 1; - // Make sure the next range pair doesn’t overlap, e.g. `[0, 11, 12, 14]` - // and you add 5-15 → `[0, 16]`, i.e. remove the `12,14` part. - added = true; - // Note: we cannot `return` just yet. - } - - else if (rangeStart <= start && rangeEnd + 1 >= end) { - // The new range is a superset of the old range. - data[index] = rangeStart; - data[index + 1] = rangeEnd + 1; - added = true; - } - - index += 2; - } - // The loop has finished without doing anything; add the new pair to the end - // of the data set. - if (!added) { - data.push(rangeStart, rangeEnd + 1); - } - return data; - }; - - var dataContains = function(data, codePoint) { - var index = 0; - var length = data.length; - // Exit early if `codePoint` is not within `data`’s overall range. - var start = data[index]; - var end = data[length - 1]; - if (length >= 2) { - if (codePoint < start || codePoint > end) { - return false; - } - } - // Iterate over the data per `(start, end)` pair. - while (index < length) { - start = data[index]; - end = data[index + 1]; - if (codePoint >= start && codePoint < end) { - return true; - } - index += 2; - } - return false; - }; - - var dataIntersection = function(data, codePoints) { - var index = 0; - var length = codePoints.length; - var codePoint; - var result = []; - while (index < length) { - codePoint = codePoints[index]; - if (dataContains(data, codePoint)) { - result.push(codePoint); - } - ++index; - } - return dataFromCodePoints(result); - }; - - var dataIsEmpty = function(data) { - return !data.length; - }; - - var dataIsSingleton = function(data) { - // Check if the set only represents a single code point. - return data.length == 2 && data[0] + 1 == data[1]; - }; - - var dataToArray = function(data) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var result = []; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1]; - while (start < end) { - result.push(start); - ++start; - } - index += 2; - } - return result; - }; - - /*--------------------------------------------------------------------------*/ - - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - var floor = Math.floor; - var highSurrogate = function(codePoint) { - return parseInt( - floor((codePoint - 0x10000) / 0x400) + HIGH_SURROGATE_MIN, - 10 - ); - }; - - var lowSurrogate = function(codePoint) { - return parseInt( - (codePoint - 0x10000) % 0x400 + LOW_SURROGATE_MIN, - 10 - ); - }; - - var stringFromCharCode = String.fromCharCode; - var codePointToString = function(codePoint) { - var string; - // https://mathiasbynens.be/notes/javascript-escapes#single - // Note: the `\b` escape sequence for U+0008 BACKSPACE in strings has a - // different meaning in regular expressions (word boundary), so it cannot - // be used here. - if (codePoint == 0x09) { - string = '\\t'; - } - // Note: IE < 9 treats `'\v'` as `'v'`, so avoid using it. - // else if (codePoint == 0x0B) { - // string = '\\v'; - // } - else if (codePoint == 0x0A) { - string = '\\n'; - } - else if (codePoint == 0x0C) { - string = '\\f'; - } - else if (codePoint == 0x0D) { - string = '\\r'; - } - else if (codePoint == 0x5C) { - string = '\\\\'; - } - else if ( - codePoint == 0x24 || - (codePoint >= 0x28 && codePoint <= 0x2B) || - (codePoint >= 0x2D && codePoint <= 0x2F) || - codePoint == 0x3F || - (codePoint >= 0x5B && codePoint <= 0x5E) || - (codePoint >= 0x7B && codePoint <= 0x7D) - ) { - // The code point maps to an unsafe printable ASCII character; - // backslash-escape it. Here’s the list of those symbols: - // - // $()*+-./?[\]^{|} - // - // See #7 for more info. - string = '\\' + stringFromCharCode(codePoint); - } - else if (codePoint >= 0x20 && codePoint <= 0x7E) { - // The code point maps to one of these printable ASCII symbols - // (including the space character): - // - // !"#%&',/0123456789:;<=>@ABCDEFGHIJKLMNO - // PQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~ - // - // These can safely be used directly. - string = stringFromCharCode(codePoint); - } - else if (codePoint <= 0xFF) { - // https://mathiasbynens.be/notes/javascript-escapes#hexadecimal - string = '\\x' + pad(hex(codePoint), 2); - } - else { // `codePoint <= 0xFFFF` holds true. - // https://mathiasbynens.be/notes/javascript-escapes#unicode - string = '\\u' + pad(hex(codePoint), 4); - } - - // There’s no need to account for astral symbols / surrogate pairs here, - // since `codePointToString` is private and only used for BMP code points. - // But if that’s what you need, just add an `else` block with this code: - // - // string = '\\u' + pad(hex(highSurrogate(codePoint)), 4) - // + '\\u' + pad(hex(lowSurrogate(codePoint)), 4); - - return string; - }; - - var codePointToStringUnicode = function(codePoint) { - if (codePoint <= 0xFFFF) { - return codePointToString(codePoint); - } - return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; - }; - - var symbolToCodePoint = function(symbol) { - var length = symbol.length; - var first = symbol.charCodeAt(0); - var second; - if ( - first >= HIGH_SURROGATE_MIN && first <= HIGH_SURROGATE_MAX && - length > 1 // There is a next code unit. - ) { - // `first` is a high surrogate, and there is a next character. Assume - // it’s a low surrogate (else it’s invalid usage of Regenerate anyway). - second = symbol.charCodeAt(1); - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - HIGH_SURROGATE_MIN) * 0x400 + - second - LOW_SURROGATE_MIN + 0x10000; - } - return first; - }; - - var createBMPCharacterClasses = function(data) { - // Iterate over the data per `(start, end)` pair. - var result = ''; - var index = 0; - var start; - var end; - var length = data.length; - if (dataIsSingleton(data)) { - return codePointToString(data[0]); - } - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - if (start == end) { - result += codePointToString(start); - } else if (start + 1 == end) { - result += codePointToString(start) + codePointToString(end); - } else { - result += codePointToString(start) + '-' + codePointToString(end); - } - index += 2; - } - return '[' + result + ']'; - }; - - var createUnicodeCharacterClasses = function(data) { - // Iterate over the data per `(start, end)` pair. - var result = ''; - var index = 0; - var start; - var end; - var length = data.length; - if (dataIsSingleton(data)) { - return codePointToStringUnicode(data[0]); - } - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - if (start == end) { - result += codePointToStringUnicode(start); - } else if (start + 1 == end) { - result += codePointToStringUnicode(start) + codePointToStringUnicode(end); - } else { - result += codePointToStringUnicode(start) + '-' + codePointToStringUnicode(end); - } - index += 2; - } - return '[' + result + ']'; - }; - - var splitAtBMP = function(data) { - // Iterate over the data per `(start, end)` pair. - var loneHighSurrogates = []; - var loneLowSurrogates = []; - var bmp = []; - var astral = []; - var index = 0; - var start; - var end; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - - if (start < HIGH_SURROGATE_MIN) { - - // The range starts and ends before the high surrogate range. - // E.g. (0, 0x10). - if (end < HIGH_SURROGATE_MIN) { - bmp.push(start, end + 1); - } - - // The range starts before the high surrogate range and ends within it. - // E.g. (0, 0xD855). - if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { - bmp.push(start, HIGH_SURROGATE_MIN); - loneHighSurrogates.push(HIGH_SURROGATE_MIN, end + 1); - } - - // The range starts before the high surrogate range and ends in the low - // surrogate range. E.g. (0, 0xDCFF). - if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { - bmp.push(start, HIGH_SURROGATE_MIN); - loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); - } - - // The range starts before the high surrogate range and ends after the - // low surrogate range. E.g. (0, 0x10FFFF). - if (end > LOW_SURROGATE_MAX) { - bmp.push(start, HIGH_SURROGATE_MIN); - loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); - if (end <= 0xFFFF) { - bmp.push(LOW_SURROGATE_MAX + 1, end + 1); - } else { - bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - } - - } else if (start >= HIGH_SURROGATE_MIN && start <= HIGH_SURROGATE_MAX) { - - // The range starts and ends in the high surrogate range. - // E.g. (0xD855, 0xD866). - if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { - loneHighSurrogates.push(start, end + 1); - } - - // The range starts in the high surrogate range and ends in the low - // surrogate range. E.g. (0xD855, 0xDCFF). - if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { - loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); - } - - // The range starts in the high surrogate range and ends after the low - // surrogate range. E.g. (0xD855, 0x10FFFF). - if (end > LOW_SURROGATE_MAX) { - loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); - if (end <= 0xFFFF) { - bmp.push(LOW_SURROGATE_MAX + 1, end + 1); - } else { - bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - } - - } else if (start >= LOW_SURROGATE_MIN && start <= LOW_SURROGATE_MAX) { - - // The range starts and ends in the low surrogate range. - // E.g. (0xDCFF, 0xDDFF). - if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { - loneLowSurrogates.push(start, end + 1); - } - - // The range starts in the low surrogate range and ends after the low - // surrogate range. E.g. (0xDCFF, 0x10FFFF). - if (end > LOW_SURROGATE_MAX) { - loneLowSurrogates.push(start, LOW_SURROGATE_MAX + 1); - if (end <= 0xFFFF) { - bmp.push(LOW_SURROGATE_MAX + 1, end + 1); - } else { - bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - } - - } else if (start > LOW_SURROGATE_MAX && start <= 0xFFFF) { - - // The range starts and ends after the low surrogate range. - // E.g. (0xFFAA, 0x10FFFF). - if (end <= 0xFFFF) { - bmp.push(start, end + 1); - } else { - bmp.push(start, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - - } else { - - // The range starts and ends in the astral range. - astral.push(start, end + 1); - - } - - index += 2; - } - return { - 'loneHighSurrogates': loneHighSurrogates, - 'loneLowSurrogates': loneLowSurrogates, - 'bmp': bmp, - 'astral': astral - }; - }; - - var optimizeSurrogateMappings = function(surrogateMappings) { - var result = []; - var tmpLow = []; - var addLow = false; - var mapping; - var nextMapping; - var highSurrogates; - var lowSurrogates; - var nextHighSurrogates; - var nextLowSurrogates; - var index = -1; - var length = surrogateMappings.length; - while (++index < length) { - mapping = surrogateMappings[index]; - nextMapping = surrogateMappings[index + 1]; - if (!nextMapping) { - result.push(mapping); - continue; - } - highSurrogates = mapping[0]; - lowSurrogates = mapping[1]; - nextHighSurrogates = nextMapping[0]; - nextLowSurrogates = nextMapping[1]; - - // Check for identical high surrogate ranges. - tmpLow = lowSurrogates; - while ( - nextHighSurrogates && - highSurrogates[0] == nextHighSurrogates[0] && - highSurrogates[1] == nextHighSurrogates[1] - ) { - // Merge with the next item. - if (dataIsSingleton(nextLowSurrogates)) { - tmpLow = dataAdd(tmpLow, nextLowSurrogates[0]); - } else { - tmpLow = dataAddRange( - tmpLow, - nextLowSurrogates[0], - nextLowSurrogates[1] - 1 - ); - } - ++index; - mapping = surrogateMappings[index]; - highSurrogates = mapping[0]; - lowSurrogates = mapping[1]; - nextMapping = surrogateMappings[index + 1]; - nextHighSurrogates = nextMapping && nextMapping[0]; - nextLowSurrogates = nextMapping && nextMapping[1]; - addLow = true; - } - result.push([ - highSurrogates, - addLow ? tmpLow : lowSurrogates - ]); - addLow = false; - } - return optimizeByLowSurrogates(result); - }; - - var optimizeByLowSurrogates = function(surrogateMappings) { - if (surrogateMappings.length == 1) { - return surrogateMappings; - } - var index = -1; - var innerIndex = -1; - while (++index < surrogateMappings.length) { - var mapping = surrogateMappings[index]; - var lowSurrogates = mapping[1]; - var lowSurrogateStart = lowSurrogates[0]; - var lowSurrogateEnd = lowSurrogates[1]; - innerIndex = index; // Note: the loop starts at the next index. - while (++innerIndex < surrogateMappings.length) { - var otherMapping = surrogateMappings[innerIndex]; - var otherLowSurrogates = otherMapping[1]; - var otherLowSurrogateStart = otherLowSurrogates[0]; - var otherLowSurrogateEnd = otherLowSurrogates[1]; - if ( - lowSurrogateStart == otherLowSurrogateStart && - lowSurrogateEnd == otherLowSurrogateEnd - ) { - // Add the code points in the other item to this one. - if (dataIsSingleton(otherMapping[0])) { - mapping[0] = dataAdd(mapping[0], otherMapping[0][0]); - } else { - mapping[0] = dataAddRange( - mapping[0], - otherMapping[0][0], - otherMapping[0][1] - 1 - ); - } - // Remove the other, now redundant, item. - surrogateMappings.splice(innerIndex, 1); - --innerIndex; - } - } - } - return surrogateMappings; - }; - - var surrogateSet = function(data) { - // Exit early if `data` is an empty set. - if (!data.length) { - return []; - } - - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var startHigh; - var startLow; - var endHigh; - var endLow; - var surrogateMappings = []; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; - - startHigh = highSurrogate(start); - startLow = lowSurrogate(start); - endHigh = highSurrogate(end); - endLow = lowSurrogate(end); - - var startsWithLowestLowSurrogate = startLow == LOW_SURROGATE_MIN; - var endsWithHighestLowSurrogate = endLow == LOW_SURROGATE_MAX; - var complete = false; - - // Append the previous high-surrogate-to-low-surrogate mappings. - // Step 1: `(startHigh, startLow)` to `(startHigh, LOW_SURROGATE_MAX)`. - if ( - startHigh == endHigh || - startsWithLowestLowSurrogate && endsWithHighestLowSurrogate - ) { - surrogateMappings.push([ - [startHigh, endHigh + 1], - [startLow, endLow + 1] - ]); - complete = true; - } else { - surrogateMappings.push([ - [startHigh, startHigh + 1], - [startLow, LOW_SURROGATE_MAX + 1] - ]); - } - - // Step 2: `(startHigh + 1, LOW_SURROGATE_MIN)` to - // `(endHigh - 1, LOW_SURROGATE_MAX)`. - if (!complete && startHigh + 1 < endHigh) { - if (endsWithHighestLowSurrogate) { - // Combine step 2 and step 3. - surrogateMappings.push([ - [startHigh + 1, endHigh + 1], - [LOW_SURROGATE_MIN, endLow + 1] - ]); - complete = true; - } else { - surrogateMappings.push([ - [startHigh + 1, endHigh], - [LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1] - ]); - } - } - - // Step 3. `(endHigh, LOW_SURROGATE_MIN)` to `(endHigh, endLow)`. - if (!complete) { - surrogateMappings.push([ - [endHigh, endHigh + 1], - [LOW_SURROGATE_MIN, endLow + 1] - ]); - } - - index += 2; - } - - // The format of `surrogateMappings` is as follows: - // - // [ surrogateMapping1, surrogateMapping2 ] - // - // i.e.: - // - // [ - // [ highSurrogates1, lowSurrogates1 ], - // [ highSurrogates2, lowSurrogates2 ] - // ] - return optimizeSurrogateMappings(surrogateMappings); - }; - - var createSurrogateCharacterClasses = function(surrogateMappings) { - var result = []; - forEach(surrogateMappings, function(surrogateMapping) { - var highSurrogates = surrogateMapping[0]; - var lowSurrogates = surrogateMapping[1]; - result.push( - createBMPCharacterClasses(highSurrogates) + - createBMPCharacterClasses(lowSurrogates) - ); - }); - return result.join('|'); - }; - - var createCharacterClassesFromData = function(data, bmpOnly, hasUnicodeFlag) { - if (hasUnicodeFlag) { - return createUnicodeCharacterClasses(data); - } - var result = []; - - var parts = splitAtBMP(data); - var loneHighSurrogates = parts.loneHighSurrogates; - var loneLowSurrogates = parts.loneLowSurrogates; - var bmp = parts.bmp; - var astral = parts.astral; - var hasLoneHighSurrogates = !dataIsEmpty(loneHighSurrogates); - var hasLoneLowSurrogates = !dataIsEmpty(loneLowSurrogates); - - var surrogateMappings = surrogateSet(astral); - - if (bmpOnly) { - bmp = dataAddData(bmp, loneHighSurrogates); - hasLoneHighSurrogates = false; - bmp = dataAddData(bmp, loneLowSurrogates); - hasLoneLowSurrogates = false; - } - - if (!dataIsEmpty(bmp)) { - // The data set contains BMP code points that are not high surrogates - // needed for astral code points in the set. - result.push(createBMPCharacterClasses(bmp)); - } - if (surrogateMappings.length) { - // The data set contains astral code points; append character classes - // based on their surrogate pairs. - result.push(createSurrogateCharacterClasses(surrogateMappings)); - } - // https://gist.github.com/mathiasbynens/bbe7f870208abcfec860 - if (hasLoneHighSurrogates) { - result.push( - createBMPCharacterClasses(loneHighSurrogates) + - // Make sure the high surrogates aren’t part of a surrogate pair. - '(?![\\uDC00-\\uDFFF])' - ); - } - if (hasLoneLowSurrogates) { - result.push( - // It is not possible to accurately assert the low surrogates aren’t - // part of a surrogate pair, since JavaScript regular expressions do - // not support lookbehind. - '(?:[^\\uD800-\\uDBFF]|^)' + - createBMPCharacterClasses(loneLowSurrogates) - ); - } - return result.join('|'); - }; - - /*--------------------------------------------------------------------------*/ - - // `regenerate` can be used as a constructor (and new methods can be added to - // its prototype) but also as a regular function, the latter of which is the - // documented and most common usage. For that reason, it’s not capitalized. - var regenerate = function(value) { - if (arguments.length > 1) { - value = slice.call(arguments); - } - if (this instanceof regenerate) { - this.data = []; - return value ? this.add(value) : this; - } - return (new regenerate).add(value); - }; - - regenerate.version = '1.3.3'; - - var proto = regenerate.prototype; - extend(proto, { - 'add': function(value) { - var $this = this; - if (value == null) { - return $this; - } - if (value instanceof regenerate) { - // Allow passing other Regenerate instances. - $this.data = dataAddData($this.data, value.data); - return $this; - } - if (arguments.length > 1) { - value = slice.call(arguments); - } - if (isArray(value)) { - forEach(value, function(item) { - $this.add(item); - }); - return $this; - } - $this.data = dataAdd( - $this.data, - isNumber(value) ? value : symbolToCodePoint(value) - ); - return $this; - }, - 'remove': function(value) { - var $this = this; - if (value == null) { - return $this; - } - if (value instanceof regenerate) { - // Allow passing other Regenerate instances. - $this.data = dataRemoveData($this.data, value.data); - return $this; - } - if (arguments.length > 1) { - value = slice.call(arguments); - } - if (isArray(value)) { - forEach(value, function(item) { - $this.remove(item); - }); - return $this; - } - $this.data = dataRemove( - $this.data, - isNumber(value) ? value : symbolToCodePoint(value) - ); - return $this; - }, - 'addRange': function(start, end) { - var $this = this; - $this.data = dataAddRange($this.data, - isNumber(start) ? start : symbolToCodePoint(start), - isNumber(end) ? end : symbolToCodePoint(end) - ); - return $this; - }, - 'removeRange': function(start, end) { - var $this = this; - var startCodePoint = isNumber(start) ? start : symbolToCodePoint(start); - var endCodePoint = isNumber(end) ? end : symbolToCodePoint(end); - $this.data = dataRemoveRange( - $this.data, - startCodePoint, - endCodePoint - ); - return $this; - }, - 'intersection': function(argument) { - var $this = this; - // Allow passing other Regenerate instances. - // TODO: Optimize this by writing and using `dataIntersectionData()`. - var array = argument instanceof regenerate ? - dataToArray(argument.data) : - argument; - $this.data = dataIntersection($this.data, array); - return $this; - }, - 'contains': function(codePoint) { - return dataContains( - this.data, - isNumber(codePoint) ? codePoint : symbolToCodePoint(codePoint) - ); - }, - 'clone': function() { - var set = new regenerate; - set.data = this.data.slice(0); - return set; - }, - 'toString': function(options) { - var result = createCharacterClassesFromData( - this.data, - options ? options.bmpOnly : false, - options ? options.hasUnicodeFlag : false - ); - if (!result) { - // For an empty set, return something that can be inserted `/here/` to - // form a valid regular expression. Avoid `(?:)` since that matches the - // empty string. - return '[]'; - } - // Use `\0` instead of `\x00` where possible. - return result.replace(regexNull, '\\0$1'); - }, - 'toRegExp': function(flags) { - var pattern = this.toString( - flags && flags.indexOf('u') != -1 ? - { 'hasUnicodeFlag': true } : - null - ); - return RegExp(pattern, flags || ''); - }, - 'valueOf': function() { // Note: `valueOf` is aliased as `toArray`. - return dataToArray(this.data); - } - }); - - proto.toArray = proto.valueOf; - - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define(function() { - return regenerate; - }); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = regenerate; - } else { // in Narwhal or RingoJS v0.7.0- - freeExports.regenerate = regenerate; - } - } else { // in Rhino or a web browser - root.regenerate = regenerate; - } - -}(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],527:[function(require,module,exports){ -"use strict"; - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _assert = require("assert"); - -var _assert2 = _interopRequireDefault(_assert); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _leap = require("./leap"); - -var leap = _interopRequireWildcard(_leap); - -var _meta = require("./meta"); - -var meta = _interopRequireWildcard(_meta); - -var _util = require("./util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hasOwn = Object.prototype.hasOwnProperty; /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -function Emitter(contextId) { - _assert2.default.ok(this instanceof Emitter); - t.assertIdentifier(contextId); - - // Used to generate unique temporary names. - this.nextTempId = 0; - - // In order to make sure the context object does not collide with - // anything in the local scope, we might have to rename it, so we - // refer to it symbolically instead of just assuming that it will be - // called "context". - this.contextId = contextId; - - // An append-only list of Statements that grows each time this.emit is - // called. - this.listing = []; - - // A sparse array whose keys correspond to locations in this.listing - // that have been marked as branch/jump targets. - this.marked = [true]; - - // The last location will be marked when this.getDispatchLoop is - // called. - this.finalLoc = loc(); - - // A list of all leap.TryEntry statements emitted. - this.tryEntries = []; - - // Each time we evaluate the body of a loop, we tell this.leapManager - // to enter a nested loop context that determines the meaning of break - // and continue statements therein. - this.leapManager = new leap.LeapManager(this); -} - -var Ep = Emitter.prototype; -exports.Emitter = Emitter; - -// Offsets into this.listing that could be used as targets for branches or -// jumps are represented as numeric Literal nodes. This representation has -// the amazingly convenient benefit of allowing the exact value of the -// location to be determined at any time, even after generating code that -// refers to the location. -function loc() { - return t.numericLiteral(-1); -} - -// Sets the exact value of the given location to the offset of the next -// Statement emitted. -Ep.mark = function (loc) { - t.assertLiteral(loc); - var index = this.listing.length; - if (loc.value === -1) { - loc.value = index; - } else { - // Locations can be marked redundantly, but their values cannot change - // once set the first time. - _assert2.default.strictEqual(loc.value, index); - } - this.marked[index] = true; - return loc; -}; - -Ep.emit = function (node) { - if (t.isExpression(node)) { - node = t.expressionStatement(node); - } - - t.assertStatement(node); - this.listing.push(node); -}; - -// Shorthand for emitting assignment statements. This will come in handy -// for assignments to temporary variables. -Ep.emitAssign = function (lhs, rhs) { - this.emit(this.assign(lhs, rhs)); - return lhs; -}; - -// Shorthand for an assignment statement. -Ep.assign = function (lhs, rhs) { - return t.expressionStatement(t.assignmentExpression("=", lhs, rhs)); -}; - -// Convenience function for generating expressions like context.next, -// context.sent, and context.rval. -Ep.contextProperty = function (name, computed) { - return t.memberExpression(this.contextId, computed ? t.stringLiteral(name) : t.identifier(name), !!computed); -}; - -// Shorthand for setting context.rval and jumping to `context.stop()`. -Ep.stop = function (rval) { - if (rval) { - this.setReturnValue(rval); - } - - this.jump(this.finalLoc); -}; - -Ep.setReturnValue = function (valuePath) { - t.assertExpression(valuePath.value); - - this.emitAssign(this.contextProperty("rval"), this.explodeExpression(valuePath)); -}; - -Ep.clearPendingException = function (tryLoc, assignee) { - t.assertLiteral(tryLoc); - - var catchCall = t.callExpression(this.contextProperty("catch", true), [tryLoc]); - - if (assignee) { - this.emitAssign(assignee, catchCall); - } else { - this.emit(catchCall); - } -}; - -// Emits code for an unconditional jump to the given location, even if the -// exact value of the location is not yet known. -Ep.jump = function (toLoc) { - this.emitAssign(this.contextProperty("next"), toLoc); - this.emit(t.breakStatement()); -}; - -// Conditional jump. -Ep.jumpIf = function (test, toLoc) { - t.assertExpression(test); - t.assertLiteral(toLoc); - - this.emit(t.ifStatement(test, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); -}; - -// Conditional jump, with the condition negated. -Ep.jumpIfNot = function (test, toLoc) { - t.assertExpression(test); - t.assertLiteral(toLoc); - - var negatedTest = void 0; - if (t.isUnaryExpression(test) && test.operator === "!") { - // Avoid double negation. - negatedTest = test.argument; - } else { - negatedTest = t.unaryExpression("!", test); - } - - this.emit(t.ifStatement(negatedTest, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); -}; - -// Returns a unique MemberExpression that can be used to store and -// retrieve temporary values. Since the object of the member expression is -// the context object, which is presumed to coexist peacefully with all -// other local variables, and since we just increment `nextTempId` -// monotonically, uniqueness is assured. -Ep.makeTempVar = function () { - return this.contextProperty("t" + this.nextTempId++); -}; - -Ep.getContextFunction = function (id) { - return t.functionExpression(id || null /*Anonymous*/ - , [this.contextId], t.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! - false // Nor an expression. - ); -}; - -// Turns this.listing into a loop of the form -// -// while (1) switch (context.next) { -// case 0: -// ... -// case n: -// return context.stop(); -// } -// -// Each marked location in this.listing will correspond to one generated -// case statement. -Ep.getDispatchLoop = function () { - var self = this; - var cases = []; - var current = void 0; - - // If we encounter a break, continue, or return statement in a switch - // case, we can skip the rest of the statements until the next case. - var alreadyEnded = false; - - self.listing.forEach(function (stmt, i) { - if (self.marked.hasOwnProperty(i)) { - cases.push(t.switchCase(t.numericLiteral(i), current = [])); - alreadyEnded = false; - } - - if (!alreadyEnded) { - current.push(stmt); - if (t.isCompletionStatement(stmt)) alreadyEnded = true; - } - }); - - // Now that we know how many statements there will be in this.listing, - // we can finally resolve this.finalLoc.value. - this.finalLoc.value = this.listing.length; - - cases.push(t.switchCase(this.finalLoc, [ - // Intentionally fall through to the "end" case... - ]), - - // So that the runtime can jump to the final location without having - // to know its offset, we provide the "end" case as a synonym. - t.switchCase(t.stringLiteral("end"), [ - // This will check/clear both context.thrown and context.rval. - t.returnStatement(t.callExpression(this.contextProperty("stop"), []))])); - - return t.whileStatement(t.numericLiteral(1), t.switchStatement(t.assignmentExpression("=", this.contextProperty("prev"), this.contextProperty("next")), cases)); -}; - -Ep.getTryLocsList = function () { - if (this.tryEntries.length === 0) { - // To avoid adding a needless [] to the majority of runtime.wrap - // argument lists, force the caller to handle this case specially. - return null; - } - - var lastLocValue = 0; - - return t.arrayExpression(this.tryEntries.map(function (tryEntry) { - var thisLocValue = tryEntry.firstLoc.value; - _assert2.default.ok(thisLocValue >= lastLocValue, "try entries out of order"); - lastLocValue = thisLocValue; - - var ce = tryEntry.catchEntry; - var fe = tryEntry.finallyEntry; - - var locs = [tryEntry.firstLoc, - // The null here makes a hole in the array. - ce ? ce.firstLoc : null]; - - if (fe) { - locs[2] = fe.firstLoc; - locs[3] = fe.afterLoc; - } - - return t.arrayExpression(locs); - })); -}; - -// All side effects must be realized in order. - -// If any subexpression harbors a leap, all subexpressions must be -// neutered of side effects. - -// No destructive modification of AST nodes. - -Ep.explode = function (path, ignoreResult) { - var node = path.node; - var self = this; - - t.assertNode(node); - - if (t.isDeclaration(node)) throw getDeclError(node); - - if (t.isStatement(node)) return self.explodeStatement(path); - - if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); - - switch (node.type) { - case "Program": - return path.get("body").map(self.explodeStatement, self); - - case "VariableDeclarator": - throw getDeclError(node); - - // These node types should be handled by their parent nodes - // (ObjectExpression, SwitchStatement, and TryStatement, respectively). - case "Property": - case "SwitchCase": - case "CatchClause": - throw new Error(node.type + " nodes should be handled by their parents"); - - default: - throw new Error("unknown Node of type " + (0, _stringify2.default)(node.type)); - } -}; - -function getDeclError(node) { - return new Error("all declarations should have been transformed into " + "assignments before the Exploder began its work: " + (0, _stringify2.default)(node)); -} - -Ep.explodeStatement = function (path, labelId) { - var stmt = path.node; - var self = this; - var before = void 0, - after = void 0, - head = void 0; - - t.assertStatement(stmt); - - if (labelId) { - t.assertIdentifier(labelId); - } else { - labelId = null; - } - - // Explode BlockStatement nodes even if they do not contain a yield, - // because we don't want or need the curly braces. - if (t.isBlockStatement(stmt)) { - path.get("body").forEach(function (path) { - self.explodeStatement(path); - }); - return; - } - - if (!meta.containsLeap(stmt)) { - // Technically we should be able to avoid emitting the statement - // altogether if !meta.hasSideEffects(stmt), but that leads to - // confusing generated code (for instance, `while (true) {}` just - // disappears) and is probably a more appropriate job for a dedicated - // dead code elimination pass. - self.emit(stmt); - return; - } - - switch (stmt.type) { - case "ExpressionStatement": - self.explodeExpression(path.get("expression"), true); - break; - - case "LabeledStatement": - after = loc(); - - // Did you know you can break from any labeled block statement or - // control structure? Well, you can! Note: when a labeled loop is - // encountered, the leap.LabeledEntry created here will immediately - // enclose a leap.LoopEntry on the leap manager's stack, and both - // entries will have the same label. Though this works just fine, it - // may seem a bit redundant. In theory, we could check here to - // determine if stmt knows how to handle its own label; for example, - // stmt happens to be a WhileStatement and so we know it's going to - // establish its own LoopEntry when we explode it (below). Then this - // LabeledEntry would be unnecessary. Alternatively, we might be - // tempted not to pass stmt.label down into self.explodeStatement, - // because we've handled the label here, but that's a mistake because - // labeled loops may contain labeled continue statements, which is not - // something we can handle in this generic case. All in all, I think a - // little redundancy greatly simplifies the logic of this case, since - // it's clear that we handle all possible LabeledStatements correctly - // here, regardless of whether they interact with the leap manager - // themselves. Also remember that labels and break/continue-to-label - // statements are rare, and all of this logic happens at transform - // time, so it has no additional runtime cost. - self.leapManager.withEntry(new leap.LabeledEntry(after, stmt.label), function () { - self.explodeStatement(path.get("body"), stmt.label); - }); - - self.mark(after); - - break; - - case "WhileStatement": - before = loc(); - after = loc(); - - self.mark(before); - self.jumpIfNot(self.explodeExpression(path.get("test")), after); - self.leapManager.withEntry(new leap.LoopEntry(after, before, labelId), function () { - self.explodeStatement(path.get("body")); - }); - self.jump(before); - self.mark(after); - - break; - - case "DoWhileStatement": - var first = loc(); - var test = loc(); - after = loc(); - - self.mark(first); - self.leapManager.withEntry(new leap.LoopEntry(after, test, labelId), function () { - self.explode(path.get("body")); - }); - self.mark(test); - self.jumpIf(self.explodeExpression(path.get("test")), first); - self.mark(after); - - break; - - case "ForStatement": - head = loc(); - var update = loc(); - after = loc(); - - if (stmt.init) { - // We pass true here to indicate that if stmt.init is an expression - // then we do not care about its result. - self.explode(path.get("init"), true); - } - - self.mark(head); - - if (stmt.test) { - self.jumpIfNot(self.explodeExpression(path.get("test")), after); - } else { - // No test means continue unconditionally. - } - - self.leapManager.withEntry(new leap.LoopEntry(after, update, labelId), function () { - self.explodeStatement(path.get("body")); - }); - - self.mark(update); - - if (stmt.update) { - // We pass true here to indicate that if stmt.update is an - // expression then we do not care about its result. - self.explode(path.get("update"), true); - } - - self.jump(head); - - self.mark(after); - - break; - - case "TypeCastExpression": - return self.explodeExpression(path.get("expression")); - - case "ForInStatement": - head = loc(); - after = loc(); - - var keyIterNextFn = self.makeTempVar(); - self.emitAssign(keyIterNextFn, t.callExpression(util.runtimeProperty("keys"), [self.explodeExpression(path.get("right"))])); - - self.mark(head); - - var keyInfoTmpVar = self.makeTempVar(); - self.jumpIf(t.memberExpression(t.assignmentExpression("=", keyInfoTmpVar, t.callExpression(keyIterNextFn, [])), t.identifier("done"), false), after); - - self.emitAssign(stmt.left, t.memberExpression(keyInfoTmpVar, t.identifier("value"), false)); - - self.leapManager.withEntry(new leap.LoopEntry(after, head, labelId), function () { - self.explodeStatement(path.get("body")); - }); - - self.jump(head); - - self.mark(after); - - break; - - case "BreakStatement": - self.emitAbruptCompletion({ - type: "break", - target: self.leapManager.getBreakLoc(stmt.label) - }); - - break; - - case "ContinueStatement": - self.emitAbruptCompletion({ - type: "continue", - target: self.leapManager.getContinueLoc(stmt.label) - }); - - break; - - case "SwitchStatement": - // Always save the discriminant into a temporary variable in case the - // test expressions overwrite values like context.sent. - var disc = self.emitAssign(self.makeTempVar(), self.explodeExpression(path.get("discriminant"))); - - after = loc(); - var defaultLoc = loc(); - var condition = defaultLoc; - var caseLocs = []; - - // If there are no cases, .cases might be undefined. - var cases = stmt.cases || []; - - for (var i = cases.length - 1; i >= 0; --i) { - var c = cases[i]; - t.assertSwitchCase(c); - - if (c.test) { - condition = t.conditionalExpression(t.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition); - } else { - caseLocs[i] = defaultLoc; - } - } - - var discriminant = path.get("discriminant"); - util.replaceWithOrRemove(discriminant, condition); - self.jump(self.explodeExpression(discriminant)); - - self.leapManager.withEntry(new leap.SwitchEntry(after), function () { - path.get("cases").forEach(function (casePath) { - var i = casePath.key; - self.mark(caseLocs[i]); - - casePath.get("consequent").forEach(function (path) { - self.explodeStatement(path); - }); - }); - }); - - self.mark(after); - if (defaultLoc.value === -1) { - self.mark(defaultLoc); - _assert2.default.strictEqual(after.value, defaultLoc.value); - } - - break; - - case "IfStatement": - var elseLoc = stmt.alternate && loc(); - after = loc(); - - self.jumpIfNot(self.explodeExpression(path.get("test")), elseLoc || after); - - self.explodeStatement(path.get("consequent")); - - if (elseLoc) { - self.jump(after); - self.mark(elseLoc); - self.explodeStatement(path.get("alternate")); - } - - self.mark(after); - - break; - - case "ReturnStatement": - self.emitAbruptCompletion({ - type: "return", - value: self.explodeExpression(path.get("argument")) - }); - - break; - - case "WithStatement": - throw new Error("WithStatement not supported in generator functions."); - - case "TryStatement": - after = loc(); - - var handler = stmt.handler; - - var catchLoc = handler && loc(); - var catchEntry = catchLoc && new leap.CatchEntry(catchLoc, handler.param); - - var finallyLoc = stmt.finalizer && loc(); - var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); - - var tryEntry = new leap.TryEntry(self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry); - - self.tryEntries.push(tryEntry); - self.updateContextPrevLoc(tryEntry.firstLoc); - - self.leapManager.withEntry(tryEntry, function () { - self.explodeStatement(path.get("block")); - - if (catchLoc) { - if (finallyLoc) { - // If we have both a catch block and a finally block, then - // because we emit the catch block first, we need to jump over - // it to the finally block. - self.jump(finallyLoc); - } else { - // If there is no finally block, then we need to jump over the - // catch block to the fall-through location. - self.jump(after); - } - - self.updateContextPrevLoc(self.mark(catchLoc)); - - var bodyPath = path.get("handler.body"); - var safeParam = self.makeTempVar(); - self.clearPendingException(tryEntry.firstLoc, safeParam); - - bodyPath.traverse(catchParamVisitor, { - safeParam: safeParam, - catchParamName: handler.param.name - }); - - self.leapManager.withEntry(catchEntry, function () { - self.explodeStatement(bodyPath); - }); - } - - if (finallyLoc) { - self.updateContextPrevLoc(self.mark(finallyLoc)); - - self.leapManager.withEntry(finallyEntry, function () { - self.explodeStatement(path.get("finalizer")); - }); - - self.emit(t.returnStatement(t.callExpression(self.contextProperty("finish"), [finallyEntry.firstLoc]))); - } - }); - - self.mark(after); - - break; - - case "ThrowStatement": - self.emit(t.throwStatement(self.explodeExpression(path.get("argument")))); - - break; - - default: - throw new Error("unknown Statement of type " + (0, _stringify2.default)(stmt.type)); - } -}; - -var catchParamVisitor = { - Identifier: function Identifier(path, state) { - if (path.node.name === state.catchParamName && util.isReference(path)) { - util.replaceWithOrRemove(path, state.safeParam); - } - }, - - Scope: function Scope(path, state) { - if (path.scope.hasOwnBinding(state.catchParamName)) { - // Don't descend into nested scopes that shadow the catch - // parameter with their own declarations. - path.skip(); - } - } -}; - -Ep.emitAbruptCompletion = function (record) { - if (!isValidCompletion(record)) { - _assert2.default.ok(false, "invalid completion record: " + (0, _stringify2.default)(record)); - } - - _assert2.default.notStrictEqual(record.type, "normal", "normal completions are not abrupt"); - - var abruptArgs = [t.stringLiteral(record.type)]; - - if (record.type === "break" || record.type === "continue") { - t.assertLiteral(record.target); - abruptArgs[1] = record.target; - } else if (record.type === "return" || record.type === "throw") { - if (record.value) { - t.assertExpression(record.value); - abruptArgs[1] = record.value; - } - } - - this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"), abruptArgs))); -}; - -function isValidCompletion(record) { - var type = record.type; - - if (type === "normal") { - return !hasOwn.call(record, "target"); - } - - if (type === "break" || type === "continue") { - return !hasOwn.call(record, "value") && t.isLiteral(record.target); - } - - if (type === "return" || type === "throw") { - return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); - } - - return false; -} - -// Not all offsets into emitter.listing are potential jump targets. For -// example, execution typically falls into the beginning of a try block -// without jumping directly there. This method returns the current offset -// without marking it, so that a switch case will not necessarily be -// generated for this offset (I say "not necessarily" because the same -// location might end up being marked in the process of emitting other -// statements). There's no logical harm in marking such locations as jump -// targets, but minimizing the number of switch cases keeps the generated -// code shorter. -Ep.getUnmarkedCurrentLoc = function () { - return t.numericLiteral(this.listing.length); -}; - -// The context.prev property takes the value of context.next whenever we -// evaluate the switch statement discriminant, which is generally good -// enough for tracking the last location we jumped to, but sometimes -// context.prev needs to be more precise, such as when we fall -// successfully out of a try block and into a finally block without -// jumping. This method exists to update context.prev to the freshest -// available location. If we were implementing a full interpreter, we -// would know the location of the current instruction with complete -// precision at all times, but we don't have that luxury here, as it would -// be costly and verbose to set context.prev before every statement. -Ep.updateContextPrevLoc = function (loc) { - if (loc) { - t.assertLiteral(loc); - - if (loc.value === -1) { - // If an uninitialized location literal was passed in, set its value - // to the current this.listing.length. - loc.value = this.listing.length; - } else { - // Otherwise assert that the location matches the current offset. - _assert2.default.strictEqual(loc.value, this.listing.length); - } - } else { - loc = this.getUnmarkedCurrentLoc(); - } - - // Make sure context.prev is up to date in case we fell into this try - // statement without jumping to it. TODO Consider avoiding this - // assignment when we know control must have jumped here. - this.emitAssign(this.contextProperty("prev"), loc); -}; - -Ep.explodeExpression = function (path, ignoreResult) { - var expr = path.node; - if (expr) { - t.assertExpression(expr); - } else { - return expr; - } - - var self = this; - var result = void 0; // Used optionally by several cases below. - var after = void 0; - - function finish(expr) { - t.assertExpression(expr); - if (ignoreResult) { - self.emit(expr); - } else { - return expr; - } - } - - // If the expression does not contain a leap, then we either emit the - // expression as a standalone statement or return it whole. - if (!meta.containsLeap(expr)) { - return finish(expr); - } - - // If any child contains a leap (such as a yield or labeled continue or - // break statement), then any sibling subexpressions will almost - // certainly have to be exploded in order to maintain the order of their - // side effects relative to the leaping child(ren). - var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); - - // In order to save the rest of explodeExpression from a combinatorial - // trainwreck of special cases, explodeViaTempVar is responsible for - // deciding when a subexpression needs to be "exploded," which is my - // very technical term for emitting the subexpression as an assignment - // to a temporary variable and the substituting the temporary variable - // for the original subexpression. Think of exploded view diagrams, not - // Michael Bay movies. The point of exploding subexpressions is to - // control the precise order in which the generated code realizes the - // side effects of those subexpressions. - function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { - _assert2.default.ok(!ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?"); - - var result = self.explodeExpression(childPath, ignoreChildResult); - - if (ignoreChildResult) { - // Side effects already emitted above. - - } else if (tempVar || hasLeapingChildren && !t.isLiteral(result)) { - // If tempVar was provided, then the result will always be assigned - // to it, even if the result does not otherwise need to be assigned - // to a temporary variable. When no tempVar is provided, we have - // the flexibility to decide whether a temporary variable is really - // necessary. Unfortunately, in general, a temporary variable is - // required whenever any child contains a yield expression, since it - // is difficult to prove (at all, let alone efficiently) whether - // this result would evaluate to the same value before and after the - // yield (see #206). One narrow case where we can prove it doesn't - // matter (and thus we do not need a temporary variable) is when the - // result in question is a Literal value. - result = self.emitAssign(tempVar || self.makeTempVar(), result); - } - return result; - } - - // If ignoreResult is true, then we must take full responsibility for - // emitting the expression with all its side effects, and we should not - // return a result. - - switch (expr.type) { - case "MemberExpression": - return finish(t.memberExpression(self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed)); - - case "CallExpression": - var calleePath = path.get("callee"); - var argsPath = path.get("arguments"); - - var newCallee = void 0; - var newArgs = []; - - var hasLeapingArgs = false; - argsPath.forEach(function (argPath) { - hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); - }); - - if (t.isMemberExpression(calleePath.node)) { - if (hasLeapingArgs) { - // If the arguments of the CallExpression contained any yield - // expressions, then we need to be sure to evaluate the callee - // before evaluating the arguments, but if the callee was a member - // expression, then we must be careful that the object of the - // member expression still gets bound to `this` for the call. - - var newObject = explodeViaTempVar( - // Assign the exploded callee.object expression to a temporary - // variable so that we can use it twice without reevaluating it. - self.makeTempVar(), calleePath.get("object")); - - var newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; - - newArgs.unshift(newObject); - - newCallee = t.memberExpression(t.memberExpression(newObject, newProperty, calleePath.node.computed), t.identifier("call"), false); - } else { - newCallee = self.explodeExpression(calleePath); - } - } else { - newCallee = explodeViaTempVar(null, calleePath); - - if (t.isMemberExpression(newCallee)) { - // If the callee was not previously a MemberExpression, then the - // CallExpression was "unqualified," meaning its `this` object - // should be the global object. If the exploded expression has - // become a MemberExpression (e.g. a context property, probably a - // temporary variable), then we need to force it to be unqualified - // by using the (0, object.property)(...) trick; otherwise, it - // will receive the object of the MemberExpression as its `this` - // object. - newCallee = t.sequenceExpression([t.numericLiteral(0), newCallee]); - } - } - - argsPath.forEach(function (argPath) { - newArgs.push(explodeViaTempVar(null, argPath)); - }); - - return finish(t.callExpression(newCallee, newArgs)); - - case "NewExpression": - return finish(t.newExpression(explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function (argPath) { - return explodeViaTempVar(null, argPath); - }))); - - case "ObjectExpression": - return finish(t.objectExpression(path.get("properties").map(function (propPath) { - if (propPath.isObjectProperty()) { - return t.objectProperty(propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed); - } else { - return propPath.node; - } - }))); - - case "ArrayExpression": - return finish(t.arrayExpression(path.get("elements").map(function (elemPath) { - return explodeViaTempVar(null, elemPath); - }))); - - case "SequenceExpression": - var lastIndex = expr.expressions.length - 1; - - path.get("expressions").forEach(function (exprPath) { - if (exprPath.key === lastIndex) { - result = self.explodeExpression(exprPath, ignoreResult); - } else { - self.explodeExpression(exprPath, true); - } - }); - - return result; - - case "LogicalExpression": - after = loc(); - - if (!ignoreResult) { - result = self.makeTempVar(); - } - - var left = explodeViaTempVar(result, path.get("left")); - - if (expr.operator === "&&") { - self.jumpIfNot(left, after); - } else { - _assert2.default.strictEqual(expr.operator, "||"); - self.jumpIf(left, after); - } - - explodeViaTempVar(result, path.get("right"), ignoreResult); - - self.mark(after); - - return result; - - case "ConditionalExpression": - var elseLoc = loc(); - after = loc(); - var test = self.explodeExpression(path.get("test")); - - self.jumpIfNot(test, elseLoc); - - if (!ignoreResult) { - result = self.makeTempVar(); - } - - explodeViaTempVar(result, path.get("consequent"), ignoreResult); - self.jump(after); - - self.mark(elseLoc); - explodeViaTempVar(result, path.get("alternate"), ignoreResult); - - self.mark(after); - - return result; - - case "UnaryExpression": - return finish(t.unaryExpression(expr.operator, - // Can't (and don't need to) break up the syntax of the argument. - // Think about delete a[b]. - self.explodeExpression(path.get("argument")), !!expr.prefix)); - - case "BinaryExpression": - return finish(t.binaryExpression(expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")))); - - case "AssignmentExpression": - return finish(t.assignmentExpression(expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")))); - - case "UpdateExpression": - return finish(t.updateExpression(expr.operator, self.explodeExpression(path.get("argument")), expr.prefix)); - - case "YieldExpression": - after = loc(); - var arg = expr.argument && self.explodeExpression(path.get("argument")); - - if (arg && expr.delegate) { - var _result = self.makeTempVar(); - - self.emit(t.returnStatement(t.callExpression(self.contextProperty("delegateYield"), [arg, t.stringLiteral(_result.property.name), after]))); - - self.mark(after); - - return _result; - } - - self.emitAssign(self.contextProperty("next"), after); - self.emit(t.returnStatement(arg || null)); - self.mark(after); - - return self.contextProperty("sent"); - - default: - throw new Error("unknown Expression of type " + (0, _stringify2.default)(expr.type)); - } -}; -},{"./leap":530,"./meta":531,"./util":533,"assert":3,"babel-runtime/core-js/json/stringify":96,"babel-types":151}],528:[function(require,module,exports){ -"use strict"; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _util = require("./util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -var hasOwn = Object.prototype.hasOwnProperty; - -// The hoist function takes a FunctionExpression or FunctionDeclaration -// and replaces any Declaration nodes in its body with assignments, then -// returns a VariableDeclaration containing just the names of the removed -// declarations. -exports.hoist = function (funPath) { - t.assertFunction(funPath.node); - - var vars = {}; - - function varDeclToExpr(vdec, includeIdentifiers) { - t.assertVariableDeclaration(vdec); - // TODO assert.equal(vdec.kind, "var"); - var exprs = []; - - vdec.declarations.forEach(function (dec) { - // Note: We duplicate 'dec.id' here to ensure that the variable declaration IDs don't - // have the same 'loc' value, since that can make sourcemaps and retainLines behave poorly. - vars[dec.id.name] = t.identifier(dec.id.name); - - if (dec.init) { - exprs.push(t.assignmentExpression("=", dec.id, dec.init)); - } else if (includeIdentifiers) { - exprs.push(dec.id); - } - }); - - if (exprs.length === 0) return null; - - if (exprs.length === 1) return exprs[0]; - - return t.sequenceExpression(exprs); - } - - funPath.get("body").traverse({ - VariableDeclaration: { - exit: function exit(path) { - var expr = varDeclToExpr(path.node, false); - if (expr === null) { - path.remove(); - } else { - // We don't need to traverse this expression any further because - // there can't be any new declarations inside an expression. - util.replaceWithOrRemove(path, t.expressionStatement(expr)); - } - - // Since the original node has been either removed or replaced, - // avoid traversing it any further. - path.skip(); - } - }, - - ForStatement: function ForStatement(path) { - var init = path.node.init; - if (t.isVariableDeclaration(init)) { - util.replaceWithOrRemove(path.get("init"), varDeclToExpr(init, false)); - } - }, - - ForXStatement: function ForXStatement(path) { - var left = path.get("left"); - if (left.isVariableDeclaration()) { - util.replaceWithOrRemove(left, varDeclToExpr(left.node, true)); - } - }, - - FunctionDeclaration: function FunctionDeclaration(path) { - var node = path.node; - vars[node.id.name] = node.id; - - var assignment = t.expressionStatement(t.assignmentExpression("=", node.id, t.functionExpression(node.id, node.params, node.body, node.generator, node.expression))); - - if (path.parentPath.isBlockStatement()) { - // Insert the assignment form before the first statement in the - // enclosing block. - path.parentPath.unshiftContainer("body", assignment); - - // Remove the function declaration now that we've inserted the - // equivalent assignment form at the beginning of the block. - path.remove(); - } else { - // If the parent node is not a block statement, then we can just - // replace the declaration with the equivalent assignment form - // without worrying about hoisting it. - util.replaceWithOrRemove(path, assignment); - } - - // Don't hoist variables out of inner functions. - path.skip(); - }, - - FunctionExpression: function FunctionExpression(path) { - // Don't descend into nested function expressions. - path.skip(); - } - }); - - var paramNames = {}; - funPath.get("params").forEach(function (paramPath) { - var param = paramPath.node; - if (t.isIdentifier(param)) { - paramNames[param.name] = param; - } else { - // Variables declared by destructuring parameter patterns will be - // harmlessly re-declared. - } - }); - - var declarations = []; - - (0, _keys2.default)(vars).forEach(function (name) { - if (!hasOwn.call(paramNames, name)) { - declarations.push(t.variableDeclarator(vars[name], null)); - } - }); - - if (declarations.length === 0) { - return null; // Be sure to handle this case! - } - - return t.variableDeclaration("var", declarations); -}; -},{"./util":533,"babel-runtime/core-js/object/keys":102,"babel-types":151}],529:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (context) { - var plugin = { - visitor: require("./visit").visitor - }; - - // Some presets manually call child presets, but fail to pass along the - // context object. Out of an abundance of caution, we verify that it - // exists first to avoid causing unnecessary breaking changes. - var version = context && context.version; - - // The "name" property is not allowed in older versions of Babel (6.x) - // and will cause the plugin validator to throw an exception. - if (version && parseInt(version, 10) >= 7) { - plugin.name = "regenerator-transform"; - } - - return plugin; -}; -},{"./visit":534}],530:[function(require,module,exports){ -"use strict"; - -var _assert = require("assert"); - -var _assert2 = _interopRequireDefault(_assert); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _util = require("util"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function Entry() { - _assert2.default.ok(this instanceof Entry); -} /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -function FunctionEntry(returnLoc) { - Entry.call(this); - t.assertLiteral(returnLoc); - this.returnLoc = returnLoc; -} - -(0, _util.inherits)(FunctionEntry, Entry); -exports.FunctionEntry = FunctionEntry; - -function LoopEntry(breakLoc, continueLoc, label) { - Entry.call(this); - - t.assertLiteral(breakLoc); - t.assertLiteral(continueLoc); - - if (label) { - t.assertIdentifier(label); - } else { - label = null; - } - - this.breakLoc = breakLoc; - this.continueLoc = continueLoc; - this.label = label; -} - -(0, _util.inherits)(LoopEntry, Entry); -exports.LoopEntry = LoopEntry; - -function SwitchEntry(breakLoc) { - Entry.call(this); - t.assertLiteral(breakLoc); - this.breakLoc = breakLoc; -} - -(0, _util.inherits)(SwitchEntry, Entry); -exports.SwitchEntry = SwitchEntry; - -function TryEntry(firstLoc, catchEntry, finallyEntry) { - Entry.call(this); - - t.assertLiteral(firstLoc); - - if (catchEntry) { - _assert2.default.ok(catchEntry instanceof CatchEntry); - } else { - catchEntry = null; - } - - if (finallyEntry) { - _assert2.default.ok(finallyEntry instanceof FinallyEntry); - } else { - finallyEntry = null; - } - - // Have to have one or the other (or both). - _assert2.default.ok(catchEntry || finallyEntry); - - this.firstLoc = firstLoc; - this.catchEntry = catchEntry; - this.finallyEntry = finallyEntry; -} - -(0, _util.inherits)(TryEntry, Entry); -exports.TryEntry = TryEntry; - -function CatchEntry(firstLoc, paramId) { - Entry.call(this); - - t.assertLiteral(firstLoc); - t.assertIdentifier(paramId); - - this.firstLoc = firstLoc; - this.paramId = paramId; -} - -(0, _util.inherits)(CatchEntry, Entry); -exports.CatchEntry = CatchEntry; - -function FinallyEntry(firstLoc, afterLoc) { - Entry.call(this); - t.assertLiteral(firstLoc); - t.assertLiteral(afterLoc); - this.firstLoc = firstLoc; - this.afterLoc = afterLoc; -} - -(0, _util.inherits)(FinallyEntry, Entry); -exports.FinallyEntry = FinallyEntry; - -function LabeledEntry(breakLoc, label) { - Entry.call(this); - - t.assertLiteral(breakLoc); - t.assertIdentifier(label); - - this.breakLoc = breakLoc; - this.label = label; -} - -(0, _util.inherits)(LabeledEntry, Entry); -exports.LabeledEntry = LabeledEntry; - -function LeapManager(emitter) { - _assert2.default.ok(this instanceof LeapManager); - - var Emitter = require("./emit").Emitter; - _assert2.default.ok(emitter instanceof Emitter); - - this.emitter = emitter; - this.entryStack = [new FunctionEntry(emitter.finalLoc)]; -} - -var LMp = LeapManager.prototype; -exports.LeapManager = LeapManager; - -LMp.withEntry = function (entry, callback) { - _assert2.default.ok(entry instanceof Entry); - this.entryStack.push(entry); - try { - callback.call(this.emitter); - } finally { - var popped = this.entryStack.pop(); - _assert2.default.strictEqual(popped, entry); - } -}; - -LMp._findLeapLocation = function (property, label) { - for (var i = this.entryStack.length - 1; i >= 0; --i) { - var entry = this.entryStack[i]; - var loc = entry[property]; - if (loc) { - if (label) { - if (entry.label && entry.label.name === label.name) { - return loc; - } - } else if (entry instanceof LabeledEntry) { - // Ignore LabeledEntry entries unless we are actually breaking to - // a label. - } else { - return loc; - } - } - } - - return null; -}; - -LMp.getBreakLoc = function (label) { - return this._findLeapLocation("breakLoc", label); -}; - -LMp.getContinueLoc = function (label) { - return this._findLeapLocation("continueLoc", label); -}; -},{"./emit":527,"assert":3,"babel-types":151,"util":560}],531:[function(require,module,exports){ -"use strict"; - -var _assert = require("assert"); - -var _assert2 = _interopRequireDefault(_assert); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var m = require("private").makeAccessor(); /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -var hasOwn = Object.prototype.hasOwnProperty; - -function makePredicate(propertyName, knownTypes) { - function onlyChildren(node) { - t.assertNode(node); - - // Assume no side effects until we find out otherwise. - var result = false; - - function check(child) { - if (result) { - // Do nothing. - } else if (Array.isArray(child)) { - child.some(check); - } else if (t.isNode(child)) { - _assert2.default.strictEqual(result, false); - result = predicate(child); - } - return result; - } - - var keys = t.VISITOR_KEYS[node.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = node[key]; - check(child); - } - } - - return result; - } - - function predicate(node) { - t.assertNode(node); - - var meta = m(node); - if (hasOwn.call(meta, propertyName)) return meta[propertyName]; - - // Certain types are "opaque," which means they have no side - // effects or leaps and we don't care about their subexpressions. - if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; - - if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; - - return meta[propertyName] = onlyChildren(node); - } - - predicate.onlyChildren = onlyChildren; - - return predicate; -} - -var opaqueTypes = { - FunctionExpression: true, - ArrowFunctionExpression: true -}; - -// These types potentially have side effects regardless of what side -// effects their subexpressions have. -var sideEffectTypes = { - CallExpression: true, // Anything could happen! - ForInStatement: true, // Modifies the key variable. - UnaryExpression: true, // Think delete. - BinaryExpression: true, // Might invoke .toString() or .valueOf(). - AssignmentExpression: true, // Side-effecting by definition. - UpdateExpression: true, // Updates are essentially assignments. - NewExpression: true // Similar to CallExpression. -}; - -// These types are the direct cause of all leaps in control flow. -var leapTypes = { - YieldExpression: true, - BreakStatement: true, - ContinueStatement: true, - ReturnStatement: true, - ThrowStatement: true -}; - -// All leap types are also side effect types. -for (var type in leapTypes) { - if (hasOwn.call(leapTypes, type)) { - sideEffectTypes[type] = leapTypes[type]; - } -} - -exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); -exports.containsLeap = makePredicate("containsLeap", leapTypes); -},{"assert":3,"babel-types":151,"private":524}],532:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = replaceShorthandObjectMethod; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _util = require("./util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -// this function converts a shorthand object generator method into a normal -// (non-shorthand) object property which is a generator function expression. for -// example, this: -// -// var foo = { -// *bar(baz) { return 5; } -// } -// -// should be replaced with: -// -// var foo = { -// bar: function*(baz) { return 5; } -// } -// -// to do this, it clones the parameter array and the body of the object generator -// method into a new FunctionExpression. -// -// this method can be passed any Function AST node path, and it will return -// either: -// a) the path that was passed in (iff the path did not need to be replaced) or -// b) the path of the new FunctionExpression that was created as a replacement -// (iff the path did need to be replaced) -// -// In either case, though, the caller can count on the fact that the return value -// is a Function AST node path. -// -// If this function is called with an AST node path that is not a Function (or with an -// argument that isn't an AST node path), it will throw an error. -function replaceShorthandObjectMethod(path) { - if (!path.node || !t.isFunction(path.node)) { - throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); - } - - // this function only replaces shorthand object methods (called ObjectMethod - // in Babel-speak). - if (!t.isObjectMethod(path.node)) { - return path; - } - - // this function only replaces generators. - if (!path.node.generator) { - return path; - } - - var parameters = path.node.params.map(function (param) { - return t.cloneDeep(param); - }); - - var functionExpression = t.functionExpression(null, // id - parameters, // params - t.cloneDeep(path.node.body), // body - path.node.generator, path.node.async); - - util.replaceWithOrRemove(path, t.objectProperty(t.cloneDeep(path.node.key), // key - functionExpression, //value - path.node.computed, // computed - false // shorthand - )); - - // path now refers to the ObjectProperty AST node path, but we want to return a - // Function AST node path for the function expression we created. we know that - // the FunctionExpression we just created is the value of the ObjectProperty, - // so return the "value" path off of this path. - return path.get("value"); -} -},{"./util":533,"babel-types":151}],533:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.runtimeProperty = runtimeProperty; -exports.isReference = isReference; -exports.replaceWithOrRemove = replaceWithOrRemove; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function runtimeProperty(name) { - return t.memberExpression(t.identifier("regeneratorRuntime"), t.identifier(name), false); -} /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -function isReference(path) { - return path.isReferenced() || path.parentPath.isAssignmentExpression({ left: path.node }); -} - -function replaceWithOrRemove(path, replacement) { - if (replacement) { - path.replaceWith(replacement); - } else { - path.remove(); - } -} -},{"babel-types":151}],534:[function(require,module,exports){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - -"use strict"; - -var _assert = require("assert"); - -var _assert2 = _interopRequireDefault(_assert); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _hoist = require("./hoist"); - -var _emit = require("./emit"); - -var _replaceShorthandObjectMethod = require("./replaceShorthandObjectMethod"); - -var _replaceShorthandObjectMethod2 = _interopRequireDefault(_replaceShorthandObjectMethod); - -var _util = require("./util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.visitor = { - Function: { - exit: function exit(path, state) { - var node = path.node; - - if (node.generator) { - if (node.async) { - // Async generator - if (state.opts.asyncGenerators === false) return; - } else { - // Plain generator - if (state.opts.generators === false) return; - } - } else if (node.async) { - // Async function - if (state.opts.async === false) return; - } else { - // Not a generator or async function. - return; - } - - // if this is an ObjectMethod, we need to convert it to an ObjectProperty - path = (0, _replaceShorthandObjectMethod2.default)(path); - node = path.node; - - var contextId = path.scope.generateUidIdentifier("context"); - var argsId = path.scope.generateUidIdentifier("args"); - - path.ensureBlock(); - var bodyBlockPath = path.get("body"); - - if (node.async) { - bodyBlockPath.traverse(awaitVisitor); - } - - bodyBlockPath.traverse(functionSentVisitor, { - context: contextId - }); - - var outerBody = []; - var innerBody = []; - - bodyBlockPath.get("body").forEach(function (childPath) { - var node = childPath.node; - if (t.isExpressionStatement(node) && t.isStringLiteral(node.expression)) { - // Babylon represents directives like "use strict" as elements - // of a bodyBlockPath.node.directives array, but they could just - // as easily be represented (by other parsers) as traditional - // string-literal-valued expression statements, so we need to - // handle that here. (#248) - outerBody.push(node); - } else if (node && node._blockHoist != null) { - outerBody.push(node); - } else { - innerBody.push(node); - } - }); - - if (outerBody.length > 0) { - // Only replace the inner body if we actually hoisted any statements - // to the outer body. - bodyBlockPath.node.body = innerBody; - } - - var outerFnExpr = getOuterFnExpr(path); - // Note that getOuterFnExpr has the side-effect of ensuring that the - // function has a name (so node.id will always be an Identifier), even - // if a temporary name has to be synthesized. - t.assertIdentifier(node.id); - var innerFnId = t.identifier(node.id.name + "$"); - - // Turn all declarations into vars, and replace the original - // declarations with equivalent assignment expressions. - var vars = (0, _hoist.hoist)(path); - - var didRenameArguments = renameArguments(path, argsId); - if (didRenameArguments) { - vars = vars || t.variableDeclaration("var", []); - var argumentIdentifier = t.identifier("arguments"); - // we need to do this as otherwise arguments in arrow functions gets hoisted - argumentIdentifier._shadowedFunctionLiteral = path; - vars.declarations.push(t.variableDeclarator(argsId, argumentIdentifier)); - } - - var emitter = new _emit.Emitter(contextId); - emitter.explode(path.get("body")); - - if (vars && vars.declarations.length > 0) { - outerBody.push(vars); - } - - var wrapArgs = [emitter.getContextFunction(innerFnId), - // Async functions that are not generators don't care about the - // outer function because they don't need it to be marked and don't - // inherit from its .prototype. - node.generator ? outerFnExpr : t.nullLiteral(), t.thisExpression()]; - - var tryLocsList = emitter.getTryLocsList(); - if (tryLocsList) { - wrapArgs.push(tryLocsList); - } - - var wrapCall = t.callExpression(util.runtimeProperty(node.async ? "async" : "wrap"), wrapArgs); - - outerBody.push(t.returnStatement(wrapCall)); - node.body = t.blockStatement(outerBody); - - var oldDirectives = bodyBlockPath.node.directives; - if (oldDirectives) { - // Babylon represents directives like "use strict" as elements of - // a bodyBlockPath.node.directives array. (#248) - node.body.directives = oldDirectives; - } - - var wasGeneratorFunction = node.generator; - if (wasGeneratorFunction) { - node.generator = false; - } - - if (node.async) { - node.async = false; - } - - if (wasGeneratorFunction && t.isExpression(node)) { - util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node])); - path.addComment("leading", "#__PURE__"); - } - - // Generators are processed in 'exit' handlers so that regenerator only has to run on - // an ES5 AST, but that means traversal will not pick up newly inserted references - // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue. - path.requeue(); - } - } -}; - -// Given a NodePath for a Function, return an Expression node that can be -// used to refer reliably to the function object from inside the function. -// This expression is essentially a replacement for arguments.callee, with -// the key advantage that it works in strict mode. -function getOuterFnExpr(funPath) { - var node = funPath.node; - t.assertFunction(node); - - if (!node.id) { - // Default-exported function declarations, and function expressions may not - // have a name to reference, so we explicitly add one. - node.id = funPath.scope.parent.generateUidIdentifier("callee"); - } - - if (node.generator && // Non-generator functions don't need to be marked. - t.isFunctionDeclaration(node)) { - // Return the identifier returned by runtime.mark(). - return getMarkedFunctionId(funPath); - } - - return node.id; -} - -var getMarkInfo = require("private").makeAccessor(); - -function getMarkedFunctionId(funPath) { - var node = funPath.node; - t.assertIdentifier(node.id); - - var blockPath = funPath.findParent(function (path) { - return path.isProgram() || path.isBlockStatement(); - }); - - if (!blockPath) { - return node.id; - } - - var block = blockPath.node; - _assert2.default.ok(Array.isArray(block.body)); - - var info = getMarkInfo(block); - if (!info.decl) { - info.decl = t.variableDeclaration("var", []); - blockPath.unshiftContainer("body", info.decl); - info.declPath = blockPath.get("body.0"); - } - - _assert2.default.strictEqual(info.declPath.node, info.decl); - - // Get a new unique identifier for our marked variable. - var markedId = blockPath.scope.generateUidIdentifier("marked"); - var markCallExp = t.callExpression(util.runtimeProperty("mark"), [node.id]); - - var index = info.decl.declarations.push(t.variableDeclarator(markedId, markCallExp)) - 1; - - var markCallExpPath = info.declPath.get("declarations." + index + ".init"); - - _assert2.default.strictEqual(markCallExpPath.node, markCallExp); - - markCallExpPath.addComment("leading", "#__PURE__"); - - return markedId; -} - -function renameArguments(funcPath, argsId) { - var state = { - didRenameArguments: false, - argsId: argsId - }; - - funcPath.traverse(argumentsVisitor, state); - - // If the traversal replaced any arguments references, then we need to - // alias the outer function's arguments binding (be it the implicit - // arguments object or some other parameter or variable) to the variable - // named by argsId. - return state.didRenameArguments; -} - -var argumentsVisitor = { - "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { - path.skip(); - }, - - Identifier: function Identifier(path, state) { - if (path.node.name === "arguments" && util.isReference(path)) { - util.replaceWithOrRemove(path, state.argsId); - state.didRenameArguments = true; - } - } -}; - -var functionSentVisitor = { - MetaProperty: function MetaProperty(path) { - var node = path.node; - - - if (node.meta.name === "function" && node.property.name === "sent") { - util.replaceWithOrRemove(path, t.memberExpression(this.context, t.identifier("_sent"))); - } - } -}; - -var awaitVisitor = { - Function: function Function(path) { - path.skip(); // Don't descend into nested function scopes. - }, - - AwaitExpression: function AwaitExpression(path) { - // Convert await expressions to yield expressions. - var argument = path.node.argument; - - // Transforming `await x` to `yield regeneratorRuntime.awrap(x)` - // causes the argument to be wrapped in such a way that the runtime - // can distinguish between awaited and merely yielded values. - util.replaceWithOrRemove(path, t.yieldExpression(t.callExpression(util.runtimeProperty("awrap"), [argument]), false)); - } -}; -},{"./emit":527,"./hoist":528,"./replaceShorthandObjectMethod":532,"./util":533,"assert":3,"babel-types":151,"private":524}],535:[function(require,module,exports){ -// Generated by `/scripts/character-class-escape-sets.js`. Do not edit. -var regenerate = require('regenerate'); - -exports.REGULAR = { - 'd': regenerate() - .addRange(0x30, 0x39), - 'D': regenerate() - .addRange(0x0, 0x2F) - .addRange(0x3A, 0xFFFF), - 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) - .addRange(0x9, 0xD) - .addRange(0x2000, 0x200A) - .addRange(0x2028, 0x2029), - 'S': regenerate() - .addRange(0x0, 0x8) - .addRange(0xE, 0x1F) - .addRange(0x21, 0x9F) - .addRange(0xA1, 0x167F) - .addRange(0x1681, 0x1FFF) - .addRange(0x200B, 0x2027) - .addRange(0x202A, 0x202E) - .addRange(0x2030, 0x205E) - .addRange(0x2060, 0x2FFF) - .addRange(0x3001, 0xFEFE) - .addRange(0xFF00, 0xFFFF), - 'w': regenerate(0x5F) - .addRange(0x30, 0x39) - .addRange(0x41, 0x5A) - .addRange(0x61, 0x7A), - 'W': regenerate(0x60) - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x40) - .addRange(0x5B, 0x5E) - .addRange(0x7B, 0xFFFF) -}; - -exports.UNICODE = { - 'd': regenerate() - .addRange(0x30, 0x39), - 'D': regenerate() - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x10FFFF), - 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) - .addRange(0x9, 0xD) - .addRange(0x2000, 0x200A) - .addRange(0x2028, 0x2029), - 'S': regenerate() - .addRange(0x0, 0x8) - .addRange(0xE, 0x1F) - .addRange(0x21, 0x9F) - .addRange(0xA1, 0x167F) - .addRange(0x1681, 0x1FFF) - .addRange(0x200B, 0x2027) - .addRange(0x202A, 0x202E) - .addRange(0x2030, 0x205E) - .addRange(0x2060, 0x2FFF) - .addRange(0x3001, 0xFEFE) - .addRange(0xFF00, 0x10FFFF), - 'w': regenerate(0x5F) - .addRange(0x30, 0x39) - .addRange(0x41, 0x5A) - .addRange(0x61, 0x7A), - 'W': regenerate(0x60) - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x40) - .addRange(0x5B, 0x5E) - .addRange(0x7B, 0x10FFFF) -}; - -exports.UNICODE_IGNORE_CASE = { - 'd': regenerate() - .addRange(0x30, 0x39), - 'D': regenerate() - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x10FFFF), - 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) - .addRange(0x9, 0xD) - .addRange(0x2000, 0x200A) - .addRange(0x2028, 0x2029), - 'S': regenerate() - .addRange(0x0, 0x8) - .addRange(0xE, 0x1F) - .addRange(0x21, 0x9F) - .addRange(0xA1, 0x167F) - .addRange(0x1681, 0x1FFF) - .addRange(0x200B, 0x2027) - .addRange(0x202A, 0x202E) - .addRange(0x2030, 0x205E) - .addRange(0x2060, 0x2FFF) - .addRange(0x3001, 0xFEFE) - .addRange(0xFF00, 0x10FFFF), - 'w': regenerate(0x5F, 0x17F, 0x212A) - .addRange(0x30, 0x39) - .addRange(0x41, 0x5A) - .addRange(0x61, 0x7A), - 'W': regenerate(0x4B, 0x53, 0x60) - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x40) - .addRange(0x5B, 0x5E) - .addRange(0x7B, 0x10FFFF) -}; - -},{"regenerate":526}],536:[function(require,module,exports){ -module.exports={ - "75": 8490, - "83": 383, - "107": 8490, - "115": 383, - "181": 924, - "197": 8491, - "383": 83, - "452": 453, - "453": 452, - "455": 456, - "456": 455, - "458": 459, - "459": 458, - "497": 498, - "498": 497, - "837": 8126, - "914": 976, - "917": 1013, - "920": 1012, - "921": 8126, - "922": 1008, - "924": 181, - "928": 982, - "929": 1009, - "931": 962, - "934": 981, - "937": 8486, - "962": 931, - "976": 914, - "977": 1012, - "981": 934, - "982": 928, - "1008": 922, - "1009": 929, - "1012": [ - 920, - 977 - ], - "1013": 917, - "7776": 7835, - "7835": 7776, - "8126": [ - 837, - 921 - ], - "8486": 937, - "8490": 75, - "8491": 197, - "66560": 66600, - "66561": 66601, - "66562": 66602, - "66563": 66603, - "66564": 66604, - "66565": 66605, - "66566": 66606, - "66567": 66607, - "66568": 66608, - "66569": 66609, - "66570": 66610, - "66571": 66611, - "66572": 66612, - "66573": 66613, - "66574": 66614, - "66575": 66615, - "66576": 66616, - "66577": 66617, - "66578": 66618, - "66579": 66619, - "66580": 66620, - "66581": 66621, - "66582": 66622, - "66583": 66623, - "66584": 66624, - "66585": 66625, - "66586": 66626, - "66587": 66627, - "66588": 66628, - "66589": 66629, - "66590": 66630, - "66591": 66631, - "66592": 66632, - "66593": 66633, - "66594": 66634, - "66595": 66635, - "66596": 66636, - "66597": 66637, - "66598": 66638, - "66599": 66639, - "66600": 66560, - "66601": 66561, - "66602": 66562, - "66603": 66563, - "66604": 66564, - "66605": 66565, - "66606": 66566, - "66607": 66567, - "66608": 66568, - "66609": 66569, - "66610": 66570, - "66611": 66571, - "66612": 66572, - "66613": 66573, - "66614": 66574, - "66615": 66575, - "66616": 66576, - "66617": 66577, - "66618": 66578, - "66619": 66579, - "66620": 66580, - "66621": 66581, - "66622": 66582, - "66623": 66583, - "66624": 66584, - "66625": 66585, - "66626": 66586, - "66627": 66587, - "66628": 66588, - "66629": 66589, - "66630": 66590, - "66631": 66591, - "66632": 66592, - "66633": 66593, - "66634": 66594, - "66635": 66595, - "66636": 66596, - "66637": 66597, - "66638": 66598, - "66639": 66599, - "68736": 68800, - "68737": 68801, - "68738": 68802, - "68739": 68803, - "68740": 68804, - "68741": 68805, - "68742": 68806, - "68743": 68807, - "68744": 68808, - "68745": 68809, - "68746": 68810, - "68747": 68811, - "68748": 68812, - "68749": 68813, - "68750": 68814, - "68751": 68815, - "68752": 68816, - "68753": 68817, - "68754": 68818, - "68755": 68819, - "68756": 68820, - "68757": 68821, - "68758": 68822, - "68759": 68823, - "68760": 68824, - "68761": 68825, - "68762": 68826, - "68763": 68827, - "68764": 68828, - "68765": 68829, - "68766": 68830, - "68767": 68831, - "68768": 68832, - "68769": 68833, - "68770": 68834, - "68771": 68835, - "68772": 68836, - "68773": 68837, - "68774": 68838, - "68775": 68839, - "68776": 68840, - "68777": 68841, - "68778": 68842, - "68779": 68843, - "68780": 68844, - "68781": 68845, - "68782": 68846, - "68783": 68847, - "68784": 68848, - "68785": 68849, - "68786": 68850, - "68800": 68736, - "68801": 68737, - "68802": 68738, - "68803": 68739, - "68804": 68740, - "68805": 68741, - "68806": 68742, - "68807": 68743, - "68808": 68744, - "68809": 68745, - "68810": 68746, - "68811": 68747, - "68812": 68748, - "68813": 68749, - "68814": 68750, - "68815": 68751, - "68816": 68752, - "68817": 68753, - "68818": 68754, - "68819": 68755, - "68820": 68756, - "68821": 68757, - "68822": 68758, - "68823": 68759, - "68824": 68760, - "68825": 68761, - "68826": 68762, - "68827": 68763, - "68828": 68764, - "68829": 68765, - "68830": 68766, - "68831": 68767, - "68832": 68768, - "68833": 68769, - "68834": 68770, - "68835": 68771, - "68836": 68772, - "68837": 68773, - "68838": 68774, - "68839": 68775, - "68840": 68776, - "68841": 68777, - "68842": 68778, - "68843": 68779, - "68844": 68780, - "68845": 68781, - "68846": 68782, - "68847": 68783, - "68848": 68784, - "68849": 68785, - "68850": 68786, - "71840": 71872, - "71841": 71873, - "71842": 71874, - "71843": 71875, - "71844": 71876, - "71845": 71877, - "71846": 71878, - "71847": 71879, - "71848": 71880, - "71849": 71881, - "71850": 71882, - "71851": 71883, - "71852": 71884, - "71853": 71885, - "71854": 71886, - "71855": 71887, - "71856": 71888, - "71857": 71889, - "71858": 71890, - "71859": 71891, - "71860": 71892, - "71861": 71893, - "71862": 71894, - "71863": 71895, - "71864": 71896, - "71865": 71897, - "71866": 71898, - "71867": 71899, - "71868": 71900, - "71869": 71901, - "71870": 71902, - "71871": 71903, - "71872": 71840, - "71873": 71841, - "71874": 71842, - "71875": 71843, - "71876": 71844, - "71877": 71845, - "71878": 71846, - "71879": 71847, - "71880": 71848, - "71881": 71849, - "71882": 71850, - "71883": 71851, - "71884": 71852, - "71885": 71853, - "71886": 71854, - "71887": 71855, - "71888": 71856, - "71889": 71857, - "71890": 71858, - "71891": 71859, - "71892": 71860, - "71893": 71861, - "71894": 71862, - "71895": 71863, - "71896": 71864, - "71897": 71865, - "71898": 71866, - "71899": 71867, - "71900": 71868, - "71901": 71869, - "71902": 71870, - "71903": 71871 -} - -},{}],537:[function(require,module,exports){ -var generate = require('regjsgen').generate; -var parse = require('regjsparser').parse; -var regenerate = require('regenerate'); -var iuMappings = require('./data/iu-mappings.json'); -var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); - -function getCharacterClassEscapeSet(character) { - if (unicode) { - if (ignoreCase) { - return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]; - } - return ESCAPE_SETS.UNICODE[character]; - } - return ESCAPE_SETS.REGULAR[character]; -} - -var object = {}; -var hasOwnProperty = object.hasOwnProperty; -function has(object, property) { - return hasOwnProperty.call(object, property); -} - -// Prepare a Regenerate set containing all code points, used for negative -// character classes (if any). -var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); -// Without the `u` flag, the range stops at 0xFFFF. -// https://mths.be/es6#sec-pattern-semantics -var BMP_SET = regenerate().addRange(0x0, 0xFFFF); - -// Prepare a Regenerate set containing all code points that are supposed to be -// matched by `/./u`. https://mths.be/es6#sec-atom -var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points - .remove( - // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators): - 0x000A, // Line Feed - 0x000D, // Carriage Return - 0x2028, // Line Separator - 0x2029 // Paragraph Separator - ); -// Prepare a Regenerate set containing all code points that are supposed to be -// matched by `/./` (only BMP code points). -var DOT_SET = DOT_SET_UNICODE.clone() - .intersection(BMP_SET); - -// Add a range of code points + any case-folded code points in that range to a -// set. -regenerate.prototype.iuAddRange = function(min, max) { - var $this = this; - do { - var folded = caseFold(min); - if (folded) { - $this.add(folded); - } - } while (++min <= max); - return $this; -}; - -function assign(target, source) { - for (var key in source) { - // Note: `hasOwnProperty` is not needed here. - target[key] = source[key]; - } -} - -function update(item, pattern) { - // TODO: Test if memoizing `pattern` here is worth the effort. - if (!pattern) { - return; - } - var tree = parse(pattern, ''); - switch (tree.type) { - case 'characterClass': - case 'group': - case 'value': - // No wrapping needed. - break; - default: - // Wrap the pattern in a non-capturing group. - tree = wrap(tree, pattern); - } - assign(item, tree); -} - -function wrap(tree, pattern) { - // Wrap the pattern in a non-capturing group. - return { - 'type': 'group', - 'behavior': 'ignore', - 'body': [tree], - 'raw': '(?:' + pattern + ')' - }; -} - -function caseFold(codePoint) { - return has(iuMappings, codePoint) ? iuMappings[codePoint] : false; -} - -var ignoreCase = false; -var unicode = false; -function processCharacterClass(characterClassItem) { - var set = regenerate(); - var body = characterClassItem.body.forEach(function(item) { - switch (item.type) { - case 'value': - set.add(item.codePoint); - if (ignoreCase && unicode) { - var folded = caseFold(item.codePoint); - if (folded) { - set.add(folded); - } - } - break; - case 'characterClassRange': - var min = item.min.codePoint; - var max = item.max.codePoint; - set.addRange(min, max); - if (ignoreCase && unicode) { - set.iuAddRange(min, max); - } - break; - case 'characterClassEscape': - set.add(getCharacterClassEscapeSet(item.value)); - break; - // The `default` clause is only here as a safeguard; it should never be - // reached. Code coverage tools should ignore it. - /* istanbul ignore next */ - default: - throw Error('Unknown term type: ' + item.type); - } - }); - if (characterClassItem.negative) { - set = (unicode ? UNICODE_SET : BMP_SET).clone().remove(set); - } - update(characterClassItem, set.toString()); - return characterClassItem; -} - -function processTerm(item) { - switch (item.type) { - case 'dot': - update( - item, - (unicode ? DOT_SET_UNICODE : DOT_SET).toString() - ); - break; - case 'characterClass': - item = processCharacterClass(item); - break; - case 'characterClassEscape': - update( - item, - getCharacterClassEscapeSet(item.value).toString() - ); - break; - case 'alternative': - case 'disjunction': - case 'group': - case 'quantifier': - item.body = item.body.map(processTerm); - break; - case 'value': - var codePoint = item.codePoint; - var set = regenerate(codePoint); - if (ignoreCase && unicode) { - var folded = caseFold(codePoint); - if (folded) { - set.add(folded); - } - } - update(item, set.toString()); - break; - case 'anchor': - case 'empty': - case 'group': - case 'reference': - // Nothing to do here. - break; - // The `default` clause is only here as a safeguard; it should never be - // reached. Code coverage tools should ignore it. - /* istanbul ignore next */ - default: - throw Error('Unknown term type: ' + item.type); - } - return item; -}; - -module.exports = function(pattern, flags) { - var tree = parse(pattern, flags); - ignoreCase = flags ? flags.indexOf('i') > -1 : false; - unicode = flags ? flags.indexOf('u') > -1 : false; - assign(tree, processTerm(tree)); - return generate(tree); -}; - -},{"./data/character-class-escape-sets.js":535,"./data/iu-mappings.json":536,"regenerate":526,"regjsgen":538,"regjsparser":539}],538:[function(require,module,exports){ -(function (global){ -/*! - * RegJSGen - * Copyright 2014 Benjamin Tan - * Available under MIT license - */ -;(function() { - 'use strict'; - - /** Used to determine if values are of the language type `Object` */ - var objectTypes = { - 'function': true, - 'object': true - }; - - /** Used as a reference to the global object */ - var root = (objectTypes[typeof window] && window) || this; - - /** Backup possible global object */ - var oldRoot = root; - - /** Detect free variable `exports` */ - var freeExports = objectTypes[typeof exports] && exports; - - /** Detect free variable `module` */ - var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; - - /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ - var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - /*! Based on https://mths.be/fromcodepoint v0.2.0 by @mathias */ - - var stringFromCharCode = String.fromCharCode; - var floor = Math.floor; - function fromCodePoint() { - var MAX_SIZE = 0x4000; - var codeUnits = []; - var highSurrogate; - var lowSurrogate; - var index = -1; - var length = arguments.length; - if (!length) { - return ''; - } - var result = ''; - while (++index < length) { - var codePoint = Number(arguments[index]); - if ( - !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` - codePoint < 0 || // not a valid Unicode code point - codePoint > 0x10FFFF || // not a valid Unicode code point - floor(codePoint) != codePoint // not an integer - ) { - throw RangeError('Invalid code point: ' + codePoint); - } - if (codePoint <= 0xFFFF) { - // BMP code point - codeUnits.push(codePoint); - } else { - // Astral code point; split in surrogate halves - // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - codePoint -= 0x10000; - highSurrogate = (codePoint >> 10) + 0xD800; - lowSurrogate = (codePoint % 0x400) + 0xDC00; - codeUnits.push(highSurrogate, lowSurrogate); - } - if (index + 1 == length || codeUnits.length > MAX_SIZE) { - result += stringFromCharCode.apply(null, codeUnits); - codeUnits.length = 0; - } - } - return result; - } - - function assertType(type, expected) { - if (expected.indexOf('|') == -1) { - if (type == expected) { - return; - } - - throw Error('Invalid node type: ' + type); - } - - expected = assertType.hasOwnProperty(expected) - ? assertType[expected] - : (assertType[expected] = RegExp('^(?:' + expected + ')$')); - - if (expected.test(type)) { - return; - } - - throw Error('Invalid node type: ' + type); - } - - /*--------------------------------------------------------------------------*/ - - function generate(node) { - var type = node.type; - - if (generate.hasOwnProperty(type) && typeof generate[type] == 'function') { - return generate[type](node); - } - - throw Error('Invalid node type: ' + type); - } - - /*--------------------------------------------------------------------------*/ - - function generateAlternative(node) { - assertType(node.type, 'alternative'); - - var terms = node.body, - length = terms ? terms.length : 0; - - if (length == 1) { - return generateTerm(terms[0]); - } else { - var i = -1, - result = ''; - - while (++i < length) { - result += generateTerm(terms[i]); - } - - return result; - } - } - - function generateAnchor(node) { - assertType(node.type, 'anchor'); - - switch (node.kind) { - case 'start': - return '^'; - case 'end': - return '$'; - case 'boundary': - return '\\b'; - case 'not-boundary': - return '\\B'; - default: - throw Error('Invalid assertion'); - } - } - - function generateAtom(node) { - assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value'); - - return generate(node); - } - - function generateCharacterClass(node) { - assertType(node.type, 'characterClass'); - - var classRanges = node.body, - length = classRanges ? classRanges.length : 0; - - var i = -1, - result = '['; - - if (node.negative) { - result += '^'; - } - - while (++i < length) { - result += generateClassAtom(classRanges[i]); - } - - result += ']'; - - return result; - } - - function generateCharacterClassEscape(node) { - assertType(node.type, 'characterClassEscape'); - - return '\\' + node.value; - } - - function generateCharacterClassRange(node) { - assertType(node.type, 'characterClassRange'); - - var min = node.min, - max = node.max; - - if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { - throw Error('Invalid character class range'); - } - - return generateClassAtom(min) + '-' + generateClassAtom(max); - } - - function generateClassAtom(node) { - assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value'); - - return generate(node); - } - - function generateDisjunction(node) { - assertType(node.type, 'disjunction'); - - var body = node.body, - length = body ? body.length : 0; - - if (length == 0) { - throw Error('No body'); - } else if (length == 1) { - return generate(body[0]); - } else { - var i = -1, - result = ''; - - while (++i < length) { - if (i != 0) { - result += '|'; - } - result += generate(body[i]); - } - - return result; - } - } - - function generateDot(node) { - assertType(node.type, 'dot'); - - return '.'; - } - - function generateGroup(node) { - assertType(node.type, 'group'); - - var result = '('; - - switch (node.behavior) { - case 'normal': - break; - case 'ignore': - result += '?:'; - break; - case 'lookahead': - result += '?='; - break; - case 'negativeLookahead': - result += '?!'; - break; - default: - throw Error('Invalid behaviour: ' + node.behaviour); - } - - var body = node.body, - length = body ? body.length : 0; - - if (length == 1) { - result += generate(body[0]); - } else { - var i = -1; - - while (++i < length) { - result += generate(body[i]); - } - } - - result += ')'; - - return result; - } - - function generateQuantifier(node) { - assertType(node.type, 'quantifier'); - - var quantifier = '', - min = node.min, - max = node.max; - - switch (max) { - case undefined: - case null: - switch (min) { - case 0: - quantifier = '*' - break; - case 1: - quantifier = '+'; - break; - default: - quantifier = '{' + min + ',}'; - break; - } - break; - default: - if (min == max) { - quantifier = '{' + min + '}'; - } - else if (min == 0 && max == 1) { - quantifier = '?'; - } else { - quantifier = '{' + min + ',' + max + '}'; - } - break; - } - - if (!node.greedy) { - quantifier += '?'; - } - - return generateAtom(node.body[0]) + quantifier; - } - - function generateReference(node) { - assertType(node.type, 'reference'); - - return '\\' + node.matchIndex; - } - - function generateTerm(node) { - assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value'); - - return generate(node); - } - - function generateValue(node) { - assertType(node.type, 'value'); - - var kind = node.kind, - codePoint = node.codePoint; - - switch (kind) { - case 'controlLetter': - return '\\c' + fromCodePoint(codePoint + 64); - case 'hexadecimalEscape': - return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); - case 'identifier': - return '\\' + fromCodePoint(codePoint); - case 'null': - return '\\' + codePoint; - case 'octal': - return '\\' + codePoint.toString(8); - case 'singleEscape': - switch (codePoint) { - case 0x0008: - return '\\b'; - case 0x009: - return '\\t'; - case 0x00A: - return '\\n'; - case 0x00B: - return '\\v'; - case 0x00C: - return '\\f'; - case 0x00D: - return '\\r'; - default: - throw Error('Invalid codepoint: ' + codePoint); - } - case 'symbol': - return fromCodePoint(codePoint); - case 'unicodeEscape': - return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); - case 'unicodeCodePointEscape': - return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; - default: - throw Error('Unsupported node kind: ' + kind); - } - } - - /*--------------------------------------------------------------------------*/ - - generate.alternative = generateAlternative; - generate.anchor = generateAnchor; - generate.characterClass = generateCharacterClass; - generate.characterClassEscape = generateCharacterClassEscape; - generate.characterClassRange = generateCharacterClassRange; - generate.disjunction = generateDisjunction; - generate.dot = generateDot; - generate.group = generateGroup; - generate.quantifier = generateQuantifier; - generate.reference = generateReference; - generate.value = generateValue; - - /*--------------------------------------------------------------------------*/ - - // export regjsgen - // some AMD build optimizers, like r.js, check for condition patterns like the following: - if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { - // define as an anonymous module so, through path mapping, it can be aliased - define(function() { - return { - 'generate': generate - }; - }); - } - // check for `exports` after `define` in case a build optimizer adds an `exports` object - else if (freeExports && freeModule) { - // in Narwhal, Node.js, Rhino -require, or RingoJS - freeExports.generate = generate; - } - // in a browser or Rhino - else { - root.regjsgen = { - 'generate': generate - }; - } -}.call(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],539:[function(require,module,exports){ -// regjsparser -// -// ================================================================== -// -// See ECMA-262 Standard: 15.10.1 -// -// NOTE: The ECMA-262 standard uses the term "Assertion" for /^/. Here the -// term "Anchor" is used. -// -// Pattern :: -// Disjunction -// -// Disjunction :: -// Alternative -// Alternative | Disjunction -// -// Alternative :: -// [empty] -// Alternative Term -// -// Term :: -// Anchor -// Atom -// Atom Quantifier -// -// Anchor :: -// ^ -// $ -// \ b -// \ B -// ( ? = Disjunction ) -// ( ? ! Disjunction ) -// -// Quantifier :: -// QuantifierPrefix -// QuantifierPrefix ? -// -// QuantifierPrefix :: -// * -// + -// ? -// { DecimalDigits } -// { DecimalDigits , } -// { DecimalDigits , DecimalDigits } -// -// Atom :: -// PatternCharacter -// . -// \ AtomEscape -// CharacterClass -// ( Disjunction ) -// ( ? : Disjunction ) -// -// PatternCharacter :: -// SourceCharacter but not any of: ^ $ \ . * + ? ( ) [ ] { } | -// -// AtomEscape :: -// DecimalEscape -// CharacterEscape -// CharacterClassEscape -// -// CharacterEscape[U] :: -// ControlEscape -// c ControlLetter -// HexEscapeSequence -// RegExpUnicodeEscapeSequence[?U] (ES6) -// IdentityEscape[?U] -// -// ControlEscape :: -// one of f n r t v -// ControlLetter :: -// one of -// a b c d e f g h i j k l m n o p q r s t u v w x y z -// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z -// -// IdentityEscape :: -// SourceCharacter but not IdentifierPart -// -// -// -// DecimalEscape :: -// DecimalIntegerLiteral [lookahead ∉ DecimalDigit] -// -// CharacterClassEscape :: -// one of d D s S w W -// -// CharacterClass :: -// [ [lookahead ∉ {^}] ClassRanges ] -// [ ^ ClassRanges ] -// -// ClassRanges :: -// [empty] -// NonemptyClassRanges -// -// NonemptyClassRanges :: -// ClassAtom -// ClassAtom NonemptyClassRangesNoDash -// ClassAtom - ClassAtom ClassRanges -// -// NonemptyClassRangesNoDash :: -// ClassAtom -// ClassAtomNoDash NonemptyClassRangesNoDash -// ClassAtomNoDash - ClassAtom ClassRanges -// -// ClassAtom :: -// - -// ClassAtomNoDash -// -// ClassAtomNoDash :: -// SourceCharacter but not one of \ or ] or - -// \ ClassEscape -// -// ClassEscape :: -// DecimalEscape -// b -// CharacterEscape -// CharacterClassEscape - -(function() { - - function parse(str, flags) { - function addRaw(node) { - node.raw = str.substring(node.range[0], node.range[1]); - return node; - } - - function updateRawStart(node, start) { - node.range[0] = start; - return addRaw(node); - } - - function createAnchor(kind, rawLength) { - return addRaw({ - type: 'anchor', - kind: kind, - range: [ - pos - rawLength, - pos - ] - }); - } - - function createValue(kind, codePoint, from, to) { - return addRaw({ - type: 'value', - kind: kind, - codePoint: codePoint, - range: [from, to] - }); - } - - function createEscaped(kind, codePoint, value, fromOffset) { - fromOffset = fromOffset || 0; - return createValue(kind, codePoint, pos - (value.length + fromOffset), pos); - } - - function createCharacter(matches) { - var _char = matches[0]; - var first = _char.charCodeAt(0); - if (hasUnicodeFlag) { - var second; - if (_char.length === 1 && first >= 0xD800 && first <= 0xDBFF) { - second = lookahead().charCodeAt(0); - if (second >= 0xDC00 && second <= 0xDFFF) { - // Unicode surrogate pair - pos++; - return createValue( - 'symbol', - (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000, - pos - 2, pos); - } - } - } - return createValue('symbol', first, pos - 1, pos); - } - - function createDisjunction(alternatives, from, to) { - return addRaw({ - type: 'disjunction', - body: alternatives, - range: [ - from, - to - ] - }); - } - - function createDot() { - return addRaw({ - type: 'dot', - range: [ - pos - 1, - pos - ] - }); - } - - function createCharacterClassEscape(value) { - return addRaw({ - type: 'characterClassEscape', - value: value, - range: [ - pos - 2, - pos - ] - }); - } - - function createReference(matchIndex) { - return addRaw({ - type: 'reference', - matchIndex: parseInt(matchIndex, 10), - range: [ - pos - 1 - matchIndex.length, - pos - ] - }); - } - - function createGroup(behavior, disjunction, from, to) { - return addRaw({ - type: 'group', - behavior: behavior, - body: disjunction, - range: [ - from, - to - ] - }); - } - - function createQuantifier(min, max, from, to) { - if (to == null) { - from = pos - 1; - to = pos; - } - - return addRaw({ - type: 'quantifier', - min: min, - max: max, - greedy: true, - body: null, // set later on - range: [ - from, - to - ] - }); - } - - function createAlternative(terms, from, to) { - return addRaw({ - type: 'alternative', - body: terms, - range: [ - from, - to - ] - }); - } - - function createCharacterClass(classRanges, negative, from, to) { - return addRaw({ - type: 'characterClass', - body: classRanges, - negative: negative, - range: [ - from, - to - ] - }); - } - - function createClassRange(min, max, from, to) { - // See 15.10.2.15: - if (min.codePoint > max.codePoint) { - bail('invalid range in character class', min.raw + '-' + max.raw, from, to); - } - - return addRaw({ - type: 'characterClassRange', - min: min, - max: max, - range: [ - from, - to - ] - }); - } - - function flattenBody(body) { - if (body.type === 'alternative') { - return body.body; - } else { - return [body]; - } - } - - function isEmpty(obj) { - return obj.type === 'empty'; - } - - function incr(amount) { - amount = (amount || 1); - var res = str.substring(pos, pos + amount); - pos += (amount || 1); - return res; - } - - function skip(value) { - if (!match(value)) { - bail('character', value); - } - } - - function match(value) { - if (str.indexOf(value, pos) === pos) { - return incr(value.length); - } - } - - function lookahead() { - return str[pos]; - } - - function current(value) { - return str.indexOf(value, pos) === pos; - } - - function next(value) { - return str[pos + 1] === value; - } - - function matchReg(regExp) { - var subStr = str.substring(pos); - var res = subStr.match(regExp); - if (res) { - res.range = []; - res.range[0] = pos; - incr(res[0].length); - res.range[1] = pos; - } - return res; - } - - function parseDisjunction() { - // Disjunction :: - // Alternative - // Alternative | Disjunction - var res = [], from = pos; - res.push(parseAlternative()); - - while (match('|')) { - res.push(parseAlternative()); - } - - if (res.length === 1) { - return res[0]; - } - - return createDisjunction(res, from, pos); - } - - function parseAlternative() { - var res = [], from = pos; - var term; - - // Alternative :: - // [empty] - // Alternative Term - while (term = parseTerm()) { - res.push(term); - } - - if (res.length === 1) { - return res[0]; - } - - return createAlternative(res, from, pos); - } - - function parseTerm() { - // Term :: - // Anchor - // Atom - // Atom Quantifier - - if (pos >= str.length || current('|') || current(')')) { - return null; /* Means: The term is empty */ - } - - var anchor = parseAnchor(); - - if (anchor) { - return anchor; - } - - var atom = parseAtom(); - if (!atom) { - bail('Expected atom'); - } - var quantifier = parseQuantifier() || false; - if (quantifier) { - quantifier.body = flattenBody(atom); - // The quantifier contains the atom. Therefore, the beginning of the - // quantifier range is given by the beginning of the atom. - updateRawStart(quantifier, atom.range[0]); - return quantifier; - } - return atom; - } - - function parseGroup(matchA, typeA, matchB, typeB) { - var type = null, from = pos; - - if (match(matchA)) { - type = typeA; - } else if (match(matchB)) { - type = typeB; - } else { - return false; - } - - var body = parseDisjunction(); - if (!body) { - bail('Expected disjunction'); - } - skip(')'); - var group = createGroup(type, flattenBody(body), from, pos); - - if (type == 'normal') { - // Keep track of the number of closed groups. This is required for - // parseDecimalEscape(). In case the string is parsed a second time the - // value already holds the total count and no incrementation is required. - if (firstIteration) { - closedCaptureCounter++; - } - } - return group; - } - - function parseAnchor() { - // Anchor :: - // ^ - // $ - // \ b - // \ B - // ( ? = Disjunction ) - // ( ? ! Disjunction ) - var res, from = pos; - - if (match('^')) { - return createAnchor('start', 1 /* rawLength */); - } else if (match('$')) { - return createAnchor('end', 1 /* rawLength */); - } else if (match('\\b')) { - return createAnchor('boundary', 2 /* rawLength */); - } else if (match('\\B')) { - return createAnchor('not-boundary', 2 /* rawLength */); - } else { - return parseGroup('(?=', 'lookahead', '(?!', 'negativeLookahead'); - } - } - - function parseQuantifier() { - // Quantifier :: - // QuantifierPrefix - // QuantifierPrefix ? - // - // QuantifierPrefix :: - // * - // + - // ? - // { DecimalDigits } - // { DecimalDigits , } - // { DecimalDigits , DecimalDigits } - - var res, from = pos; - var quantifier; - var min, max; - - if (match('*')) { - quantifier = createQuantifier(0); - } - else if (match('+')) { - quantifier = createQuantifier(1); - } - else if (match('?')) { - quantifier = createQuantifier(0, 1); - } - else if (res = matchReg(/^\{([0-9]+)\}/)) { - min = parseInt(res[1], 10); - quantifier = createQuantifier(min, min, res.range[0], res.range[1]); - } - else if (res = matchReg(/^\{([0-9]+),\}/)) { - min = parseInt(res[1], 10); - quantifier = createQuantifier(min, undefined, res.range[0], res.range[1]); - } - else if (res = matchReg(/^\{([0-9]+),([0-9]+)\}/)) { - min = parseInt(res[1], 10); - max = parseInt(res[2], 10); - if (min > max) { - bail('numbers out of order in {} quantifier', '', from, pos); - } - quantifier = createQuantifier(min, max, res.range[0], res.range[1]); - } - - if (quantifier) { - if (match('?')) { - quantifier.greedy = false; - quantifier.range[1] += 1; - } - } - - return quantifier; - } - - function parseAtom() { - // Atom :: - // PatternCharacter - // . - // \ AtomEscape - // CharacterClass - // ( Disjunction ) - // ( ? : Disjunction ) - - var res; - - // jviereck: allow ']', '}' here as well to be compatible with browser's - // implementations: ']'.match(/]/); - // if (res = matchReg(/^[^^$\\.*+?()[\]{}|]/)) { - if (res = matchReg(/^[^^$\\.*+?(){[|]/)) { - // PatternCharacter - return createCharacter(res); - } - else if (match('.')) { - // . - return createDot(); - } - else if (match('\\')) { - // \ AtomEscape - res = parseAtomEscape(); - if (!res) { - bail('atomEscape'); - } - return res; - } - else if (res = parseCharacterClass()) { - return res; - } - else { - // ( Disjunction ) - // ( ? : Disjunction ) - return parseGroup('(?:', 'ignore', '(', 'normal'); - } - } - - function parseUnicodeSurrogatePairEscape(firstEscape) { - if (hasUnicodeFlag) { - var first, second; - if (firstEscape.kind == 'unicodeEscape' && - (first = firstEscape.codePoint) >= 0xD800 && first <= 0xDBFF && - current('\\') && next('u') ) { - var prevPos = pos; - pos++; - var secondEscape = parseClassEscape(); - if (secondEscape.kind == 'unicodeEscape' && - (second = secondEscape.codePoint) >= 0xDC00 && second <= 0xDFFF) { - // Unicode surrogate pair - firstEscape.range[1] = secondEscape.range[1]; - firstEscape.codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - firstEscape.type = 'value'; - firstEscape.kind = 'unicodeCodePointEscape'; - addRaw(firstEscape); - } - else { - pos = prevPos; - } - } - } - return firstEscape; - } - - function parseClassEscape() { - return parseAtomEscape(true); - } - - function parseAtomEscape(insideCharacterClass) { - // AtomEscape :: - // DecimalEscape - // CharacterEscape - // CharacterClassEscape - - var res, from = pos; - - res = parseDecimalEscape(); - if (res) { - return res; - } - - // For ClassEscape - if (insideCharacterClass) { - if (match('b')) { - // 15.10.2.19 - // The production ClassEscape :: b evaluates by returning the - // CharSet containing the one character (Unicode value 0008). - return createEscaped('singleEscape', 0x0008, '\\b'); - } else if (match('B')) { - bail('\\B not possible inside of CharacterClass', '', from); - } - } - - res = parseCharacterEscape(); - - return res; - } - - - function parseDecimalEscape() { - // DecimalEscape :: - // DecimalIntegerLiteral [lookahead ∉ DecimalDigit] - // CharacterClassEscape :: one of d D s S w W - - var res, match; - - if (res = matchReg(/^(?!0)\d+/)) { - match = res[0]; - var refIdx = parseInt(res[0], 10); - if (refIdx <= closedCaptureCounter) { - // If the number is smaller than the normal-groups found so - // far, then it is a reference... - return createReference(res[0]); - } else { - // ... otherwise it needs to be interpreted as a octal (if the - // number is in an octal format). If it is NOT octal format, - // then the slash is ignored and the number is matched later - // as normal characters. - - // Recall the negative decision to decide if the input must be parsed - // a second time with the total normal-groups. - backrefDenied.push(refIdx); - - // Reset the position again, as maybe only parts of the previous - // matched numbers are actual octal numbers. E.g. in '019' only - // the '01' should be matched. - incr(-res[0].length); - if (res = matchReg(/^[0-7]{1,3}/)) { - return createEscaped('octal', parseInt(res[0], 8), res[0], 1); - } else { - // If we end up here, we have a case like /\91/. Then the - // first slash is to be ignored and the 9 & 1 to be treated - // like ordinary characters. Create a character for the - // first number only here - other number-characters - // (if available) will be matched later. - res = createCharacter(matchReg(/^[89]/)); - return updateRawStart(res, res.range[0] - 1); - } - } - } - // Only allow octal numbers in the following. All matched numbers start - // with a zero (if the do not, the previous if-branch is executed). - // If the number is not octal format and starts with zero (e.g. `091`) - // then only the zeros `0` is treated here and the `91` are ordinary - // characters. - // Example: - // /\091/.exec('\091')[0].length === 3 - else if (res = matchReg(/^[0-7]{1,3}/)) { - match = res[0]; - if (/^0{1,3}$/.test(match)) { - // If they are all zeros, then only take the first one. - return createEscaped('null', 0x0000, '0', match.length + 1); - } else { - return createEscaped('octal', parseInt(match, 8), match, 1); - } - } else if (res = matchReg(/^[dDsSwW]/)) { - return createCharacterClassEscape(res[0]); - } - return false; - } - - function parseCharacterEscape() { - // CharacterEscape :: - // ControlEscape - // c ControlLetter - // HexEscapeSequence - // UnicodeEscapeSequence - // IdentityEscape - - var res; - if (res = matchReg(/^[fnrtv]/)) { - // ControlEscape - var codePoint = 0; - switch (res[0]) { - case 't': codePoint = 0x009; break; - case 'n': codePoint = 0x00A; break; - case 'v': codePoint = 0x00B; break; - case 'f': codePoint = 0x00C; break; - case 'r': codePoint = 0x00D; break; - } - return createEscaped('singleEscape', codePoint, '\\' + res[0]); - } else if (res = matchReg(/^c([a-zA-Z])/)) { - // c ControlLetter - return createEscaped('controlLetter', res[1].charCodeAt(0) % 32, res[1], 2); - } else if (res = matchReg(/^x([0-9a-fA-F]{2})/)) { - // HexEscapeSequence - return createEscaped('hexadecimalEscape', parseInt(res[1], 16), res[1], 2); - } else if (res = matchReg(/^u([0-9a-fA-F]{4})/)) { - // UnicodeEscapeSequence - return parseUnicodeSurrogatePairEscape( - createEscaped('unicodeEscape', parseInt(res[1], 16), res[1], 2) - ); - } else if (hasUnicodeFlag && (res = matchReg(/^u\{([0-9a-fA-F]+)\}/))) { - // RegExpUnicodeEscapeSequence (ES6 Unicode code point escape) - return createEscaped('unicodeCodePointEscape', parseInt(res[1], 16), res[1], 4); - } else { - // IdentityEscape - return parseIdentityEscape(); - } - } - - // Taken from the Esprima parser. - function isIdentifierPart(ch) { - // Generated by `tools/generate-identifier-regex.js`. - var NonAsciiIdentifierPart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); - - return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) - (ch >= 65 && ch <= 90) || // A..Z - (ch >= 97 && ch <= 122) || // a..z - (ch >= 48 && ch <= 57) || // 0..9 - (ch === 92) || // \ (backslash) - ((ch >= 0x80) && NonAsciiIdentifierPart.test(String.fromCharCode(ch))); - } - - function parseIdentityEscape() { - // IdentityEscape :: - // SourceCharacter but not IdentifierPart - // - // - - var ZWJ = '\u200C'; - var ZWNJ = '\u200D'; - - var tmp; - - if (!isIdentifierPart(lookahead())) { - tmp = incr(); - return createEscaped('identifier', tmp.charCodeAt(0), tmp, 1); - } - - if (match(ZWJ)) { - // - return createEscaped('identifier', 0x200C, ZWJ); - } else if (match(ZWNJ)) { - // - return createEscaped('identifier', 0x200D, ZWNJ); - } - - return null; - } - - function parseCharacterClass() { - // CharacterClass :: - // [ [lookahead ∉ {^}] ClassRanges ] - // [ ^ ClassRanges ] - - var res, from = pos; - if (res = matchReg(/^\[\^/)) { - res = parseClassRanges(); - skip(']'); - return createCharacterClass(res, true, from, pos); - } else if (match('[')) { - res = parseClassRanges(); - skip(']'); - return createCharacterClass(res, false, from, pos); - } - - return null; - } - - function parseClassRanges() { - // ClassRanges :: - // [empty] - // NonemptyClassRanges - - var res; - if (current(']')) { - // Empty array means nothing insinde of the ClassRange. - return []; - } else { - res = parseNonemptyClassRanges(); - if (!res) { - bail('nonEmptyClassRanges'); - } - return res; - } - } - - function parseHelperClassRanges(atom) { - var from, to, res; - if (current('-') && !next(']')) { - // ClassAtom - ClassAtom ClassRanges - skip('-'); - - res = parseClassAtom(); - if (!res) { - bail('classAtom'); - } - to = pos; - var classRanges = parseClassRanges(); - if (!classRanges) { - bail('classRanges'); - } - from = atom.range[0]; - if (classRanges.type === 'empty') { - return [createClassRange(atom, res, from, to)]; - } - return [createClassRange(atom, res, from, to)].concat(classRanges); - } - - res = parseNonemptyClassRangesNoDash(); - if (!res) { - bail('nonEmptyClassRangesNoDash'); - } - - return [atom].concat(res); - } - - function parseNonemptyClassRanges() { - // NonemptyClassRanges :: - // ClassAtom - // ClassAtom NonemptyClassRangesNoDash - // ClassAtom - ClassAtom ClassRanges - - var atom = parseClassAtom(); - if (!atom) { - bail('classAtom'); - } - - if (current(']')) { - // ClassAtom - return [atom]; - } - - // ClassAtom NonemptyClassRangesNoDash - // ClassAtom - ClassAtom ClassRanges - return parseHelperClassRanges(atom); - } - - function parseNonemptyClassRangesNoDash() { - // NonemptyClassRangesNoDash :: - // ClassAtom - // ClassAtomNoDash NonemptyClassRangesNoDash - // ClassAtomNoDash - ClassAtom ClassRanges - - var res = parseClassAtom(); - if (!res) { - bail('classAtom'); - } - if (current(']')) { - // ClassAtom - return res; - } - - // ClassAtomNoDash NonemptyClassRangesNoDash - // ClassAtomNoDash - ClassAtom ClassRanges - return parseHelperClassRanges(res); - } - - function parseClassAtom() { - // ClassAtom :: - // - - // ClassAtomNoDash - if (match('-')) { - return createCharacter('-'); - } else { - return parseClassAtomNoDash(); - } - } - - function parseClassAtomNoDash() { - // ClassAtomNoDash :: - // SourceCharacter but not one of \ or ] or - - // \ ClassEscape - - var res; - if (res = matchReg(/^[^\\\]-]/)) { - return createCharacter(res[0]); - } else if (match('\\')) { - res = parseClassEscape(); - if (!res) { - bail('classEscape'); - } - - return parseUnicodeSurrogatePairEscape(res); - } - } - - function bail(message, details, from, to) { - from = from == null ? pos : from; - to = to == null ? from : to; - - var contextStart = Math.max(0, from - 10); - var contextEnd = Math.min(to + 10, str.length); - - // Output a bit of context and a line pointing to where our error is. - // - // We are assuming that there are no actual newlines in the content as this is a regular expression. - var context = ' ' + str.substring(contextStart, contextEnd); - var pointer = ' ' + new Array(from - contextStart + 1).join(' ') + '^'; - - throw SyntaxError(message + ' at position ' + from + (details ? ': ' + details : '') + '\n' + context + '\n' + pointer); - } - - var backrefDenied = []; - var closedCaptureCounter = 0; - var firstIteration = true; - var hasUnicodeFlag = (flags || "").indexOf("u") !== -1; - var pos = 0; - - // Convert the input to a string and treat the empty string special. - str = String(str); - if (str === '') { - str = '(?:)'; - } - - var result = parseDisjunction(); - - if (result.range[1] !== str.length) { - bail('Could not parse entire input - got stuck', '', result.range[1]); - } - - // The spec requires to interpret the `\2` in `/\2()()/` as backreference. - // As the parser collects the number of capture groups as the string is - // parsed it is impossible to make these decisions at the point when the - // `\2` is handled. In case the local decision turns out to be wrong after - // the parsing has finished, the input string is parsed a second time with - // the total number of capture groups set. - // - // SEE: https://github.com/jviereck/regjsparser/issues/70 - for (var i = 0; i < backrefDenied.length; i++) { - if (backrefDenied[i] <= closedCaptureCounter) { - // Parse the input a second time. - pos = 0; - firstIteration = false; - return parseDisjunction(); - } - } - - return result; - } - - var regjsparser = { - parse: parse - }; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = regjsparser; - } else { - window.regjsparser = regjsparser; - } - -}()); - -},{}],540:[function(require,module,exports){ -'use strict'; -var isFinite = require('is-finite'); - -module.exports = function (str, n) { - if (typeof str !== 'string') { - throw new TypeError('Expected `input` to be a string'); - } - - if (n < 0 || !isFinite(n)) { - throw new TypeError('Expected `count` to be a positive finite number'); - } - - var ret = ''; - - do { - if (n & 1) { - ret += str; - } - - str += str; - } while ((n >>= 1)); - - return ret; -}; - -},{"is-finite":293}],541:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var isExtendedLengthPath = /^\\\\\?\\/.test(str); - var hasNonAscii = /[^\x00-\x80]+/.test(str); - - if (isExtendedLengthPath || hasNonAscii) { - return str; - } - - return str.replace(/\\/g, '/'); -}; - -},{}],542:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); -var has = Object.prototype.hasOwnProperty; -var hasNativeMap = typeof Map !== "undefined"; - -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); -} - -/** - * Static method for creating ArraySet instances from an existing array. - */ -ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; -}; - -/** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ -ArraySet.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; -}; - -/** - * Add the given string to this set. - * - * @param String aStr - */ -ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } -}; - -/** - * Is the given string a member of this set? - * - * @param String aStr - */ -ArraySet.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); - } -}; - -/** - * What is the index of the given string in the array? - * - * @param String aStr - */ -ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); -}; - -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; - -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -exports.ArraySet = ArraySet; - -},{"./util":551}],543:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. 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 Google Inc. 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 - * 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. - */ - -var base64 = require('./base64'); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; - -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; - -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; - -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} - -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; - -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; - -},{"./base64":544}],544:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; -}; - -},{}],545:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; - -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } -} - -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; -}; - -},{}],546:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); - -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} - -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} - -/** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; - -/** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ -MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -exports.MappingList = MappingList; - -},{"./util":551}],547:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - -/** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} - -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); -} - -/** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } -} - -/** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; - -},{}],548:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); -var binarySearch = require('./binary-search'); -var ArraySet = require('./array-set').ArraySet; -var base64VLQ = require('./base64-vlq'); -var quickSort = require('./quick-sort').quickSort; - -function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); -} - -SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); -} - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. - -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } -}); - -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } -}); - -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; - -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; - } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -exports.SourceMapConsumer = SourceMapConsumer; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; -} - -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); - } -}); - -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); -} - -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } -}); - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - -},{"./array-set":542,"./base64-vlq":543,"./binary-search":545,"./quick-sort":547,"./util":551}],549:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var base64VLQ = require('./base64-vlq'); -var util = require('./util'); -var ArraySet = require('./array-set').ArraySet; -var MappingList = require('./mapping-list').MappingList; - -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} - -SourceMapGenerator.prototype._version = 3; - -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - -/** - * Externalize the source map. - */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - -exports.SourceMapGenerator = SourceMapGenerator; - -},{"./array-set":542,"./base64-vlq":543,"./mapping-list":546,"./util":551}],550:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; -var util = require('./util'); - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; - -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); -} - -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; - -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; - -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; -}; - -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; - -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; -}; - -exports.SourceNode = SourceNode; - -},{"./source-map-generator":549,"./util":551}],551:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; - -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; - -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; - -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; - -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; - -/** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; -} -exports.join = join; - -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); -}; - -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; - -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); - -function identity (s) { - return s; -} - -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; - -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; - -function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; -} - -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByOriginalPositions = compareByOriginalPositions; - -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; -} - -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - -},{}],552:[function(require,module,exports){ -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; -exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; -exports.SourceNode = require('./lib/source-node').SourceNode; - -},{"./lib/source-map-consumer":548,"./lib/source-map-generator":549,"./lib/source-node":550}],553:[function(require,module,exports){ -'use strict'; -var ansiRegex = require('ansi-regex')(); - -module.exports = function (str) { - return typeof str === 'string' ? str.replace(ansiRegex, '') : str; -}; - -},{"ansi-regex":1}],554:[function(require,module,exports){ -(function (process){ -'use strict'; -var argv = process.argv; - -var terminator = argv.indexOf('--'); -var hasFlag = function (flag) { - flag = '--' + flag; - var pos = argv.indexOf(flag); - return pos !== -1 && (terminator !== -1 ? pos < terminator : true); -}; - -module.exports = (function () { - if ('FORCE_COLOR' in process.env) { - return true; - } - - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return false; - } - - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return true; - } - - if (process.stdout && !process.stdout.isTTY) { - return false; - } - - if (process.platform === 'win32') { - return true; - } - - if ('COLORTERM' in process.env) { - return true; - } - - if (process.env.TERM === 'dumb') { - return false; - } - - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } - - return false; -})(); - -}).call(this,require('_process')) -},{"_process":525}],555:[function(require,module,exports){ -'use strict'; -module.exports = function toFastproperties(o) { - function Sub() {} - Sub.prototype = o; - var receiver = new Sub(); // create an instance - function ic() { return typeof receiver.foo; } // perform access - ic(); - ic(); - return o; - eval("o" + o); // ensure no dead code elimination -} - -},{}],556:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var tail = str.length; - - while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { - tail--; - } - - return str.slice(0, tail); -}; - -},{}],557:[function(require,module,exports){ -exports.isatty = function () { return false; }; - -function ReadStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.ReadStream = ReadStream; - -function WriteStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.WriteStream = WriteStream; - -},{}],558:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],559:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],560:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":559,"_process":525,"inherits":558}],561:[function(require,module,exports){ -/*import { transform as babelTransform } from 'babel-core'; -import babelTransformDynamicImport from 'babel-plugin-syntax-dynamic-import'; -import babelTransformES2015ModulesSystemJS from 'babel-plugin-transform-es2015-modules-systemjs';*/ - -// sadly, due to how rollup works, we can't use es6 imports here -var babelTransform = require('babel-core').transform; -var babelTransformDynamicImport = require('babel-plugin-syntax-dynamic-import'); -var babelTransformES2015ModulesSystemJS = require('babel-plugin-transform-es2015-modules-systemjs'); -var babelPresetES2015 = require('babel-preset-es2015'); - -self.onmessage = function (evt) { - // transform source with Babel - var output = babelTransform(evt.data.source, { - compact: false, - filename: evt.data.key + '!transpiled', - sourceFileName: evt.data.key, - moduleIds: false, - sourceMaps: 'inline', - babelrc: false, - plugins: [babelTransformDynamicImport, babelTransformES2015ModulesSystemJS], - presets: [babelPresetES2015], - }); - - self.postMessage({key: evt.data.key, code: output.code, source: evt.data.source}); -}; - -},{"babel-core":5,"babel-plugin-syntax-dynamic-import":63,"babel-plugin-transform-es2015-modules-systemjs":79,"babel-preset-es2015":94}]},{},[561]); diff --git a/kasmweb/vendor/browser-es-module-loader/dist/browser-es-module-loader.js b/kasmweb/vendor/browser-es-module-loader/dist/browser-es-module-loader.js deleted file mode 100644 index 6c8022d..0000000 --- a/kasmweb/vendor/browser-es-module-loader/dist/browser-es-module-loader.js +++ /dev/null @@ -1,1486 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.BrowserESModuleLoader = factory()); -}(this, (function () { 'use strict'; - -/* - * Environment - */ -var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; -var isNode = typeof process !== 'undefined' && process.versions && process.versions.node; -var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/); - -var envGlobal = typeof self !== 'undefined' ? self : global; -/* - * Simple Symbol() shim - */ -var hasSymbol = typeof Symbol !== 'undefined'; -function createSymbol (name) { - return hasSymbol ? Symbol() : '@@' + name; -} - -var toStringTag = hasSymbol && Symbol.toStringTag; - - - - - -/* - * Environment baseURI - */ -var baseURI; - -// environent baseURI detection -if (typeof document != 'undefined' && document.getElementsByTagName) { - baseURI = document.baseURI; - - if (!baseURI) { - var bases = document.getElementsByTagName('base'); - baseURI = bases[0] && bases[0].href || window.location.href; - } -} -else if (typeof location != 'undefined') { - baseURI = location.href; -} - -// sanitize out the hash and querystring -if (baseURI) { - baseURI = baseURI.split('#')[0].split('?')[0]; - var slashIndex = baseURI.lastIndexOf('/'); - if (slashIndex !== -1) - baseURI = baseURI.substr(0, slashIndex + 1); -} -else if (typeof process !== 'undefined' && process.cwd) { - baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd(); - if (isWindows) - baseURI = baseURI.replace(/\\/g, '/'); -} -else { - throw new TypeError('No environment baseURI'); -} - -// ensure baseURI has trailing "/" -if (baseURI[baseURI.length - 1] !== '/') - baseURI += '/'; - -/* - * LoaderError with chaining for loader stacks - */ -var errArgs = new Error(0, '_').fileName == '_'; -function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) { - // Convert file:/// URLs to paths in Node - if (!isBrowser) - newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, ''); - - var message = (childErr.message || childErr) + '\n ' + newMessage; - - var err; - if (errArgs && childErr.fileName) - err = new Error(message, childErr.fileName, childErr.lineNumber); - else - err = new Error(message); - - - var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack; - - if (isNode) - // node doesn't show the message otherwise - err.stack = message + '\n ' + stack; - else - err.stack = stack; - - err.originalErr = childErr.originalErr || childErr; - - return err; -} - -var resolvedPromise$1 = Promise.resolve(); - -/* - * Simple Array values shim - */ -function arrayValues (arr) { - if (arr.values) - return arr.values(); - - if (typeof Symbol === 'undefined' || !Symbol.iterator) - throw new Error('Symbol.iterator not supported in this browser'); - - var iterable = {}; - iterable[Symbol.iterator] = function () { - var keys = Object.keys(arr); - var keyIndex = 0; - return { - next: function () { - if (keyIndex < keys.length) - return { - value: arr[keys[keyIndex++]], - done: false - }; - else - return { - value: undefined, - done: true - }; - } - }; - }; - return iterable; -} - -/* - * 3. Reflect.Loader - * - * We skip the entire native internal pipeline, just providing the bare API - */ -// 3.1.1 -function Loader () { - this.registry = new Registry(); -} -// 3.3.1 -Loader.prototype.constructor = Loader; - -function ensureInstantiated (module) { - if (module === undefined) - return; - if (module instanceof ModuleNamespace === false && module[toStringTag] !== 'module') - throw new TypeError('Module instantiation did not return a valid namespace object.'); - return module; -} - -// 3.3.2 -Loader.prototype.import = function (key, parent) { - if (typeof key !== 'string') - throw new TypeError('Loader import method must be passed a module key string'); - // custom resolveInstantiate combined hook for better perf - var loader = this; - return resolvedPromise$1 - .then(function () { - return loader[RESOLVE_INSTANTIATE](key, parent); - }) - .then(ensureInstantiated) - //.then(Module.evaluate) - .catch(function (err) { - throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); - }); -}; -// 3.3.3 -var RESOLVE = Loader.resolve = createSymbol('resolve'); - -/* - * Combined resolve / instantiate hook - * - * Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described - * in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted. - * - * We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid - * the need for double registry lookups as a performance optimization. - */ -var RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate'); - -// default resolveInstantiate is just to call resolve and then get from the registry -// this provides compatibility for the resolveInstantiate optimization -Loader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) { - var loader = this; - return loader.resolve(key, parent) - .then(function (resolved) { - return loader.registry.get(resolved); - }); -}; - -function ensureResolution (resolvedKey) { - if (resolvedKey === undefined) - throw new RangeError('No resolution found.'); - return resolvedKey; -} - -Loader.prototype.resolve = function (key, parent) { - var loader = this; - return resolvedPromise$1 - .then(function() { - return loader[RESOLVE](key, parent); - }) - .then(ensureResolution) - .catch(function (err) { - throw LoaderError__Check_error_message_for_loader_stack(err, 'Resolving ' + key + (parent ? ' to ' + parent : '')); - }); -}; - -// 3.3.4 (import without evaluate) -// this is not documented because the use of deferred evaluation as in Module.evaluate is not -// documented, as it is not considered a stable feature to be encouraged -// Loader.prototype.load may well be deprecated if this stays disabled -/* Loader.prototype.load = function (key, parent) { - return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key)) - .catch(function (err) { - throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); - }); -}; */ - -/* - * 4. Registry - * - * Instead of structuring through a Map, just use a dictionary object - * We throw for construction attempts so this doesn't affect the public API - * - * Registry has been adjusted to use Namespace objects over ModuleStatus objects - * as part of simplifying loader API implementation - */ -var iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator; -var REGISTRY = createSymbol('registry'); -function Registry() { - this[REGISTRY] = {}; -} -// 4.4.1 -if (iteratorSupport) { - // 4.4.2 - Registry.prototype[Symbol.iterator] = function () { - return this.entries()[Symbol.iterator](); - }; - - // 4.4.3 - Registry.prototype.entries = function () { - var registry = this[REGISTRY]; - return arrayValues(Object.keys(registry).map(function (key) { - return [key, registry[key]]; - })); - }; -} - -// 4.4.4 -Registry.prototype.keys = function () { - return arrayValues(Object.keys(this[REGISTRY])); -}; -// 4.4.5 -Registry.prototype.values = function () { - var registry = this[REGISTRY]; - return arrayValues(Object.keys(registry).map(function (key) { - return registry[key]; - })); -}; -// 4.4.6 -Registry.prototype.get = function (key) { - return this[REGISTRY][key]; -}; -// 4.4.7 -Registry.prototype.set = function (key, namespace) { - if (!(namespace instanceof ModuleNamespace || namespace[toStringTag] === 'module')) - throw new Error('Registry must be set with an instance of Module Namespace'); - this[REGISTRY][key] = namespace; - return this; -}; -// 4.4.8 -Registry.prototype.has = function (key) { - return Object.hasOwnProperty.call(this[REGISTRY], key); -}; -// 4.4.9 -Registry.prototype.delete = function (key) { - if (Object.hasOwnProperty.call(this[REGISTRY], key)) { - delete this[REGISTRY][key]; - return true; - } - return false; -}; - -/* - * Simple ModuleNamespace Exotic object based on a baseObject - * We export this for allowing a fast-path for module namespace creation over Module descriptors - */ -// var EVALUATE = createSymbol('evaluate'); -var BASE_OBJECT = createSymbol('baseObject'); - -// 8.3.1 Reflect.Module -/* - * Best-effort simplified non-spec implementation based on - * a baseObject referenced via getters. - * - * Allows: - * - * loader.registry.set('x', new Module({ default: 'x' })); - * - * Optional evaluation function provides experimental Module.evaluate - * support for non-executed modules in registry. - */ -function ModuleNamespace (baseObject/*, evaluate*/) { - Object.defineProperty(this, BASE_OBJECT, { - value: baseObject - }); - - // evaluate defers namespace population - /* if (evaluate) { - Object.defineProperty(this, EVALUATE, { - value: evaluate, - configurable: true, - writable: true - }); - } - else { */ - Object.keys(baseObject).forEach(extendNamespace, this); - //} -} -// 8.4.2 -ModuleNamespace.prototype = Object.create(null); - -if (toStringTag) - Object.defineProperty(ModuleNamespace.prototype, toStringTag, { - value: 'Module' - }); - -function extendNamespace (key) { - Object.defineProperty(this, key, { - enumerable: true, - get: function () { - return this[BASE_OBJECT][key]; - } - }); -} - -/* function doEvaluate (evaluate, context) { - try { - evaluate.call(context); - } - catch (e) { - return e; - } -} - -// 8.4.1 Module.evaluate... not documented or used because this is potentially unstable -Module.evaluate = function (ns) { - var evaluate = ns[EVALUATE]; - if (evaluate) { - ns[EVALUATE] = undefined; - var err = doEvaluate(evaluate); - if (err) { - // cache the error - ns[EVALUATE] = function () { - throw err; - }; - throw err; - } - Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns); - } - // make chainable - return ns; -}; */ - -/* - * Optimized URL normalization assuming a syntax-valid URL parent - */ -function throwResolveError (relUrl, parentUrl) { - throw new RangeError('Unable to resolve "' + relUrl + '" to ' + parentUrl); -} -var backslashRegEx = /\\/g; -function resolveIfNotPlain (relUrl, parentUrl) { - if (relUrl[0] === ' ' || relUrl[relUrl.length - 1] === ' ') - relUrl = relUrl.trim(); - var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1); - - var firstChar = relUrl[0]; - var secondChar = relUrl[1]; - - // protocol-relative - if (firstChar === '/' && secondChar === '/') { - if (!parentProtocol) - throwResolveError(relUrl, parentUrl); - if (relUrl.indexOf('\\') !== -1) - relUrl = relUrl.replace(backslashRegEx, '/'); - return parentProtocol + relUrl; - } - // relative-url - else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) || - relUrl.length === 1 && (relUrl += '/')) || - firstChar === '/') { - if (relUrl.indexOf('\\') !== -1) - relUrl = relUrl.replace(backslashRegEx, '/'); - var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/'; - - // read pathname from parent if a URL - // pathname taken to be part after leading "/" - var pathname; - if (parentIsPlain) { - // resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname - if (parentUrl === undefined) - throwResolveError(relUrl, parentUrl); - pathname = parentUrl; - } - else if (parentUrl[parentProtocol.length + 1] === '/') { - // resolving to a :// so we need to read out the auth and host - if (parentProtocol !== 'file:') { - pathname = parentUrl.substr(parentProtocol.length + 2); - pathname = pathname.substr(pathname.indexOf('/') + 1); - } - else { - pathname = parentUrl.substr(8); - } - } - else { - // resolving to :/ so pathname is the /... part - pathname = parentUrl.substr(parentProtocol.length + 1); - } - - if (firstChar === '/') { - if (parentIsPlain) - throwResolveError(relUrl, parentUrl); - else - return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl; - } - - // join together and split for removal of .. and . segments - // looping the string instead of anything fancy for perf reasons - // '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain - var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl; - - var output = []; - var segmentIndex = -1; - - for (var i = 0; i < segmented.length; i++) { - // busy reading a segment - only terminate on '/' - if (segmentIndex !== -1) { - if (segmented[i] === '/') { - output.push(segmented.substring(segmentIndex, i + 1)); - segmentIndex = -1; - } - continue; - } - - // new segment - check if it is relative - if (segmented[i] === '.') { - // ../ segment - if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) { - output.pop(); - i += 2; - } - // ./ segment - else if (segmented[i + 1] === '/' || i + 1 === segmented.length) { - i += 1; - } - else { - // the start of a new segment as below - segmentIndex = i; - continue; - } - - // this is the plain URI backtracking error (../, package:x -> error) - if (parentIsPlain && output.length === 0) - throwResolveError(relUrl, parentUrl); - - continue; - } - - // it is the start of a new segment - segmentIndex = i; - } - // finish reading out the last segment - if (segmentIndex !== -1) - output.push(segmented.substr(segmentIndex)); - - return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join(''); - } - - // sanitizes and verifies (by returning undefined if not a valid URL-like form) - // Windows filepath compatibility is an added convenience here - var protocolIndex = relUrl.indexOf(':'); - if (protocolIndex !== -1) { - if (isNode) { - // C:\x becomes file:///c:/x (we don't support C|\x) - if (relUrl[1] === ':' && relUrl[2] === '\\' && relUrl[0].match(/[a-z]/i)) - return 'file:///' + relUrl.replace(backslashRegEx, '/'); - } - return relUrl; - } -} - -var resolvedPromise = Promise.resolve(); -/* - * Register Loader - * - * Builds directly on top of loader polyfill to provide: - * - loader.register support - * - hookable higher-level resolve - * - instantiate hook returning a ModuleNamespace or undefined for es module loading - * - loader error behaviour as in HTML and loader specs, caching load and eval errors separately - * - build tracing support by providing a .trace=true and .loads object format - */ - -var REGISTER_INTERNAL = createSymbol('register-internal'); - -function RegisterLoader$1 () { - Loader.call(this); - - var registryDelete = this.registry.delete; - this.registry.delete = function (key) { - var deleted = registryDelete.call(this, key); - - // also delete from register registry if linked - if (records.hasOwnProperty(key) && !records[key].linkRecord) { - delete records[key]; - deleted = true; - } - - return deleted; - }; - - var records = {}; - - this[REGISTER_INTERNAL] = { - // last anonymous System.register call - lastRegister: undefined, - // in-flight es module load records - records: records - }; - - // tracing - this.trace = false; -} - -RegisterLoader$1.prototype = Object.create(Loader.prototype); -RegisterLoader$1.prototype.constructor = RegisterLoader$1; - -var INSTANTIATE = RegisterLoader$1.instantiate = createSymbol('instantiate'); - -// default normalize is the WhatWG style normalizer -RegisterLoader$1.prototype[RegisterLoader$1.resolve = Loader.resolve] = function (key, parentKey) { - return resolveIfNotPlain(key, parentKey || baseURI); -}; - -RegisterLoader$1.prototype[INSTANTIATE] = function (key, processAnonRegister) {}; - -// once evaluated, the linkRecord is set to undefined leaving just the other load record properties -// this allows tracking new binding listeners for es modules through importerSetters -// for dynamic modules, the load record is removed entirely. -function createLoadRecord (state, key, registration) { - return state.records[key] = { - key: key, - - // defined System.register cache - registration: registration, - - // module namespace object - module: undefined, - - // es-only - // this sticks around so new module loads can listen to binding changes - // for already-loaded modules by adding themselves to their importerSetters - importerSetters: undefined, - - loadError: undefined, - evalError: undefined, - - // in-flight linking record - linkRecord: { - // promise for instantiated - instantiatePromise: undefined, - dependencies: undefined, - execute: undefined, - executingRequire: false, - - // underlying module object bindings - moduleObj: undefined, - - // es only, also indicates if es or not - setters: undefined, - - // promise for instantiated dependencies (dependencyInstantiations populated) - depsInstantiatePromise: undefined, - // will be the array of dependency load record or a module namespace - dependencyInstantiations: undefined, - - // top-level await! - evaluatePromise: undefined, - - // NB optimization and way of ensuring module objects in setters - // indicates setters which should run pre-execution of that dependency - // setters is then just for completely executed module objects - // alternatively we just pass the partially filled module objects as - // arguments into the execute function - // hoisted: undefined - } - }; -} - -RegisterLoader$1.prototype[Loader.resolveInstantiate] = function (key, parentKey) { - var loader = this; - var state = this[REGISTER_INTERNAL]; - var registry = this.registry[REGISTRY]; - - return resolveInstantiate(loader, key, parentKey, registry, state) - .then(function (instantiated) { - if (instantiated instanceof ModuleNamespace || instantiated[toStringTag] === 'module') - return instantiated; - - // resolveInstantiate always returns a load record with a link record and no module value - var link = instantiated.linkRecord; - - // if already beaten to done, return - if (!link) { - if (instantiated.module) - return instantiated.module; - throw instantiated.evalError; - } - - return deepInstantiateDeps(loader, instantiated, link, registry, state) - .then(function () { - return ensureEvaluate(loader, instantiated, link, registry, state); - }); - }); -}; - -function resolveInstantiate (loader, key, parentKey, registry, state) { - // normalization shortpath for already-normalized key - // could add a plain name filter, but doesn't yet seem necessary for perf - var module = registry[key]; - if (module) - return Promise.resolve(module); - - var load = state.records[key]; - - // already linked but not in main registry is ignored - if (load && !load.module) { - if (load.loadError) - return Promise.reject(load.loadError); - return instantiate(loader, load, load.linkRecord, registry, state); - } - - return loader.resolve(key, parentKey) - .then(function (resolvedKey) { - // main loader registry always takes preference - module = registry[resolvedKey]; - if (module) - return module; - - load = state.records[resolvedKey]; - - // already has a module value but not already in the registry (load.module) - // means it was removed by registry.delete, so we should - // disgard the current load record creating a new one over it - // but keep any existing registration - if (!load || load.module) - load = createLoadRecord(state, resolvedKey, load && load.registration); - - if (load.loadError) - return Promise.reject(load.loadError); - - var link = load.linkRecord; - if (!link) - return load; - - return instantiate(loader, load, link, registry, state); - }); -} - -function createProcessAnonRegister (loader, load, state) { - return function () { - var lastRegister = state.lastRegister; - - if (!lastRegister) - return !!load.registration; - - state.lastRegister = undefined; - load.registration = lastRegister; - - return true; - }; -} - -function instantiate (loader, load, link, registry, state) { - return link.instantiatePromise || (link.instantiatePromise = - // if there is already an existing registration, skip running instantiate - (load.registration ? resolvedPromise : resolvedPromise.then(function () { - state.lastRegister = undefined; - return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state)); - })) - .then(function (instantiation) { - // direct module return from instantiate -> we're done - if (instantiation !== undefined) { - if (!(instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module')) - throw new TypeError('Instantiate did not return a valid Module object.'); - - delete state.records[load.key]; - if (loader.trace) - traceLoad(loader, load, link); - return registry[load.key] = instantiation; - } - - // run the cached loader.register declaration if there is one - var registration = load.registration; - // clear to allow new registrations for future loads (combined with registry delete) - load.registration = undefined; - if (!registration) - throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.'); - - link.dependencies = registration[0]; - - load.importerSetters = []; - - link.moduleObj = {}; - - // process System.registerDynamic declaration - if (registration[2]) { - link.moduleObj.default = link.moduleObj.__useDefault = {}; - link.executingRequire = registration[1]; - link.execute = registration[2]; - } - - // process System.register declaration - else { - registerDeclarative(loader, load, link, registration[1]); - } - - return load; - }) - .catch(function (err) { - load.linkRecord = undefined; - throw load.loadError = load.loadError || LoaderError__Check_error_message_for_loader_stack(err, 'Instantiating ' + load.key); - })); -} - -// like resolveInstantiate, but returning load records for linking -function resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) { - // normalization shortpaths for already-normalized key - // DISABLED to prioritise consistent resolver calls - // could add a plain name filter, but doesn't yet seem necessary for perf - /* var load = state.records[key]; - var module = registry[key]; - - if (module) { - if (traceDepMap) - traceDepMap[key] = key; - - // registry authority check in case module was deleted or replaced in main registry - if (load && load.module && load.module === module) - return load; - else - return module; - } - - // already linked but not in main registry is ignored - if (load && !load.module) { - if (traceDepMap) - traceDepMap[key] = key; - return instantiate(loader, load, load.linkRecord, registry, state); - } */ - return loader.resolve(key, parentKey) - .then(function (resolvedKey) { - if (traceDepMap) - traceDepMap[key] = resolvedKey; - - // normalization shortpaths for already-normalized key - var load = state.records[resolvedKey]; - var module = registry[resolvedKey]; - - // main loader registry always takes preference - if (module && (!load || load.module && module !== load.module)) - return module; - - if (load && load.loadError) - throw load.loadError; - - // already has a module value but not already in the registry (load.module) - // means it was removed by registry.delete, so we should - // disgard the current load record creating a new one over it - // but keep any existing registration - if (!load || !module && load.module) - load = createLoadRecord(state, resolvedKey, load && load.registration); - - var link = load.linkRecord; - if (!link) - return load; - - return instantiate(loader, load, link, registry, state); - }); -} - -function traceLoad (loader, load, link) { - loader.loads = loader.loads || {}; - loader.loads[load.key] = { - key: load.key, - deps: link.dependencies, - dynamicDeps: [], - depMap: link.depMap || {} - }; -} - -/* - * Convert a CJS module.exports into a valid object for new Module: - * - * new Module(getEsModule(module.exports)) - * - * Sets the default value to the module, while also reading off named exports carefully. - */ -function registerDeclarative (loader, load, link, declare) { - var moduleObj = link.moduleObj; - var importerSetters = load.importerSetters; - - var definedExports = false; - - // closure especially not based on link to allow link record disposal - var declared = declare.call(envGlobal, function (name, value) { - if (typeof name === 'object') { - var changed = false; - for (var p in name) { - value = name[p]; - if (p !== '__useDefault' && (!(p in moduleObj) || moduleObj[p] !== value)) { - changed = true; - moduleObj[p] = value; - } - } - if (changed === false) - return value; - } - else { - if ((definedExports || name in moduleObj) && moduleObj[name] === value) - return value; - moduleObj[name] = value; - } - - for (var i = 0; i < importerSetters.length; i++) - importerSetters[i](moduleObj); - - return value; - }, new ContextualLoader(loader, load.key)); - - link.setters = declared.setters || []; - link.execute = declared.execute; - if (declared.exports) { - link.moduleObj = moduleObj = declared.exports; - definedExports = true; - } -} - -function instantiateDeps (loader, load, link, registry, state) { - if (link.depsInstantiatePromise) - return link.depsInstantiatePromise; - - var depsInstantiatePromises = Array(link.dependencies.length); - - for (var i = 0; i < link.dependencies.length; i++) - depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {})); - - var depsInstantiatePromise = Promise.all(depsInstantiatePromises) - .then(function (dependencyInstantiations) { - link.dependencyInstantiations = dependencyInstantiations; - - // run setters to set up bindings to instantiated dependencies - if (link.setters) { - for (var i = 0; i < dependencyInstantiations.length; i++) { - var setter = link.setters[i]; - if (setter) { - var instantiation = dependencyInstantiations[i]; - - if (instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module') { - setter(instantiation); - } - else { - if (instantiation.loadError) - throw instantiation.loadError; - setter(instantiation.module || instantiation.linkRecord.moduleObj); - // this applies to both es and dynamic registrations - if (instantiation.importerSetters) - instantiation.importerSetters.push(setter); - } - } - } - } - - return load; - }); - - if (loader.trace) - depsInstantiatePromise = depsInstantiatePromise.then(function () { - traceLoad(loader, load, link); - return load; - }); - - depsInstantiatePromise = depsInstantiatePromise.catch(function (err) { - // throw up the instantiateDeps stack - link.depsInstantiatePromise = undefined; - throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + load.key); - }); - - depsInstantiatePromise.catch(function () {}); - - return link.depsInstantiatePromise = depsInstantiatePromise; -} - -function deepInstantiateDeps (loader, load, link, registry, state) { - var seen = []; - function addDeps (load, link) { - if (!link) - return resolvedPromise; - if (seen.indexOf(load) !== -1) - return resolvedPromise; - seen.push(load); - - return instantiateDeps(loader, load, link, registry, state) - .then(function () { - var depPromises; - for (var i = 0; i < link.dependencies.length; i++) { - var depLoad = link.dependencyInstantiations[i]; - if (!(depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module')) { - depPromises = depPromises || []; - depPromises.push(addDeps(depLoad, depLoad.linkRecord)); - } - } - if (depPromises) - return Promise.all(depPromises); - }); - } - - return addDeps(load, link); -} - -/* - * System.register - */ -RegisterLoader$1.prototype.register = function (key, deps, declare) { - var state = this[REGISTER_INTERNAL]; - - // anonymous modules get stored as lastAnon - if (declare === undefined) { - state.lastRegister = [key, deps, undefined]; - } - - // everything else registers into the register cache - else { - var load = state.records[key] || createLoadRecord(state, key, undefined); - load.registration = [deps, declare, undefined]; - } -}; - -/* - * System.registerDyanmic - */ -RegisterLoader$1.prototype.registerDynamic = function (key, deps, executingRequire, execute) { - var state = this[REGISTER_INTERNAL]; - - // anonymous modules get stored as lastAnon - if (typeof key !== 'string') { - state.lastRegister = [key, deps, executingRequire]; - } - - // everything else registers into the register cache - else { - var load = state.records[key] || createLoadRecord(state, key, undefined); - load.registration = [deps, executingRequire, execute]; - } -}; - -// ContextualLoader class -// backwards-compatible with previous System.register context argument by exposing .id, .key -function ContextualLoader (loader, key) { - this.loader = loader; - this.key = this.id = key; - this.meta = { - url: key - // scriptElement: null - }; -} -/*ContextualLoader.prototype.constructor = function () { - throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.'); -};*/ -ContextualLoader.prototype.import = function (key) { - if (this.loader.trace) - this.loader.loads[this.key].dynamicDeps.push(key); - return this.loader.import(key, this.key); -}; -/*ContextualLoader.prototype.resolve = function (key) { - return this.loader.resolve(key, this.key); -};*/ - -function ensureEvaluate (loader, load, link, registry, state) { - if (load.module) - return load.module; - if (load.evalError) - throw load.evalError; - if (link.evaluatePromise) - return link.evaluatePromise; - - if (link.setters) { - var evaluatePromise = doEvaluateDeclarative(loader, load, link, registry, state, [load]); - if (evaluatePromise) - return evaluatePromise; - } - else { - doEvaluateDynamic(loader, load, link, registry, state, [load]); - } - return load.module; -} - -function makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) { - // we can only require from already-known dependencies - return function (name) { - for (var i = 0; i < dependencies.length; i++) { - if (dependencies[i] === name) { - var depLoad = dependencyInstantiations[i]; - var module; - - if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') { - module = depLoad; - } - else { - if (depLoad.evalError) - throw depLoad.evalError; - if (depLoad.module === undefined && seen.indexOf(depLoad) === -1 && !depLoad.linkRecord.evaluatePromise) { - if (depLoad.linkRecord.setters) { - doEvaluateDeclarative(loader, depLoad, depLoad.linkRecord, registry, state, [depLoad]); - } - else { - seen.push(depLoad); - doEvaluateDynamic(loader, depLoad, depLoad.linkRecord, registry, state, seen); - } - } - module = depLoad.module || depLoad.linkRecord.moduleObj; - } - - return '__useDefault' in module ? module.__useDefault : module; - } - } - throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key); - }; -} - -function evalError (load, err) { - load.linkRecord = undefined; - var evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key); - if (load.evalError === undefined) - load.evalError = evalError; - throw evalError; -} - -// es modules evaluate dependencies first -// returns the error if any -function doEvaluateDeclarative (loader, load, link, registry, state, seen) { - var depLoad, depLink; - var depLoadPromises; - for (var i = 0; i < link.dependencies.length; i++) { - var depLoad = link.dependencyInstantiations[i]; - if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') - continue; - - // custom Module returned from instantiate - depLink = depLoad.linkRecord; - if (depLink) { - if (depLoad.evalError) { - evalError(load, depLoad.evalError); - } - else if (depLink.setters) { - if (seen.indexOf(depLoad) === -1) { - seen.push(depLoad); - try { - var depLoadPromise = doEvaluateDeclarative(loader, depLoad, depLink, registry, state, seen); - } - catch (e) { - evalError(load, e); - } - if (depLoadPromise) { - depLoadPromises = depLoadPromises || []; - depLoadPromises.push(depLoadPromise.catch(function (err) { - evalError(load, err); - })); - } - } - } - else { - try { - doEvaluateDynamic(loader, depLoad, depLink, registry, state, [depLoad]); - } - catch (e) { - evalError(load, e); - } - } - } - } - - if (depLoadPromises) - return link.evaluatePromise = Promise.all(depLoadPromises) - .then(function () { - if (link.execute) { - // ES System.register execute - // "this" is null in ES - try { - var execPromise = link.execute.call(nullContext); - } - catch (e) { - evalError(load, e); - } - if (execPromise) - return execPromise.catch(function (e) { - evalError(load, e); - }) - .then(function () { - load.linkRecord = undefined; - return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - }); - } - - // dispose link record - load.linkRecord = undefined; - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - }); - - if (link.execute) { - // ES System.register execute - // "this" is null in ES - try { - var execPromise = link.execute.call(nullContext); - } - catch (e) { - evalError(load, e); - } - if (execPromise) - return link.evaluatePromise = execPromise.catch(function (e) { - evalError(load, e); - }) - .then(function () { - load.linkRecord = undefined; - return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - }); - } - - // dispose link record - load.linkRecord = undefined; - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); -} - -// non es modules explicitly call moduleEvaluate through require -function doEvaluateDynamic (loader, load, link, registry, state, seen) { - // System.registerDynamic execute - // "this" is "exports" in CJS - var module = { id: load.key }; - var moduleObj = link.moduleObj; - Object.defineProperty(module, 'exports', { - configurable: true, - set: function (exports) { - moduleObj.default = moduleObj.__useDefault = exports; - }, - get: function () { - return moduleObj.__useDefault; - } - }); - - var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen); - - // evaluate deps first - if (!link.executingRequire) - for (var i = 0; i < link.dependencies.length; i++) - require(link.dependencies[i]); - - try { - var output = link.execute.call(envGlobal, require, moduleObj.default, module); - if (output !== undefined) - module.exports = output; - } - catch (e) { - evalError(load, e); - } - - load.linkRecord = undefined; - - // pick up defineProperty calls to module.exports when we can - if (module.exports !== moduleObj.__useDefault) - moduleObj.default = moduleObj.__useDefault = module.exports; - - var moduleDefault = moduleObj.default; - - // __esModule flag extension support via lifting - if (moduleDefault && moduleDefault.__esModule) { - for (var p in moduleDefault) { - if (Object.hasOwnProperty.call(moduleDefault, p)) - moduleObj[p] = moduleDefault[p]; - } - } - - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - - // run importer setters and clear them - // this allows dynamic modules to update themselves into es modules - // as soon as execution has completed - if (load.importerSetters) - for (var i = 0; i < load.importerSetters.length; i++) - load.importerSetters[i](load.module); - load.importerSetters = undefined; -} - -// the closest we can get to call(undefined) -var nullContext = Object.create(null); -if (Object.freeze) - Object.freeze(nullContext); - -var loader; - -// - - - - - - - - - - - - - - -
-
-
Kasm encountered an error:
-
-
-
-
- -
- Loading statistics... -
- - -
- -
-
- -
- -

- - - - - -
- - - - - -
- - -
- -
-
- - - - - - -
-
-
- - - -
-
-
- Power -
- - - -
-
- - - -
-
-
- Clipboard -
- -
- -
-
- - - - - - -
-
-
    -
  • - Settings -
  • -
  • - -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • -
  • - - -
  • -
  • - - -
  • -

  • -
  • - -
  • -
  • - - -
  • -

  • -
  • -
    Advanced
    -
      -
    • - - -
    • -
    • -
      WebSocket
      -
        -
      • - -
      • -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
    • -

    • -
    • - -
    • -
    • - - -
    • -

    • -
    • - -
    • -

    • - -
    • - -
    • -
    -
  • -
-
-
- - - - -
-
- -
- -
- - - - - -
-
- -
- Connect -
-
-
- - -
-
-
    -
  • - - -
  • -
  • - -
  • -
-
-
- - -
-
-
- -
-
-
- - -
- - -
- - - - diff --git a/kasmweb/vnc_lite.html b/kasmweb/vnc_lite.html deleted file mode 100644 index 6e0040c..0000000 --- a/kasmweb/vnc_lite.html +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - KasmVNC - - - - - - - - - - - - - - - - - - - - -
-
Loading
-
Send CtrlAltDel
-
-
- -
- - diff --git a/kasmweb/webpack.config.js b/kasmweb/webpack.config.js deleted file mode 100644 index e4f0749..0000000 --- a/kasmweb/webpack.config.js +++ /dev/null @@ -1,138 +0,0 @@ -const path = require('path'); -const { CleanWebpackPlugin } = require('clean-webpack-plugin'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); - -const HtmlWebpackInlineSVGPlugin = require('html-webpack-inline-svg-plugin'); -const MiniCssExtractPlugin = require("mini-css-extract-plugin"); -// const SvgSpriteHtmlWebpackPlugin = require('svg-sprite-html-webpack'); -const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); - -module.exports = { - mode: "production", - entry: { - main: './app/ui.js', - error_handler: './app/error-handler.js', - promise: './vendor/promise.js', - style: './app/styles/base.css' - }, - output: { - path: path.resolve(__dirname, 'dist'), - filename: '[name].bundle.js' - }, - module: { - rules: [ - { - test: /\.js$/, - exclude: /(node_modules)/, - use: { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'] - } - } - }, - { - test: /\.(sa|sc|c)ss$/, - use: [ - { - loader: MiniCssExtractPlugin.loader - }, - { - loader: "css-loader", - }, - // { - // loader: "postcss-loader" - // }, - { - loader: "sass-loader", - options: { - implementation: require("sass") - } - } - ] - }, - { - // Now we apply rule for images - test: /\.(png|jpe?g|gif|svg)$/, - use: [ - { - // Using file-loader for these files - loader: "file-loader", - - // In options we can set different things like format - // and directory to save - options: { - outputPath: 'images' - } - } - ] - }, - { - // Apply rule for fonts files - test: /\.(woff|woff2|ttf|otf|eot)$/, - use: [ - { - // Using file-loader too - loader: "file-loader", - options: { - outputPath: 'fonts' - } - } - ] - }, - // { - // test: /\.svg$/, - // exclude: /node_modules/, - // use: SvgSpriteHtmlWebpackPlugin.getLoader(), - // } - ] - }, - optimization: { - minimize: true, - minimizer: [ - new CssMinimizerPlugin(), - ], - runtimeChunk: 'single', - splitChunks: { - chunks: 'all', - }, - }, - plugins: [ - new CleanWebpackPlugin(), - new HtmlWebpackPlugin({ - filename: '../index.html', - template: 'load.html', - minify: { - html5: true, - collapseWhitespace: true, - minifyCSS: true, - minifyJS: true, - minifyURLs: false, - removeAttributeQuotes: true, - removeComments: true, // false for Vue SSR to find app placeholder - removeEmptyAttributes: true, - removeOptionalTags: true, - removeRedundantAttributes: true, - removeScriptTypeAttributes: true, - removeStyleLinkTypeAttributese: true, - useShortDoctype: true - } - }), - // new SvgSpriteHtmlWebpackPlugin({ - // append: true, - // includeFiles: [ - // 'app/images/*.svg', - // ], - // generateSymbolId: function(svgFilePath, svgHash, svgContent) { - // return svgHash.toString(); - // }, - // }), - new HtmlWebpackInlineSVGPlugin({ - inlineAll: true, - runPreEmit: true, - }), - new MiniCssExtractPlugin({ - filename: "[name].bundle.css" - }), - ], -}; \ No newline at end of file diff --git a/unix/xserver/hw/vnc/RFBGlue.cc b/unix/xserver/hw/vnc/RFBGlue.cc index 6086025..7c32bea 100644 --- a/unix/xserver/hw/vnc/RFBGlue.cc +++ b/unix/xserver/hw/vnc/RFBGlue.cc @@ -1,5 +1,5 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. - * Copyright 2011-2015 Pierre Ossman for Cendio AB + * Copyright 2011-2019 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -226,3 +226,35 @@ int vncIsTCPPortUsed(int port) } return 0; } + +char* vncConvertLF(const char* src, size_t bytes) +{ + try { + return convertLF(src, bytes); + } catch (...) { + return NULL; + } +} + +char* vncLatin1ToUTF8(const char* src, size_t bytes) +{ + try { + return latin1ToUTF8(src, bytes); + } catch (...) { + return NULL; + } +} + +char* vncUTF8ToLatin1(const char* src, size_t bytes) +{ + try { + return utf8ToLatin1(src, bytes); + } catch (...) { + return NULL; + } +} + +void vncStrFree(char* str) +{ + strFree(str); +} diff --git a/unix/xserver/hw/vnc/RFBGlue.h b/unix/xserver/hw/vnc/RFBGlue.h index d62236a..695cea1 100644 --- a/unix/xserver/hw/vnc/RFBGlue.h +++ b/unix/xserver/hw/vnc/RFBGlue.h @@ -1,5 +1,5 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. - * Copyright 2011-2015 Pierre Ossman for Cendio AB + * Copyright 2011-2019 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -50,6 +50,13 @@ void vncListParams(int width, int nameWidth); int vncGetSocketPort(int fd); int vncIsTCPPortUsed(int port); +char* vncConvertLF(const char* src, size_t bytes); + +char* vncLatin1ToUTF8(const char* src, size_t bytes); +char* vncUTF8ToLatin1(const char* src, size_t bytes); + +void vncStrFree(char* str); + #ifdef __cplusplus } #endif diff --git a/unix/xserver/hw/vnc/XserverDesktop.cc b/unix/xserver/hw/vnc/XserverDesktop.cc index 0f8a241..872b2ec 100644 --- a/unix/xserver/hw/vnc/XserverDesktop.cc +++ b/unix/xserver/hw/vnc/XserverDesktop.cc @@ -176,25 +176,43 @@ XserverDesktop::queryConnection(network::Socket* sock, return rfb::VNCServerST::PENDING; } -void XserverDesktop::bell() +void XserverDesktop::requestClipboard() { - server->bell(); + try { + server->requestClipboard(); + } catch (rdr::Exception& e) { + vlog.error("XserverDesktop::requestClipboard: %s",e.str()); + } } -void XserverDesktop::setLEDState(unsigned int state) +void XserverDesktop::announceClipboard(bool available) { - server->setLEDState(state); + try { + server->announceClipboard(available); + } catch (rdr::Exception& e) { + vlog.error("XserverDesktop::announceClipboard: %s",e.str()); + } } -void XserverDesktop::serverCutText(const char* str, int len) +void XserverDesktop::sendClipboardData(const char* data) { try { - server->serverCutText(str, len); + server->sendClipboardData(data); } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::serverCutText: %s",e.str()); + vlog.error("XserverDesktop::sendClipboardData: %s",e.str()); } } +void XserverDesktop::bell() +{ + server->bell(); +} + +void XserverDesktop::setLEDState(unsigned int state) +{ + server->setLEDState(state); +} + void XserverDesktop::setDesktopName(const char* name) { try { @@ -241,6 +259,15 @@ void XserverDesktop::setCursor(int width, int height, int hotX, int hotY, delete [] cursorData; } +void XserverDesktop::setCursorPos(int x, int y, bool warped) +{ + try { + server->setCursorPos(Point(x, y), warped); + } catch (rdr::Exception& e) { + vlog.error("XserverDesktop::setCursorPos: %s",e.str()); + } +} + void XserverDesktop::add_changed(const rfb::Region ®ion) { try { @@ -358,7 +385,7 @@ void XserverDesktop::blockHandler(int* timeout) if (oldCursorPos.x != cursorX || oldCursorPos.y != cursorY) { oldCursorPos.x = cursorX; oldCursorPos.y = cursorY; - server->setCursorPos(oldCursorPos); + server->setCursorPos(oldCursorPos, false); } // Trigger timers and check when the next will expire @@ -426,11 +453,6 @@ void XserverDesktop::pointerEvent(const Point& pos, int buttonMask, vncPointerButtonAction(buttonMask, skipClick, skipRelease); } -void XserverDesktop::clientCutText(const char* str, int len) -{ - vncClientCutText(str, len); -} - unsigned int XserverDesktop::setScreenLayout(int fb_width, int fb_height, const rfb::ScreenSet& layout) { @@ -444,6 +466,21 @@ unsigned int XserverDesktop::setScreenLayout(int fb_width, int fb_height, return ::setScreenLayout(fb_width, fb_height, layout, &outputIdMap); } +void XserverDesktop::handleClipboardRequest() +{ + vncHandleClipboardRequest(); +} + +void XserverDesktop::handleClipboardAnnounce(bool available) +{ + vncHandleClipboardAnnounce(available); +} + +void XserverDesktop::handleClipboardData(const char* data_, int len) +{ + vncHandleClipboardData(data_, len); +} + void XserverDesktop::grabRegion(const rfb::Region& region) { if (directFbptr) diff --git a/unix/xserver/hw/vnc/XserverDesktop.h b/unix/xserver/hw/vnc/XserverDesktop.h index ec9bf37..e35f015 100644 --- a/unix/xserver/hw/vnc/XserverDesktop.h +++ b/unix/xserver/hw/vnc/XserverDesktop.h @@ -60,12 +60,15 @@ public: void unblockUpdates(); void setFramebuffer(int w, int h, void* fbptr, int stride); void refreshScreenLayout(); + void requestClipboard(); + void announceClipboard(bool available); + void sendClipboardData(const char* data); void bell(); void setLEDState(unsigned int state); - void serverCutText(const char* str, int len); void setDesktopName(const char* name); void setCursor(int width, int height, int hotX, int hotY, const unsigned char *rgbaData); + void setCursorPos(int x, int y, bool warped); void add_changed(const rfb::Region ®ion); void add_copied(const rfb::Region &dest, const rfb::Point &delta); void handleSocketEvent(int fd, bool read, bool write); @@ -89,9 +92,11 @@ public: virtual void pointerEvent(const rfb::Point& pos, int buttonMask, const bool skipClick, const bool skipRelease); virtual void keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down); - virtual void clientCutText(const char* str, int len); virtual unsigned int setScreenLayout(int fb_width, int fb_height, const rfb::ScreenSet& layout); + virtual void handleClipboardRequest(); + virtual void handleClipboardAnnounce(bool available); + virtual void handleClipboardData(const char* data, int len); // rfb::PixelBuffer callbacks virtual void grabRegion(const rfb::Region& r); diff --git a/unix/xserver/hw/vnc/qnum_to_xorgevdev.c b/unix/xserver/hw/vnc/qnum_to_xorgevdev.c index 357c88d..c93d5d2 100644 --- a/unix/xserver/hw/vnc/qnum_to_xorgevdev.c +++ b/unix/xserver/hw/vnc/qnum_to_xorgevdev.c @@ -1,8 +1,8 @@ /* - * This file is auto-generated from keymaps.csv on 2017-08-28 13:03 - * Database checksum sha256(f8aeff0c3430077a350e3d7ba2b335b381bd929ac4b193413730a402ff3f0097) + * This file is auto-generated from keymaps.csv + * Database checksum sha256(76d68c10e97d37fe2ea459e210125ae41796253fb217e900bf2983ade13a7920) * To re-generate, run: - * keymap-gen --lang=stdc code-map keymaps.csv qnum xorgevdev + * keymap-gen code-map --lang=stdc keymaps.csv qnum xorgevdev */ const unsigned short code_map_qnum_to_xorgevdev[254] = { [0x1] = 0x9, /* qnum:1 -> linux:1 (KEY_ESC) -> xorgevdev:9 */ @@ -112,9 +112,9 @@ const unsigned short code_map_qnum_to_xorgevdev[254] = { [0x6c] = 0xa9, /* qnum:108 -> linux:161 (KEY_EJECTCD) -> xorgevdev:169 */ [0x6d] = 0xc9, /* qnum:109 -> linux:193 (KEY_F23) -> xorgevdev:201 */ [0x6f] = 0xca, /* qnum:111 -> linux:194 (KEY_F24) -> xorgevdev:202 */ - [0x70] = 0xb2, /* qnum:112 -> linux:170 (KEY_ISO) -> xorgevdev:178 */ - [0x71] = 0xb6, /* qnum:113 -> linux:174 (KEY_EXIT) -> xorgevdev:182 */ - [0x72] = 0xb7, /* qnum:114 -> linux:175 (KEY_MOVE) -> xorgevdev:183 */ + [0x70] = 0x65, /* qnum:112 -> linux:93 (KEY_KATAKANAHIRAGANA) -> xorgevdev:101 */ + [0x71] = 0x83, /* qnum:113 -> linux:123 (KEY_HANJA) -> xorgevdev:131 */ + [0x72] = 0x82, /* qnum:114 -> linux:122 (KEY_HANGEUL) -> xorgevdev:130 */ [0x73] = 0x61, /* qnum:115 -> linux:89 (KEY_RO) -> xorgevdev:97 */ [0x74] = 0xc7, /* qnum:116 -> linux:191 (KEY_F21) -> xorgevdev:199 */ [0x75] = 0xb9, /* qnum:117 -> linux:177 (KEY_SCROLLUP) -> xorgevdev:185 */ @@ -137,7 +137,6 @@ const unsigned short code_map_qnum_to_xorgevdev[254] = { [0x8a] = 0xbe, /* qnum:138 -> linux:182 (KEY_REDO) -> xorgevdev:190 */ [0x8b] = 0x80, /* qnum:139 -> linux:120 (KEY_SCALE) -> xorgevdev:128 */ [0x8c] = 0x8c, /* qnum:140 -> linux:132 (KEY_FRONT) -> xorgevdev:140 */ - [0x8d] = 0x83, /* qnum:141 -> linux:123 (KEY_HANJA) -> xorgevdev:131 */ [0x8e] = 0xf1, /* qnum:142 -> linux:233 (KEY_FORWARDMAIL) -> xorgevdev:241 */ [0x8f] = 0xba, /* qnum:143 -> linux:178 (KEY_SCROLLDOWN) -> xorgevdev:186 */ [0x90] = 0xad, /* qnum:144 -> linux:165 (KEY_PREVIOUSSONG) -> xorgevdev:173 */ @@ -177,6 +176,7 @@ const unsigned short code_map_qnum_to_xorgevdev[254] = { [0xb4] = 0xd8, /* qnum:180 -> linux:208 (KEY_FASTFORWARD) -> xorgevdev:216 */ [0xb5] = 0x6a, /* qnum:181 -> linux:98 (KEY_KPSLASH) -> xorgevdev:106 */ [0xb6] = 0xd9, /* qnum:182 -> linux:209 (KEY_BASSBOOST) -> xorgevdev:217 */ + [0xb7] = 0x6b, /* qnum:183 -> linux:99 (KEY_SYSRQ) -> xorgevdev:107 */ [0xb8] = 0x6c, /* qnum:184 -> linux:100 (KEY_RIGHTALT) -> xorgevdev:108 */ [0xb9] = 0xda, /* qnum:185 -> linux:210 (KEY_PRINT) -> xorgevdev:218 */ [0xba] = 0xdb, /* qnum:186 -> linux:211 (KEY_HP) -> xorgevdev:219 */ diff --git a/unix/xserver/hw/vnc/qnum_to_xorgkbd.c b/unix/xserver/hw/vnc/qnum_to_xorgkbd.c index 57c2047..86632db 100644 --- a/unix/xserver/hw/vnc/qnum_to_xorgkbd.c +++ b/unix/xserver/hw/vnc/qnum_to_xorgkbd.c @@ -1,8 +1,8 @@ /* - * This file is auto-generated from keymaps.csv on 2017-08-28 13:04 - * Database checksum sha256(f8aeff0c3430077a350e3d7ba2b335b381bd929ac4b193413730a402ff3f0097) + * This file is auto-generated from keymaps.csv + * Database checksum sha256(76d68c10e97d37fe2ea459e210125ae41796253fb217e900bf2983ade13a7920) * To re-generate, run: - * keymap-gen --lang=stdc code-map keymaps.csv qnum xorgkbd + * keymap-gen code-map --lang=stdc keymaps.csv qnum xorgkbd */ const unsigned short code_map_qnum_to_xorgkbd[254] = { [0x1] = 0x9, /* qnum:1 -> linux:1 (KEY_ESC) -> xorgkbd:9 */ @@ -97,11 +97,15 @@ const unsigned short code_map_qnum_to_xorgkbd[254] = { [0x5d] = 0x76, /* qnum:93 -> linux:183 (KEY_F13) -> xorgkbd:118 */ [0x5e] = 0x77, /* qnum:94 -> linux:184 (KEY_F14) -> xorgkbd:119 */ [0x5f] = 0x78, /* qnum:95 -> linux:185 (KEY_F15) -> xorgkbd:120 */ + [0x70] = 0xd0, /* qnum:112 -> linux:93 (KEY_KATAKANAHIRAGANA) -> xorgkbd:208 */ + [0x71] = 0x7a, /* qnum:113 -> linux:123 (KEY_HANJA) -> xorgkbd:122 */ + [0x72] = 0x79, /* qnum:114 -> linux:122 (KEY_HANGEUL) -> xorgkbd:121 */ [0x7d] = 0x85, /* qnum:125 -> linux:124 (KEY_YEN) -> xorgkbd:133 */ [0x83] = 0x7a, /* qnum:131 -> linux:187 (KEY_F17) -> xorgkbd:122 */ [0x9c] = 0x6c, /* qnum:156 -> linux:96 (KEY_KPENTER) -> xorgkbd:108 */ [0x9d] = 0x6d, /* qnum:157 -> linux:97 (KEY_RIGHTCTRL) -> xorgkbd:109 */ [0xb5] = 0x70, /* qnum:181 -> linux:98 (KEY_KPSLASH) -> xorgkbd:112 */ + [0xb7] = 0x6f, /* qnum:183 -> linux:99 (KEY_SYSRQ) -> xorgkbd:111 */ [0xb8] = 0x71, /* qnum:184 -> linux:100 (KEY_RIGHTALT) -> xorgkbd:113 */ [0xc6] = 0x6e, /* qnum:198 -> linux:119 (KEY_PAUSE) -> xorgkbd:110 */ [0xc7] = 0x61, /* qnum:199 -> linux:102 (KEY_HOME) -> xorgkbd:97 */ diff --git a/unix/xserver/hw/vnc/vncExtInit.cc b/unix/xserver/hw/vnc/vncExtInit.cc index 99e00dc..6b60c0a 100644 --- a/unix/xserver/hw/vnc/vncExtInit.cc +++ b/unix/xserver/hw/vnc/vncExtInit.cc @@ -315,10 +315,22 @@ void vncUpdateDesktopName(void) desktop[scr]->setDesktopName(desktopName); } -void vncServerCutText(const char *text, size_t len) +void vncRequestClipboard(void) { for (int scr = 0; scr < vncGetScreenCount(); scr++) - desktop[scr]->serverCutText(text, len); + desktop[scr]->requestClipboard(); +} + +void vncAnnounceClipboard(int available) +{ + for (int scr = 0; scr < vncGetScreenCount(); scr++) + desktop[scr]->announceClipboard(available); +} + +void vncSendClipboardData(const char* data) +{ + for (int scr = 0; scr < vncGetScreenCount(); scr++) + desktop[scr]->sendClipboardData(data); } int vncConnectClient(const char *addr) @@ -418,6 +430,11 @@ void vncSetCursor(int width, int height, int hotX, int hotY, desktop[scr]->setCursor(width, height, hotX, hotY, rgbaData); } +void vncSetCursorPos(int scrIdx, int x, int y) +{ + desktop[scrIdx]->setCursorPos(x, y, true); +} + void vncPreScreenResize(int scrIdx) { // We need to prevent the RFB core from accessing the framebuffer diff --git a/unix/xserver/hw/vnc/vncExtInit.h b/unix/xserver/hw/vnc/vncExtInit.h index 9414723..943537d 100644 --- a/unix/xserver/hw/vnc/vncExtInit.h +++ b/unix/xserver/hw/vnc/vncExtInit.h @@ -60,7 +60,9 @@ int vncGetSendPrimary(void); void vncUpdateDesktopName(void); -void vncServerCutText(const char *text, size_t len); +void vncRequestClipboard(void); +void vncAnnounceClipboard(int available); +void vncSendClipboardData(const char* data); int vncConnectClient(const char *addr); @@ -86,6 +88,7 @@ void vncAddCopied(int scrIdx, const struct UpdateRect *extents, void vncSetCursor(int width, int height, int hotX, int hotY, const unsigned char *rgbaData); +void vncSetCursorPos(int scrIdx, int x, int y); void vncPreScreenResize(int scrIdx); void vncPostScreenResize(int scrIdx, int success, int width, int height); diff --git a/unix/xserver/hw/vnc/vncHooks.c b/unix/xserver/hw/vnc/vncHooks.c index e2be124..f48f756 100644 --- a/unix/xserver/hw/vnc/vncHooks.c +++ b/unix/xserver/hw/vnc/vncHooks.c @@ -65,6 +65,9 @@ typedef struct _vncHooksScreenRec { RestoreAreasProcPtr RestoreAreas; #endif DisplayCursorProcPtr DisplayCursor; +#if XORG >= 119 + CursorWarpedToProcPtr CursorWarpedTo; +#endif ScreenBlockHandlerProcPtr BlockHandler; #ifdef RENDER CompositeProcPtr Composite; @@ -137,6 +140,12 @@ static RegionPtr vncHooksRestoreAreas(WindowPtr pWin, RegionPtr prgnExposed); #endif static Bool vncHooksDisplayCursor(DeviceIntPtr pDev, ScreenPtr pScreen, CursorPtr cursor); +#if XORG >= 119 +static void vncHooksCursorWarpedTo(DeviceIntPtr pDev, + ScreenPtr pScreen_, ClientPtr pClient, + WindowPtr pWindow, SpritePtr pSprite, + int x, int y); +#endif #if XORG <= 112 static void vncHooksBlockHandler(int i, pointer blockData, pointer pTimeout, pointer pReadmask); @@ -316,6 +325,9 @@ int vncHooksInit(int scrIdx) wrap(vncHooksScreen, pScreen, RestoreAreas, vncHooksRestoreAreas); #endif wrap(vncHooksScreen, pScreen, DisplayCursor, vncHooksDisplayCursor); +#if XORG >= 119 + wrap(vncHooksScreen, pScreen, CursorWarpedTo, vncHooksCursorWarpedTo); +#endif wrap(vncHooksScreen, pScreen, BlockHandler, vncHooksBlockHandler); #ifdef RENDER ps = GetPictureScreenIfSet(pScreen); @@ -725,6 +737,20 @@ out: return ret; } +// CursorWarpedTo - notify that the cursor was warped + +#if XORG >= 119 +static void vncHooksCursorWarpedTo(DeviceIntPtr pDev, + ScreenPtr pScreen_, ClientPtr pClient, + WindowPtr pWindow, SpritePtr pSprite, + int x, int y) +{ + SCREEN_PROLOGUE(pScreen_, CursorWarpedTo); + vncSetCursorPos(pScreen->myNum, x, y); + SCREEN_EPILOGUE(CursorWarpedTo); +} +#endif + // BlockHandler - ignore any changes during the block handler - it's likely // these are just drawing the cursor. diff --git a/unix/xserver/hw/vnc/vncSelection.c b/unix/xserver/hw/vnc/vncSelection.c index 51dfd9c..21a2a61 100644 --- a/unix/xserver/hw/vnc/vncSelection.c +++ b/unix/xserver/hw/vnc/vncSelection.c @@ -1,4 +1,4 @@ -/* Copyright 2016 Pierre Ossman for Cendio AB +/* Copyright 2016-2019 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,15 +47,34 @@ static Atom xaTARGETS, xaTIMESTAMP, xaSTRING, xaTEXT, xaUTF8_STRING; static WindowPtr pWindow; static Window wid; -static char* clientCutText; -static int clientCutTextLen; +static Bool probing; +static Atom activeSelection = None; + +struct VncDataTarget { + ClientPtr client; + Atom selection; + Atom target; + Atom property; + Window requestor; + CARD32 time; + struct VncDataTarget* next; +}; + +static struct VncDataTarget* vncDataTargetHead; static int vncCreateSelectionWindow(void); static int vncOwnSelection(Atom selection); +static int vncConvertSelection(ClientPtr client, Atom selection, + Atom target, Atom property, + Window requestor, CARD32 time, + const char* data, int len); static int vncProcConvertSelection(ClientPtr client); +static void vncSelectionRequest(Atom selection, Atom target); static int vncProcSendEvent(ClientPtr client); static void vncSelectionCallback(CallbackListPtr *callbacks, void * data, void * args); +static void vncClientStateCallback(CallbackListPtr * l, + void * d, void * p); static int (*origProcConvertSelection)(ClientPtr); static int (*origProcSendEvent)(ClientPtr); @@ -80,34 +99,99 @@ void vncSelectionInit(void) if (!AddCallback(&SelectionCallback, vncSelectionCallback, 0)) FatalError("Add VNC SelectionCallback failed\n"); + if (!AddCallback(&ClientStateCallback, vncClientStateCallback, 0)) + FatalError("Add VNC ClientStateCallback failed\n"); } -void vncClientCutText(const char* str, int len) +void vncHandleClipboardRequest(void) { - int rc; - - if (clientCutText != NULL) - free(clientCutText); - - clientCutText = malloc(len); - if (clientCutText == NULL) { - LOG_ERROR("Could not allocate clipboard buffer"); - DeleteWindowFromAnySelections(pWindow); + if (activeSelection == None) { + LOG_DEBUG("Got request for local clipboard although no clipboard is active"); return; } - memcpy(clientCutText, str, len); - clientCutTextLen = len; + LOG_DEBUG("Got request for local clipboard, re-probing formats"); + + probing = FALSE; + vncSelectionRequest(activeSelection, xaTARGETS); +} + +void vncHandleClipboardAnnounce(int available) +{ + if (available) { + int rc; + + LOG_DEBUG("Remote clipboard announced, grabbing local ownership"); + + if (vncGetSetPrimary()) { + rc = vncOwnSelection(xaPRIMARY); + if (rc != Success) + LOG_ERROR("Could not set PRIMARY selection"); + } - if (vncGetSetPrimary()) { - rc = vncOwnSelection(xaPRIMARY); + rc = vncOwnSelection(xaCLIPBOARD); if (rc != Success) - LOG_ERROR("Could not set PRIMARY selection"); + LOG_ERROR("Could not set CLIPBOARD selection"); + } else { + struct VncDataTarget* next; + + if (pWindow == NULL) + return; + + LOG_DEBUG("Remote clipboard lost, removing local ownership"); + + DeleteWindowFromAnySelections(pWindow); + + /* Abort any pending transfer */ + while (vncDataTargetHead != NULL) { + xEvent event; + + event.u.u.type = SelectionNotify; + event.u.selectionNotify.time = vncDataTargetHead->time; + event.u.selectionNotify.requestor = vncDataTargetHead->requestor; + event.u.selectionNotify.selection = vncDataTargetHead->selection; + event.u.selectionNotify.target = vncDataTargetHead->target; + event.u.selectionNotify.property = None; + WriteEventsToClient(vncDataTargetHead->client, 1, &event); + + next = vncDataTargetHead->next; + free(vncDataTargetHead); + vncDataTargetHead = next; + } } +} - vncOwnSelection(xaCLIPBOARD); - if (rc != Success) - LOG_ERROR("Could not set CLIPBOARD selection"); +void vncHandleClipboardData(const char* data, int len) +{ + struct VncDataTarget* next; + + LOG_DEBUG("Got remote clipboard data, sending to X11 clients"); + + while (vncDataTargetHead != NULL) { + int rc; + xEvent event; + + rc = vncConvertSelection(vncDataTargetHead->client, + vncDataTargetHead->selection, + vncDataTargetHead->target, + vncDataTargetHead->property, + vncDataTargetHead->requestor, + vncDataTargetHead->time, + data, len); + if (rc != Success) { + event.u.u.type = SelectionNotify; + event.u.selectionNotify.time = vncDataTargetHead->time; + event.u.selectionNotify.requestor = vncDataTargetHead->requestor; + event.u.selectionNotify.selection = vncDataTargetHead->selection; + event.u.selectionNotify.target = vncDataTargetHead->target; + event.u.selectionNotify.property = None; + WriteEventsToClient(vncDataTargetHead->client, 1, &event); + } + + next = vncDataTargetHead->next; + free(vncDataTargetHead); + vncDataTargetHead = next; + } } static int vncCreateSelectionWindow(void) @@ -195,7 +279,8 @@ static int vncOwnSelection(Atom selection) static int vncConvertSelection(ClientPtr client, Atom selection, Atom target, Atom property, - Window requestor, CARD32 time) + Window requestor, CARD32 time, + const char* data, int len) { Selection *pSel; WindowPtr pWin; @@ -205,8 +290,13 @@ static int vncConvertSelection(ClientPtr client, Atom selection, xEvent event; - LOG_DEBUG("Selection request for %s (type %s)", - NameForAtom(selection), NameForAtom(target)); + if (data == NULL) { + LOG_DEBUG("Selection request for %s (type %s)", + NameForAtom(selection), NameForAtom(target)); + } else { + LOG_DEBUG("Sending data for selection request for %s (type %s)", + NameForAtom(selection), NameForAtom(target)); + } rc = dixLookupSelection(&pSel, selection, client, DixGetAttrAccess); if (rc != Success) @@ -243,51 +333,59 @@ static int vncConvertSelection(ClientPtr client, Atom selection, TRUE); if (rc != Success) return rc; - } else if ((target == xaSTRING) || (target == xaTEXT)) { - rc = dixChangeWindowProperty(serverClient, pWin, realProperty, - XA_STRING, 8, PropModeReplace, - clientCutTextLen, clientCutText, - TRUE); - if (rc != Success) - return rc; - } else if (target == xaUTF8_STRING) { - unsigned char* buffer; - unsigned char* out; - size_t len; - - const unsigned char* in; - size_t in_len; - - buffer = malloc(clientCutTextLen*2); - if (buffer == NULL) - return BadAlloc; - - out = buffer; - len = 0; - in = clientCutText; - in_len = clientCutTextLen; - while (in_len > 0) { - if (*in & 0x80) { - *out++ = 0xc0 | (*in >> 6); - *out++ = 0x80 | (*in & 0x3f); - len += 2; - in++; - in_len--; + } else { + if (data == NULL) { + struct VncDataTarget* vdt; + + if ((target != xaSTRING) && (target != xaTEXT) && + (target != xaUTF8_STRING)) + return BadMatch; + + vdt = calloc(1, sizeof(struct VncDataTarget)); + if (vdt == NULL) + return BadAlloc; + + vdt->client = client; + vdt->selection = selection; + vdt->target = target; + vdt->property = property; + vdt->requestor = requestor; + vdt->time = time; + + vdt->next = vncDataTargetHead; + vncDataTargetHead = vdt; + + LOG_DEBUG("Requesting clipboard data from client"); + + vncRequestClipboard(); + + return Success; + } else { + if ((target == xaSTRING) || (target == xaTEXT)) { + char* latin1; + + latin1 = vncUTF8ToLatin1(data, (size_t)-1); + if (latin1 == NULL) + return BadAlloc; + + rc = dixChangeWindowProperty(serverClient, pWin, realProperty, + XA_STRING, 8, PropModeReplace, + len, latin1, TRUE); + + vncStrFree(latin1); + + if (rc != Success) + return rc; + } else if (target == xaUTF8_STRING) { + rc = dixChangeWindowProperty(serverClient, pWin, realProperty, + xaUTF8_STRING, 8, PropModeReplace, + len, data, TRUE); + if (rc != Success) + return rc; } else { - *out++ = *in++; - len++; - in_len--; + return BadMatch; } } - - rc = dixChangeWindowProperty(serverClient, pWin, realProperty, - xaUTF8_STRING, 8, PropModeReplace, - len, buffer, TRUE); - free(buffer); - if (rc != Success) - return rc; - } else { - return BadMatch; } event.u.u.type = SelectionNotify; @@ -326,7 +424,7 @@ static int vncProcConvertSelection(ClientPtr client) pSel->window == wid) { rc = vncConvertSelection(client, stuff->selection, stuff->target, stuff->property, - stuff->requestor, stuff->time); + stuff->requestor, stuff->time, NULL, 0); if (rc != Success) { xEvent event; @@ -410,69 +508,61 @@ static void vncHandleSelection(Atom selection, Atom target, if (prop->type != XA_ATOM) return; - if (vncHasAtom(xaSTRING, (const Atom*)prop->data, prop->size)) - vncSelectionRequest(selection, xaSTRING); - else if (vncHasAtom(xaUTF8_STRING, (const Atom*)prop->data, prop->size)) - vncSelectionRequest(selection, xaUTF8_STRING); + if (probing) { + if (vncHasAtom(xaSTRING, (const Atom*)prop->data, prop->size) || + vncHasAtom(xaUTF8_STRING, (const Atom*)prop->data, prop->size)) { + LOG_DEBUG("Compatible format found, notifying clients"); + activeSelection = selection; + vncAnnounceClipboard(TRUE); + } + } else { + if (vncHasAtom(xaUTF8_STRING, (const Atom*)prop->data, prop->size)) + vncSelectionRequest(selection, xaUTF8_STRING); + else if (vncHasAtom(xaSTRING, (const Atom*)prop->data, prop->size)) + vncSelectionRequest(selection, xaSTRING); + } } else if (target == xaSTRING) { + char* filtered; + char* utf8; + if (prop->format != 8) return; if (prop->type != xaSTRING) return; - vncServerCutText(prop->data, prop->size); - } else if (target == xaUTF8_STRING) { - unsigned char* buffer; - unsigned char* out; - size_t len; + filtered = vncConvertLF(prop->data, prop->size); + if (filtered == NULL) + return; + + utf8 = vncLatin1ToUTF8(filtered, (size_t)-1); + vncStrFree(filtered); + if (utf8 == NULL) + return; + + LOG_DEBUG("Sending clipboard to clients (%d bytes)", + (int)strlen(utf8)); - const unsigned char* in; - size_t in_len; + vncSendClipboardData(utf8); + + vncStrFree(utf8); + } else if (target == xaUTF8_STRING) { + char *filtered; if (prop->format != 8) return; if (prop->type != xaUTF8_STRING) return; - buffer = malloc(prop->size); - if (buffer == NULL) + filtered = vncConvertLF(prop->data, prop->size); + if (filtered == NULL) return; - out = buffer; - len = 0; - in = prop->data; - in_len = prop->size; - while (in_len > 0) { - if ((*in & 0x80) == 0x00) { - *out++ = *in++; - len++; - in_len--; - } else if ((*in & 0xe0) == 0xc0) { - unsigned ucs; - ucs = (*in++ & 0x1f) << 6; - in_len--; - if (in_len > 0) { - ucs |= (*in++ & 0x3f); - in_len--; - } - if (ucs <= 0xff) - *out++ = ucs; - else - *out++ = '?'; - len++; - } else { - *out++ = '?'; - len++; - do { - in++; - in_len--; - } while ((in_len > 0) && ((*in & 0xc0) == 0x80)); - } - } + LOG_DEBUG("Sending clipboard to clients (%d bytes)", + (int)strlen(filtered)); - vncServerCutText((const char*)buffer, len); + vncSendClipboardData(filtered); - free(buffer); + vncStrFree(filtered); } } @@ -504,6 +594,12 @@ static void vncSelectionCallback(CallbackListPtr *callbacks, { SelectionInfoRec *info = (SelectionInfoRec *) args; + if (info->selection->selection == activeSelection) { + LOG_DEBUG("Local clipboard lost, notifying clients"); + activeSelection = None; + vncAnnounceClipboard(FALSE); + } + if (info->kind != SelectionSetOwner) return; if (info->client == serverClient) @@ -512,6 +608,13 @@ static void vncSelectionCallback(CallbackListPtr *callbacks, LOG_DEBUG("Selection owner change for %s", NameForAtom(info->selection->selection)); + /* + * If we're the previous owner of this selection, then we're also the + * owner of _the other_ selection. Make sure we drop all ownerships so + * we either own both selections or nonw. + */ + DeleteWindowFromAnySelections(pWindow); + if ((info->selection->selection != xaPRIMARY) && (info->selection->selection != xaCLIPBOARD)) return; @@ -520,5 +623,25 @@ static void vncSelectionCallback(CallbackListPtr *callbacks, !vncGetSendPrimary()) return; + LOG_DEBUG("Got clipboard notification, probing for formats"); + + probing = TRUE; vncSelectionRequest(info->selection->selection, xaTARGETS); } + +static void vncClientStateCallback(CallbackListPtr * l, + void * d, void * p) +{ + ClientPtr client = ((NewClientInfoRec*)p)->client; + if (client->clientState == ClientStateGone) { + struct VncDataTarget** nextPtr = &vncDataTargetHead; + for (struct VncDataTarget* cur = vncDataTargetHead; cur; cur = *nextPtr) { + if (cur->client == client) { + *nextPtr = cur->next; + free(cur); + continue; + } + nextPtr = &cur->next; + } + } +} diff --git a/unix/xserver/hw/vnc/vncSelection.h b/unix/xserver/hw/vnc/vncSelection.h index 969f895..337f9bf 100644 --- a/unix/xserver/hw/vnc/vncSelection.h +++ b/unix/xserver/hw/vnc/vncSelection.h @@ -1,4 +1,4 @@ -/* Copyright 2016 Pierre Ossman for Cendio AB +/* Copyright 2016-2019 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,7 +24,9 @@ extern "C" { void vncSelectionInit(void); -void vncClientCutText(const char* str, int len); +void vncHandleClipboardRequest(void); +void vncHandleClipboardAnnounce(int available); +void vncHandleClipboardData(const char* data, int len); #ifdef __cplusplus } diff --git a/win/rfb_win32/SDisplay.cxx b/win/rfb_win32/SDisplay.cxx index 9b2cbb0..1c9a0ac 100644 --- a/win/rfb_win32/SDisplay.cxx +++ b/win/rfb_win32/SDisplay.cxx @@ -385,7 +385,7 @@ SDisplay::processEvent(HANDLE event) { // Update the cursor position // NB: First translate from Screen coordinates to Desktop Point desktopPos = info.position.translate(screenRect.tl.negate()); - server->setCursorPos(desktopPos); + server->setCursorPos(desktopPos, false); old_cursor = info; }