installed pty
authorVSORC <josuer08@gmail.com>
Thu, 14 Nov 2019 20:10:32 +0000 (16:10 -0400)
committerVSORC <josuer08@gmail.com>
Thu, 14 Nov 2019 20:10:32 +0000 (16:10 -0400)
401 files changed:
fifo [new file with mode: 0644]
img/pc.svg
img/pcold.svg [deleted file]
img/switch.png [new file with mode: 0644]
img/switch.svg [deleted file]
img/switch2.svg [deleted file]
js/topology/flowtables.js
js/topology/topology.js
node_modules/node-pty/LICENSE [new file with mode: 0644]
node_modules/node-pty/README.md [new file with mode: 0644]
node_modules/node-pty/binding.gyp [new file with mode: 0644]
node_modules/node-pty/build/Makefile [new file with mode: 0644]
node_modules/node-pty/build/Release/pty.node [new file with mode: 0755]
node_modules/node-pty/build/binding.Makefile [new file with mode: 0644]
node_modules/node-pty/build/config.gypi [new file with mode: 0644]
node_modules/node-pty/build/pty.target.mk [new file with mode: 0644]
node_modules/node-pty/deps/.editorconfig [new file with mode: 0644]
node_modules/node-pty/deps/winpty/.drone.yml [new file with mode: 0644]
node_modules/node-pty/deps/winpty/.gitattributes [new file with mode: 0644]
node_modules/node-pty/deps/winpty/.gitignore [new file with mode: 0644]
node_modules/node-pty/deps/winpty/LICENSE [new file with mode: 0644]
node_modules/node-pty/deps/winpty/Makefile [new file with mode: 0644]
node_modules/node-pty/deps/winpty/README.md [new file with mode: 0644]
node_modules/node-pty/deps/winpty/RELEASES.md [new file with mode: 0644]
node_modules/node-pty/deps/winpty/VERSION.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/configure [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/.gitignore [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/BufferResizeTests.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ChangeScreenBuffer.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ClearConsole.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ConinMode.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ConinMode.ps1 [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ConoutMode.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/DebugClient.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/DebugServer.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/DumpLines.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/EnableExtendedFlags.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Consolas.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Lucida.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP932.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP936.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP949.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP950.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/MinimumWindowWidths.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Results.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Windows10SetFontBugginess.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/FontSurvey.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/FormatChar.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/FreezePerfTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/GetCh.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/GetConsolePos.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/GetFont.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/IdentifyConsoleWindow.ps1 [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/IsNewConsole.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/MouseInputNotes.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/MoveConsoleWindow.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Notes.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/OSVersion.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ScreenBufferFreezeInactive.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ScreenBufferTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ScreenBufferTest2.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/SelectAllTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/SetBufferSize.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/SetCursorPos.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/SetFont.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/SetWindowRect.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ShowArgv.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/ShowConsoleInput.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Spew.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/TestUtil.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/UnicodeDoubleWidthTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/UnicodeWideTest1.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/UnicodeWideTest2.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/UnixEcho.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Utf16Echo.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/VeryLargeRead.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/VkEscapeTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win10ResizeWhileFrozen.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win10WrapTest1.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win10WrapTest2.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win32Echo1.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win32Echo2.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win32Test1.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win32Test2.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win32Test3.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/Win32Write1.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/WindowsBugCrashReader.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/WriteConsole.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/build32.sh [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/build64.sh [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/color-test.sh [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/font-notes.txt [new file with mode: 0644]
node_modules/node-pty/deps/winpty/misc/winbug-15048.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/ship/build-pty4j-libpty.bat [new file with mode: 0644]
node_modules/node-pty/deps/winpty/ship/common_ship.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/ship/make_msvc_package.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/ship/ship.py [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Agent.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Agent.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Coord.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/DsrSender.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/EventLoop.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/EventLoop.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/InputMap.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/InputMap.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/NamedPipe.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/NamedPipe.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Scraper.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Scraper.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/SimplePool.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/SmallRect.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Terminal.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Terminal.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/UnicodeEncoding.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/UnicodeEncodingTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Win32Console.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Win32Console.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/main.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/agent/subdir.mk [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/configurations.gypi [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/debugserver/DebugServer.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/debugserver/subdir.mk [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/include/winpty.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/include/winpty_constants.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/libwinpty/LibWinptyException.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/libwinpty/WinptyInternal.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/libwinpty/subdir.mk [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/libwinpty/winpty.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/AgentMsg.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/Buffer.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/Buffer.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/DebugClient.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/DebugClient.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/GenRandom.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/GenRandom.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/GetCommitHash.bat [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/Mutex.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/OsModule.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/PrecompiledHeader.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/StringBuilder.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/StringBuilderTest.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/StringUtil.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/StringUtil.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/TimeMeasurement.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/UnixCtrlChars.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/UpdateGenVersion.bat [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WinptyException.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WinptyException.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/shared/winpty_snprintf.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/subdir.mk [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/tests/subdir.mk [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/tests/trivial_test.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/Util.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/Util.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.h [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/main.cc [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/unix-adapter/subdir.mk [new file with mode: 0644]
node_modules/node-pty/deps/winpty/src/winpty.gyp [new file with mode: 0644]
node_modules/node-pty/deps/winpty/vcbuild.bat [new file with mode: 0644]
node_modules/node-pty/lib/conpty_console_list_agent.js [new file with mode: 0644]
node_modules/node-pty/lib/conpty_console_list_agent.js.map [new file with mode: 0644]
node_modules/node-pty/lib/eventEmitter2.js [new file with mode: 0644]
node_modules/node-pty/lib/eventEmitter2.js.map [new file with mode: 0644]
node_modules/node-pty/lib/eventEmitter2.test.js [new file with mode: 0644]
node_modules/node-pty/lib/eventEmitter2.test.js.map [new file with mode: 0644]
node_modules/node-pty/lib/index.js [new file with mode: 0644]
node_modules/node-pty/lib/index.js.map [new file with mode: 0644]
node_modules/node-pty/lib/interfaces.js [new file with mode: 0644]
node_modules/node-pty/lib/interfaces.js.map [new file with mode: 0644]
node_modules/node-pty/lib/terminal.js [new file with mode: 0644]
node_modules/node-pty/lib/terminal.js.map [new file with mode: 0644]
node_modules/node-pty/lib/terminal.test.js [new file with mode: 0644]
node_modules/node-pty/lib/terminal.test.js.map [new file with mode: 0644]
node_modules/node-pty/lib/testUtils.test.js [new file with mode: 0644]
node_modules/node-pty/lib/testUtils.test.js.map [new file with mode: 0644]
node_modules/node-pty/lib/types.js [new file with mode: 0644]
node_modules/node-pty/lib/types.js.map [new file with mode: 0644]
node_modules/node-pty/lib/unixTerminal.js [new file with mode: 0644]
node_modules/node-pty/lib/unixTerminal.js.map [new file with mode: 0644]
node_modules/node-pty/lib/unixTerminal.test.js [new file with mode: 0644]
node_modules/node-pty/lib/unixTerminal.test.js.map [new file with mode: 0644]
node_modules/node-pty/lib/utils.js [new file with mode: 0644]
node_modules/node-pty/lib/utils.js.map [new file with mode: 0644]
node_modules/node-pty/lib/windowsPtyAgent.js [new file with mode: 0644]
node_modules/node-pty/lib/windowsPtyAgent.js.map [new file with mode: 0644]
node_modules/node-pty/lib/windowsPtyAgent.test.js [new file with mode: 0644]
node_modules/node-pty/lib/windowsPtyAgent.test.js.map [new file with mode: 0644]
node_modules/node-pty/lib/windowsTerminal.js [new file with mode: 0644]
node_modules/node-pty/lib/windowsTerminal.js.map [new file with mode: 0644]
node_modules/node-pty/lib/windowsTerminal.test.js [new file with mode: 0644]
node_modules/node-pty/lib/windowsTerminal.test.js.map [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/CHANGELOG.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/LICENSE.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/README.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/asyncworker.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/buffers.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/callback.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/converters.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/errors.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/json.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/maybe_types.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/methods.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/new.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/node_misc.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/object_wrappers.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/persistent.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/scopes.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/script.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/string_bytes.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/v8_internals.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/doc/v8_misc.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/include_dirs.js [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_callbacks.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_callbacks_12_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_callbacks_pre_12_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_converters.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_converters_43_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_converters_pre_43_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_define_own_property_helper.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_implementation_12_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_implementation_pre_12_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_json.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_maybe_43_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_maybe_pre_43_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_new.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_object_wrap.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_persistent_12_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_persistent_pre_12_inl.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_private.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_string_bytes.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_typedarray_contents.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/nan_weak.h [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/package.json [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/tools/1to2.js [new file with mode: 0755]
node_modules/node-pty/node_modules/nan/tools/README.md [new file with mode: 0644]
node_modules/node-pty/node_modules/nan/tools/package.json [new file with mode: 0644]
node_modules/node-pty/package.json [new file with mode: 0644]
node_modules/node-pty/scripts/install.js [new file with mode: 0644]
node_modules/node-pty/scripts/post-install.js [new file with mode: 0644]
node_modules/node-pty/scripts/publish.js [new file with mode: 0644]
node_modules/node-pty/src/conpty_console_list_agent.ts [new file with mode: 0644]
node_modules/node-pty/src/eventEmitter2.test.ts [new file with mode: 0644]
node_modules/node-pty/src/eventEmitter2.ts [new file with mode: 0644]
node_modules/node-pty/src/index.ts [new file with mode: 0644]
node_modules/node-pty/src/interfaces.ts [new file with mode: 0644]
node_modules/node-pty/src/native.d.ts [new file with mode: 0644]
node_modules/node-pty/src/terminal.test.ts [new file with mode: 0644]
node_modules/node-pty/src/terminal.ts [new file with mode: 0644]
node_modules/node-pty/src/testUtils.test.ts [new file with mode: 0644]
node_modules/node-pty/src/types.ts [new file with mode: 0644]
node_modules/node-pty/src/unix/pty.cc [new file with mode: 0644]
node_modules/node-pty/src/unixTerminal.test.ts [new file with mode: 0644]
node_modules/node-pty/src/unixTerminal.ts [new file with mode: 0644]
node_modules/node-pty/src/utils.ts [new file with mode: 0644]
node_modules/node-pty/src/win/conpty.cc [new file with mode: 0644]
node_modules/node-pty/src/win/conpty_console_list.cc [new file with mode: 0644]
node_modules/node-pty/src/win/path_util.cc [new file with mode: 0644]
node_modules/node-pty/src/win/path_util.h [new file with mode: 0644]
node_modules/node-pty/src/win/winpty.cc [new file with mode: 0644]
node_modules/node-pty/src/windowsPtyAgent.test.ts [new file with mode: 0644]
node_modules/node-pty/src/windowsPtyAgent.ts [new file with mode: 0644]
node_modules/node-pty/src/windowsTerminal.test.ts [new file with mode: 0644]
node_modules/node-pty/src/windowsTerminal.ts [new file with mode: 0644]
node_modules/node-pty/typings/node-pty.d.ts [new file with mode: 0644]
node_modules/xterm/LICENSE [new file with mode: 0644]
node_modules/xterm/README.md [new file with mode: 0644]
node_modules/xterm/css/xterm.css [new file with mode: 0644]
node_modules/xterm/lib/xterm.js [new file with mode: 0644]
node_modules/xterm/lib/xterm.js.map [new file with mode: 0644]
node_modules/xterm/package.json [new file with mode: 0644]
node_modules/xterm/src/AccessibilityManager.ts [new file with mode: 0644]
node_modules/xterm/src/InputHandler.ts [new file with mode: 0644]
node_modules/xterm/src/Terminal.ts [new file with mode: 0644]
node_modules/xterm/src/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/WindowsMode.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Clipboard.ts [new file with mode: 0644]
node_modules/xterm/src/browser/ColorManager.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Lifecycle.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Linkifier.ts [new file with mode: 0644]
node_modules/xterm/src/browser/LocalizableStrings.ts [new file with mode: 0644]
node_modules/xterm/src/browser/MouseZoneManager.ts [new file with mode: 0644]
node_modules/xterm/src/browser/RenderDebouncer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/ScreenDprMonitor.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/Viewport.ts [new file with mode: 0644]
node_modules/xterm/src/browser/input/CompositionHelper.ts [new file with mode: 0644]
node_modules/xterm/src/browser/input/Mouse.ts [new file with mode: 0644]
node_modules/xterm/src/browser/input/MoveToCell.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/GridCache.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/RendererUtils.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/TextRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/Constants.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/atlas/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts [new file with mode: 0644]
node_modules/xterm/src/browser/selection/SelectionModel.ts [new file with mode: 0644]
node_modules/xterm/src/browser/selection/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/CharSizeService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/MouseService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/RenderService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/SelectionService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/Services.ts [new file with mode: 0644]
node_modules/xterm/src/browser/services/SoundService.ts [new file with mode: 0644]
node_modules/xterm/src/browser/tsconfig.json [new file with mode: 0644]
node_modules/xterm/src/common/CharWidth.ts [new file with mode: 0644]
node_modules/xterm/src/common/CircularList.ts [new file with mode: 0644]
node_modules/xterm/src/common/Clone.ts [new file with mode: 0644]
node_modules/xterm/src/common/EventEmitter.ts [new file with mode: 0644]
node_modules/xterm/src/common/Lifecycle.ts [new file with mode: 0644]
node_modules/xterm/src/common/Platform.ts [new file with mode: 0644]
node_modules/xterm/src/common/TypedArrayUtils.ts [new file with mode: 0644]
node_modules/xterm/src/common/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/AttributeData.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Buffer.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/BufferLine.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/BufferReflow.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/BufferSet.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/CellData.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Constants.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Marker.ts [new file with mode: 0644]
node_modules/xterm/src/common/buffer/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/common/data/Charsets.ts [new file with mode: 0644]
node_modules/xterm/src/common/data/EscapeSequences.ts [new file with mode: 0644]
node_modules/xterm/src/common/input/Keyboard.ts [new file with mode: 0644]
node_modules/xterm/src/common/input/TextDecoder.ts [new file with mode: 0644]
node_modules/xterm/src/common/input/WriteBuffer.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/Constants.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/DcsParser.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/EscapeSequenceParser.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/OscParser.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/Params.ts [new file with mode: 0644]
node_modules/xterm/src/common/parser/Types.d.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/BufferService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/CoreMouseService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/CoreService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/DirtyRowService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/InstantiationService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/LogService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/OptionsService.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/ServiceRegistry.ts [new file with mode: 0644]
node_modules/xterm/src/common/services/Services.ts [new file with mode: 0644]
node_modules/xterm/src/common/tsconfig.json [new file with mode: 0644]
node_modules/xterm/src/public/AddonManager.ts [new file with mode: 0644]
node_modules/xterm/src/public/Terminal.ts [new file with mode: 0644]
node_modules/xterm/src/renderer/CursorRenderLayer.ts [new file with mode: 0644]
node_modules/xterm/src/renderer/Renderer.ts [new file with mode: 0644]
node_modules/xterm/src/renderer/dom/DomRenderer.ts [new file with mode: 0644]
node_modules/xterm/src/tsconfig-base.json [new file with mode: 0644]
node_modules/xterm/src/tsconfig-library-base.json [new file with mode: 0644]
node_modules/xterm/src/tsconfig.json [new file with mode: 0644]
node_modules/xterm/tsconfig.all.json [new file with mode: 0644]
node_modules/xterm/typings/xterm.d.ts [new file with mode: 0644]
src/index.js
src/views/starter.ejs [deleted file]

diff --git a/fifo b/fifo
new file mode 100644 (file)
index 0000000..e69de29
index 206bda1bcd5493bb1407943b193be1d852f11572..3d5e6c8a9cd147c897737e527f4d9fb5b40f89b8 100644 (file)
Binary files a/img/pc.svg and b/img/pc.svg differ
diff --git a/img/pcold.svg b/img/pcold.svg
deleted file mode 100644 (file)
index 3d5e6c8..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>\r
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\r
-<!-- Generated by Microsoft Visio, SVG Export pc.svg Page-1 -->\r
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events"\r
-               xmlns:v="http://schemas.microsoft.com/visio/2003/SVGExtensions/" width="6.0444in" height="6.0444in"\r
-               viewBox="0 0 435.197 435.197" xml:space="preserve" color-interpolation-filters="sRGB" class="st4">\r
-       <v:documentProperties v:langID="1033" v:viewMarkup="false"/>\r
-\r
-       <style type="text/css">\r
-       <![CDATA[\r
-               .st1 {fill:none;stroke:#246767;stroke-linecap:round;stroke-linejoin:round;stroke-width:10}\r
-               .st2 {stroke:#246767;stroke-linecap:round;stroke-linejoin:round;stroke-width:10}\r
-               .st3 {stroke:#246767;stroke-width:10}\r
-               .st4 {fill:none;fill-rule:evenodd;font-size:12px;overflow:visible;stroke-linecap:square;stroke-miterlimit:3}\r
-       ]]>\r
-       </style>\r
-\r
-       <g v:mID="0" v:index="1" v:groupContext="foregroundPage">\r
-               <title>Page-1</title>\r
-               <v:pageProperties v:drawingScale="0.0393701" v:pageScale="0.0393701" v:drawingUnits="24" v:shadowOffsetX="8.50394"\r
-                               v:shadowOffsetY="-8.50394"/>\r
-               <g id="shape3-1" v:mID="3" v:groupContext="shape" transform="translate(5,-5)">\r
-                       <title>Sheet.3</title>\r
-                       <rect x="0" y="350.157" width="425.197" height="85.0394" rx="22.6772" ry="22.6772" class="st1"/>\r
-               </g>\r
-               <g id="shape4-3" v:mID="4" v:groupContext="shape" transform="translate(5,-203.425)">\r
-                       <title>Sheet.4</title>\r
-                       <rect x="0" y="208.425" width="425.197" height="226.772" rx="22.6772" ry="22.6772" class="st1"/>\r
-               </g>\r
-               <g id="shape5-5" v:mID="5" v:groupContext="shape" transform="translate(189.252,-146.732)">\r
-                       <title>Sheet.5</title>\r
-                       <path d="M0 435.2 L56.69 435.2 L42.52 378.5 L14.17 378.5 L0 435.2 Z" class="st1"/>\r
-               </g>\r
-               <g id="shape6-7" v:mID="6" v:groupContext="shape" transform="translate(104.213,-146.732)">\r
-                       <title>Sheet.6</title>\r
-                       <path d="M0 435.2 L226.77 435.2" class="st2"/>\r
-               </g>\r
-               <g id="shape9-10" v:mID="9" v:groupContext="shape" transform="translate(33.3465,-61.6929)">\r
-                       <title>Sheet.9</title>\r
-                       <path d="M0 435.2 L226.77 435.2" class="st3"/>\r
-               </g>\r
-               <g id="shape11-13" v:mID="11" v:groupContext="shape" transform="translate(288.465,-61.6929)">\r
-                       <title>Sheet.11</title>\r
-                       <path d="M0 435.2 L113.39 435.2" class="st3"/>\r
-               </g>\r
-               <g id="shape12-16" v:mID="12" v:groupContext="shape" transform="translate(33.3465,-33.3465)">\r
-                       <title>Sheet.12</title>\r
-                       <path d="M0 435.2 L368.5 435.2" class="st3"/>\r
-               </g>\r
-               <g id="shape13-19" v:mID="13" v:groupContext="shape" transform="translate(104.213,-132.559)">\r
-                       <title>Sheet.13</title>\r
-                       <path d="M0 435.2 L226.77 435.2" class="st2"/>\r
-               </g>\r
-       </g>\r
-</svg>\r
diff --git a/img/switch.png b/img/switch.png
new file mode 100644 (file)
index 0000000..0b2b03a
Binary files /dev/null and b/img/switch.png differ
diff --git a/img/switch.svg b/img/switch.svg
deleted file mode 100644 (file)
index 77371f9..0000000
Binary files a/img/switch.svg and /dev/null differ
diff --git a/img/switch2.svg b/img/switch2.svg
deleted file mode 100755 (executable)
index 128a126..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="38pt" height="26pt" viewBox="0 0 38 26" version="1.1">
-<defs>
-<clipPath id="clip1">
-  <path d="M 0.0585938 0.820312 L 37 0.820312 L 37 25.820312 L 0.0585938 25.820312 L 0.0585938 0.820312 Z M 0.0585938 0.820312 "/>
-</clipPath>
-<clipPath id="clip2">
-  <path d="M 0.0585938 0.820312 L 37 0.820312 L 37 25.820312 L 0.0585938 25.820312 L 0.0585938 0.820312 Z M 0.0585938 0.820312 "/>
-</clipPath>
-</defs>
-<g id="surface0">
-<path style=" stroke:none;fill-rule:nonzero;fill:rgb(0.784314%,42.352941%,60.784314%);fill-opacity:1;" d="M 36.984375 8.171875 C 36.984375 12.121094 28.75 15.324219 18.59375 15.324219 C 8.433594 15.324219 0.199219 12.121094 0.199219 8.171875 L 0.199219 18.648438 C 0.199219 22.597656 8.433594 25.800781 18.59375 25.800781 C 28.75 25.800781 36.984375 22.597656 36.984375 18.648438 L 36.984375 8.171875 "/>
-<g clip-path="url(#clip1)" clip-rule="nonzero">
-<path style="fill:none;stroke-width:0.4;stroke-linecap:butt;stroke-linejoin:miter;stroke:rgb(100%,100%,100%);stroke-opacity:1;stroke-miterlimit:4;" d="M 36.984375 17.828125 C 36.984375 13.878906 28.75 10.675781 18.59375 10.675781 C 8.433594 10.675781 0.199219 13.878906 0.199219 17.828125 L 0.199219 7.351562 C 0.199219 3.402344 8.433594 0.199219 18.59375 0.199219 C 28.75 0.199219 36.984375 3.402344 36.984375 7.351562 L 36.984375 17.828125 Z M 36.984375 17.828125 " transform="matrix(1,0,0,-1,0,26)"/>
-</g>
-<path style=" stroke:none;fill-rule:nonzero;fill:rgb(0.784314%,42.352941%,60.784314%);fill-opacity:1;" d="M 18.59375 15.324219 C 28.75 15.324219 36.984375 12.121094 36.984375 8.171875 C 36.984375 4.222656 28.75 1.019531 18.59375 1.019531 C 8.433594 1.019531 0.199219 4.222656 0.199219 8.171875 C 0.199219 12.121094 8.433594 15.324219 18.59375 15.324219 "/>
-<g clip-path="url(#clip2)" clip-rule="nonzero">
-<path style="fill:none;stroke-width:0.4;stroke-linecap:butt;stroke-linejoin:miter;stroke:rgb(100%,100%,100%);stroke-opacity:1;stroke-miterlimit:4;" d="M 18.59375 10.675781 C 28.75 10.675781 36.984375 13.878906 36.984375 17.828125 C 36.984375 21.777344 28.75 24.980469 18.59375 24.980469 C 8.433594 24.980469 0.199219 21.777344 0.199219 17.828125 C 0.199219 13.878906 8.433594 10.675781 18.59375 10.675781 Z M 18.59375 10.675781 " transform="matrix(1,0,0,-1,0,26)"/>
-</g>
-<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 14.394531 5.375 L 15.910156 7.652344 L 10.167969 8.980469 L 11.425781 7.9375 L 2.550781 6.417969 L 4.773438 4.75 L 13.339844 6.199219 L 14.394531 5.375 "/>
-<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 22.472656 10.898438 L 21.4375 8.550781 L 26.617188 7.515625 L 25.71875 8.320312 L 34.351562 9.796875 L 32.277344 11.453125 L 23.699219 9.839844 L 22.472656 10.898438 "/>
-<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 19.640625 4.132812 L 25.441406 2.542969 L 25.511719 5.027344 L 24.058594 4.753906 L 21.230469 7.101562 L 18.527344 6.707031 L 21.449219 4.410156 L 19.640625 4.132812 "/>
-<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 17.152344 13.039062 L 11.628906 14.074219 L 11.421875 11.519531 L 13.011719 11.867188 L 16.050781 9.269531 L 18.742188 9.726562 L 15.496094 12.558594 L 17.152344 13.039062 "/>
-</g>
-</svg>
index 99830aa9cbc362971a0e90fcb8d77340a1b60771..cd350719536ebbf30561a4984b9a267caf0e40de 100644 (file)
@@ -96,7 +96,7 @@ $(function () {
 
 
     function startRefresh() {
-        setTimeout(startRefresh,10000);
+        setTimeout(startRefresh,30000);
         loadFlows();
     }
 
index 14bfb2e5fb985fb2730c8b25ffef5a2d51989426..0f6e1f1ba426019396ffcf5359281ef406f0cd9a 100644 (file)
@@ -139,7 +139,7 @@ $(function () {
         node.append("image")
             .attr("xlink:href", function (d) {
                 if (d.type === "switch") {
-                    return "img/switch.svg"
+                    return "img/switch.png"
                 } else if (d.type === "cloud") {
                     return "img/cloud.svg"
                 } else {
@@ -276,7 +276,7 @@ $(function () {
 
     function getTopology() {
         tabObj.buildTabs("#main", ["Graph", "Tables"], "Nothing to show!");
-        var $svg = $('<svg width="1616" height="900"></svg>');
+        var $svg = $('<svg width="800" height="600"></svg>');
         var $data = $('<div id="data"></div>');
         tabObj.buildContent('Graph', $svg);
         tabObj.buildContent('Tables', $data);
diff --git a/node_modules/node-pty/LICENSE b/node_modules/node-pty/LICENSE
new file mode 100644 (file)
index 0000000..22f780d
--- /dev/null
@@ -0,0 +1,69 @@
+Copyright (c) 2012-2015, Christopher Jeffrey (https://github.com/chjj/)
+
+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.
+
+
+
+The MIT License (MIT)
+
+Copyright (c) 2016, Daniel Imms (http://www.growingwiththeweb.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 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.
+
+
+
+MIT License
+
+Copyright (c) 2018 - present Microsoft Corporation
+
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/node_modules/node-pty/README.md b/node_modules/node-pty/README.md
new file mode 100644 (file)
index 0000000..a36bba3
--- /dev/null
@@ -0,0 +1,146 @@
+# node-pty
+
+[![Build Status](https://dev.azure.com/vscode/node-pty/_apis/build/status/Microsoft.node-pty)](https://dev.azure.com/vscode/node-pty/_build/latest?definitionId=11)
+
+`forkpty(3)` bindings for node.js. This allows you to fork processes with pseudoterminal file descriptors. It returns a terminal object which allows reads and writes.
+
+This is useful for:
+
+- Writing a terminal emulator (eg. via [xterm.js](https://github.com/sourcelair/xterm.js)).
+- Getting certain programs to *think* you're a terminal, such as when you need a program to send you control sequences.
+
+`node-pty` supports Linux, macOS and Windows. Windows support is possible by utilizing the [Windows conpty API](https://blogs.msdn.microsoft.com/commandline/2018/08/02/windows-command-line-introducing-the-windows-pseudo-console-conpty/) on Windows 1809+ and the [winpty](https://github.com/rprichard/winpty) library in older version.
+
+## Real-world Uses
+
+`node-pty` powers many different terminal emulators, including:
+
+- [Microsoft Visual Studio Code](https://code.visualstudio.com)
+- [Hyper](https://hyper.is/)
+- [Upterm](https://github.com/railsware/upterm)
+- [Script Runner](https://github.com/ioquatix/script-runner) for Atom.
+- [Theia](https://github.com/theia-ide/theia)
+- [FreeMAN](https://github.com/matthew-matvei/freeman) file manager
+- [atom-xterm](https://atom.io/packages/atom-xterm) - Atom plugin for providing terminals inside your Atom workspace.
+- [Termination](https://atom.io/packages/termination) - Another Atom plugin that provides terminals inside your Atom workspace.
+- [electerm](https://github.com/electerm/electerm) Terminal/ssh/sftp client(linux, mac, win).
+- [Extraterm](http://extraterm.org/)
+- [Wetty](https://github.com/krishnasrinivas/wetty) Browser based Terminal over HTTP and HTTPS
+
+Do you use node-pty in your application as well? Please open a [Pull Request](https://github.com/Tyriar/node-pty/pulls) to include it here. We would love to have it in our list.
+
+## Example Usage
+
+```js
+var os = require('os');
+var pty = require('node-pty');
+
+var shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
+
+var ptyProcess = pty.spawn(shell, [], {
+  name: 'xterm-color',
+  cols: 80,
+  rows: 30,
+  cwd: process.env.HOME,
+  env: process.env
+});
+
+ptyProcess.on('data', function(data) {
+  process.stdout.write(data);
+});
+
+ptyProcess.write('ls\r');
+ptyProcess.resize(100, 40);
+ptyProcess.write('ls\r');
+```
+
+## Building
+
+```bash
+# Install dependencies and build C++
+npm install
+# Compile TypeScript -> JavaScript
+npm run tsc
+```
+
+## Dependencies
+
+### Linux/Ubuntu
+
+```
+sudo apt install -y make python build-essential
+```
+
+The following are also needed:
+
+- Node.JS 10+
+
+### Windows
+
+`npm install` requires some tools to be present in the system like Python and C++ compiler. Windows users can easily install them by running the following command in PowerShell as administrator. For more information see https://github.com/felixrieseberg/windows-build-tools:
+
+```sh
+npm install --global --production windows-build-tools
+```
+
+The following are also needed:
+
+- [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk) - only the "Desktop C++ Apps" components are needed to be installed
+- Node.JS 10+
+
+## Debugging
+
+[The wiki](https://github.com/Microsoft/node-pty/wiki/Debugging) contains instructions for debugging node-pty.
+
+## Security
+
+All processes launched from node-pty will launch at the same permission level of the parent process. Take care particularly when using node-pty inside a server that's accessible on the internet. We recommend launching the pty inside a container to protect your host machine.
+
+## Thread Safety
+
+Note that node-pty is not thread safe so running it across multiple worker threads in node.js could cause issues.
+
+## Flow Control
+
+Automatic flow control can be enabled by either providing `handleFlowControl = true` in the constructor options or setting it later on:
+
+```js
+const PAUSE = '\x13';   // XOFF
+const RESUME = '\x11';  // XON
+
+const ptyProcess = pty.spawn(shell, [], {handleFlowControl: true});
+
+// flow control in action
+ptyProcess.write(PAUSE);  // pty will block and pause the slave program
+...
+ptyProcess.write(RESUME); // pty will enter flow mode and resume the slave program
+
+// temporarily disable/re-enable flow control
+ptyProcess.handleFlowControl = false;
+...
+ptyProcess.handleFlowControl = true;
+```
+
+By default `PAUSE` and `RESUME` are XON/XOFF control codes (as shown above). To avoid conflicts in environments that use these control codes for different purposes the messages can be customized as `flowControlPause: string` and `flowControlResume: string` in the constructor options. `PAUSE` and `RESUME` are not passed to the underlying pseudoterminal if flow control is enabled.
+
+## Troubleshooting
+
+### Powershell gives error 8009001d
+
+> Internal Windows PowerShell error.  Loading managed Windows PowerShell failed with error 8009001d.
+
+This happens when PowerShell is launched with no `SystemRoot` environment variable present.
+
+### ConnectNamedPipe failed: Windows error 232
+
+This error can occur due to anti-virus software intercepting winpty from creating a pty. To workaround this you can exclude this file from your anti-virus scanning `node-pty\build\Release\winpty-agent.exe`
+
+## pty.js
+
+This project is forked from [chjj/pty.js](https://github.com/chjj/pty.js) with the primary goals being to provide better support for later Node.JS versions and Windows.
+
+## License
+
+Copyright (c) 2012-2015, Christopher Jeffrey (MIT License).<br>
+Copyright (c) 2016, Daniel Imms (MIT License).<br>
+Copyright (c) 2018, Microsoft Corporation (MIT License).
diff --git a/node_modules/node-pty/binding.gyp b/node_modules/node-pty/binding.gyp
new file mode 100644 (file)
index 0000000..dac085f
--- /dev/null
@@ -0,0 +1,85 @@
+{
+  'conditions': [
+    ['OS=="win"', {
+      'targets': [
+        {
+          'target_name': 'conpty',
+          'include_dirs' : [
+            '<!(node -e "require(\'nan\')")'
+          ],
+          'sources' : [
+            'src/win/conpty.cc',
+            'src/win/path_util.cc'
+          ],
+          'libraries': [
+            'shlwapi.lib'
+          ]
+        },
+        {
+          'target_name': 'conpty_console_list',
+          'include_dirs' : [
+            '<!(node -e "require(\'nan\')")'
+          ],
+          'sources' : [
+            'src/win/conpty_console_list.cc'
+          ]
+        },
+        {
+          'target_name': 'pty',
+          'include_dirs' : [
+            '<!(node -e "require(\'nan\')")',
+            'deps/winpty/src/include',
+          ],
+          # Disabled due to winpty
+          'msvs_disabled_warnings': [ 4506, 4530 ],
+          'dependencies' : [
+            'deps/winpty/src/winpty.gyp:winpty-agent',
+            'deps/winpty/src/winpty.gyp:winpty',
+          ],
+          'sources' : [
+            'src/win/winpty.cc',
+            'src/win/path_util.cc'
+          ],
+          'libraries': [
+            'shlwapi.lib'
+          ],
+        }
+      ]
+    }, { # OS!="win"
+      'targets': [{
+        'target_name': 'pty',
+        'include_dirs' : [
+          '<!(node -e "require(\'nan\')")'
+        ],
+        'sources': [
+          'src/unix/pty.cc'
+        ],
+        'libraries': [
+          '-lutil'
+        ],
+        'conditions': [
+          # http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html
+          #   One some systems (at least including Cygwin, Interix,
+          #   OSF/1 4 and 5, and Mac OS X) linking with -lutil is not required.
+          ['OS=="mac" or OS=="solaris"', {
+            'libraries!': [
+              '-lutil'
+            ]
+          }],
+          ['OS=="mac"', {
+            "xcode_settings": {
+              "OTHER_CPLUSPLUSFLAGS": [
+                "-std=c++11",
+                "-stdlib=libc++"
+              ],
+              "OTHER_LDFLAGS": [
+                "-stdlib=libc++"
+              ],
+              "MACOSX_DEPLOYMENT_TARGET":"10.7"
+            }
+          }]
+        ]
+      }]
+    }]
+  ]
+}
diff --git a/node_modules/node-pty/build/Makefile b/node_modules/node-pty/build/Makefile
new file mode 100644 (file)
index 0000000..8bea253
--- /dev/null
@@ -0,0 +1,324 @@
+# We borrow heavily from the kernel build setup, though we are simpler since
+# we don't have Kconfig tweaking settings on us.
+
+# The implicit make rules have it looking for RCS files, among other things.
+# We instead explicitly write all the rules we care about.
+# It's even quicker (saves ~200ms) to pass -r on the command line.
+MAKEFLAGS=-r
+
+# The source directory tree.
+srcdir := ..
+abs_srcdir := $(abspath $(srcdir))
+
+# The name of the builddir.
+builddir_name ?= .
+
+# The V=1 flag on command line makes us verbosely print command lines.
+ifdef V
+  quiet=
+else
+  quiet=quiet_
+endif
+
+# Specify BUILDTYPE=Release on the command line for a release build.
+BUILDTYPE ?= Release
+
+# Directory all our build output goes into.
+# Note that this must be two directories beneath src/ for unit tests to pass,
+# as they reach into the src/ directory for data with relative paths.
+builddir ?= $(builddir_name)/$(BUILDTYPE)
+abs_builddir := $(abspath $(builddir))
+depsdir := $(builddir)/.deps
+
+# Object output directory.
+obj := $(builddir)/obj
+abs_obj := $(abspath $(obj))
+
+# We build up a list of every single one of the targets so we can slurp in the
+# generated dependency rule Makefiles in one pass.
+all_deps :=
+
+
+
+CC.target ?= $(CC)
+CFLAGS.target ?= $(CFLAGS)
+CXX.target ?= $(CXX)
+CXXFLAGS.target ?= $(CXXFLAGS) $(CPPFLAGS)
+LINK.target ?= $(LINK)
+LDFLAGS.target ?= $(LDFLAGS)
+AR.target ?= $(AR)
+
+# C++ apps need to be linked with g++.
+LINK ?= $(CXX.target)
+
+# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
+# to replicate this environment fallback in make as well.
+CC.host ?= gcc
+CFLAGS.host ?=
+CXX.host ?= g++
+CXXFLAGS.host ?=
+LINK.host ?= $(CXX.host)
+LDFLAGS.host ?=
+AR.host ?= ar
+
+# Define a dir function that can handle spaces.
+# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
+# "leading spaces cannot appear in the text of the first argument as written.
+# These characters can be put into the argument value by variable substitution."
+empty :=
+space := $(empty) $(empty)
+
+# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
+replace_spaces = $(subst $(space),?,$1)
+unreplace_spaces = $(subst ?,$(space),$1)
+dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
+
+# Flags to make gcc output dependency info.  Note that you need to be
+# careful here to use the flags that ccache and distcc can understand.
+# We write to a dep file on the side first and then rename at the end
+# so we can't end up with a broken dep file.
+depfile = $(depsdir)/$(call replace_spaces,$@).d
+DEPFLAGS = -MMD -MF $(depfile).raw
+
+# We have to fixup the deps output in a few ways.
+# (1) the file output should mention the proper .o file.
+# ccache or distcc lose the path to the target, so we convert a rule of
+# the form:
+#   foobar.o: DEP1 DEP2
+# into
+#   path/to/foobar.o: DEP1 DEP2
+# (2) we want missing files not to cause us to fail to build.
+# We want to rewrite
+#   foobar.o: DEP1 DEP2 \
+#               DEP3
+# to
+#   DEP1:
+#   DEP2:
+#   DEP3:
+# so if the files are missing, they're just considered phony rules.
+# We have to do some pretty insane escaping to get those backslashes
+# and dollar signs past make, the shell, and sed at the same time.
+# Doesn't work with spaces, but that's fine: .d files have spaces in
+# their names replaced with other characters.
+define fixup_dep
+# The depfile may not exist if the input file didn't have any #includes.
+touch $(depfile).raw
+# Fixup path as in (1).
+sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
+# Add extra rules as in (2).
+# We remove slashes and replace spaces with new lines;
+# remove blank lines;
+# delete the first line and append a colon to the remaining lines.
+sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
+  grep -v '^$$'                             |\
+  sed -e 1d -e 's|$$|:|'                     \
+    >> $(depfile)
+rm $(depfile).raw
+endef
+
+# Command definitions:
+# - cmd_foo is the actual command to run;
+# - quiet_cmd_foo is the brief-output summary of the command.
+
+quiet_cmd_cc = CC($(TOOLSET)) $@
+cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
+
+quiet_cmd_cxx = CXX($(TOOLSET)) $@
+cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
+
+quiet_cmd_touch = TOUCH $@
+cmd_touch = touch $@
+
+quiet_cmd_copy = COPY $@
+# send stderr to /dev/null to ignore messages when linking directories.
+cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
+
+quiet_cmd_alink = AR($(TOOLSET)) $@
+cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
+
+quiet_cmd_alink_thin = AR($(TOOLSET)) $@
+cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
+
+# Due to circular dependencies between libraries :(, we wrap the
+# special "figure out circular dependencies" flags around the entire
+# input list during linking.
+quiet_cmd_link = LINK($(TOOLSET)) $@
+cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
+
+# We support two kinds of shared objects (.so):
+# 1) shared_library, which is just bundling together many dependent libraries
+# into a link line.
+# 2) loadable_module, which is generating a module intended for dlopen().
+#
+# They differ only slightly:
+# In the former case, we want to package all dependent code into the .so.
+# In the latter case, we want to package just the API exposed by the
+# outermost module.
+# This means shared_library uses --whole-archive, while loadable_module doesn't.
+# (Note that --whole-archive is incompatible with the --start-group used in
+# normal linking.)
+
+# Other shared-object link notes:
+# - Set SONAME to the library filename so our binaries don't reference
+# the local, absolute paths used on the link command-line.
+quiet_cmd_solink = SOLINK($(TOOLSET)) $@
+cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
+
+quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
+cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
+
+
+# Define an escape_quotes function to escape single quotes.
+# This allows us to handle quotes properly as long as we always use
+# use single quotes and escape_quotes.
+escape_quotes = $(subst ','\'',$(1))
+# This comment is here just to include a ' to unconfuse syntax highlighting.
+# Define an escape_vars function to escape '$' variable syntax.
+# This allows us to read/write command lines with shell variables (e.g.
+# $LD_LIBRARY_PATH), without triggering make substitution.
+escape_vars = $(subst $$,$$$$,$(1))
+# Helper that expands to a shell command to echo a string exactly as it is in
+# make. This uses printf instead of echo because printf's behaviour with respect
+# to escape sequences is more portable than echo's across different shells
+# (e.g., dash, bash).
+exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
+
+# Helper to compare the command we're about to run against the command
+# we logged the last time we ran the command.  Produces an empty
+# string (false) when the commands match.
+# Tricky point: Make has no string-equality test function.
+# The kernel uses the following, but it seems like it would have false
+# positives, where one string reordered its arguments.
+#   arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
+#                       $(filter-out $(cmd_$@), $(cmd_$(1))))
+# We instead substitute each for the empty string into the other, and
+# say they're equal if both substitutions produce the empty string.
+# .d files contain ? instead of spaces, take that into account.
+command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
+                       $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
+
+# Helper that is non-empty when a prerequisite changes.
+# Normally make does this implicitly, but we force rules to always run
+# so we can check their command lines.
+#   $? -- new prerequisites
+#   $| -- order-only dependencies
+prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
+
+# Helper that executes all postbuilds until one fails.
+define do_postbuilds
+  @E=0;\
+  for p in $(POSTBUILDS); do\
+    eval $$p;\
+    E=$$?;\
+    if [ $$E -ne 0 ]; then\
+      break;\
+    fi;\
+  done;\
+  if [ $$E -ne 0 ]; then\
+    rm -rf "$@";\
+    exit $$E;\
+  fi
+endef
+
+# do_cmd: run a command via the above cmd_foo names, if necessary.
+# Should always run for a given target to handle command-line changes.
+# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
+# Third argument, if non-zero, makes it do POSTBUILDS processing.
+# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
+# spaces already and dirx strips the ? characters.
+define do_cmd
+$(if $(or $(command_changed),$(prereq_changed)),
+  @$(call exact_echo,  $($(quiet)cmd_$(1)))
+  @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
+  $(if $(findstring flock,$(word 1,$(cmd_$1))),
+    @$(cmd_$(1))
+    @echo "  $(quiet_cmd_$(1)): Finished",
+    @$(cmd_$(1))
+  )
+  @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
+  @$(if $(2),$(fixup_dep))
+  $(if $(and $(3), $(POSTBUILDS)),
+    $(call do_postbuilds)
+  )
+)
+endef
+
+# Declare the "all" target first so it is the default,
+# even though we don't have the deps yet.
+.PHONY: all
+all:
+
+# make looks for ways to re-generate included makefiles, but in our case, we
+# don't have a direct way. Explicitly telling make that it has nothing to do
+# for them makes it go faster.
+%.d: ;
+
+# Use FORCE_DO_CMD to force a target to run.  Should be coupled with
+# do_cmd.
+.PHONY: FORCE_DO_CMD
+FORCE_DO_CMD:
+
+TOOLSET := target
+# Suffix rules, putting all outputs into $(obj).
+$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+
+# Try building from generated source, too.
+$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+
+$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
+       @$(call do_cmd,cc,1)
+
+
+ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
+    $(findstring $(join ^,$(prefix)),\
+                 $(join ^,pty.target.mk)))),)
+  include pty.target.mk
+endif
+
+quiet_cmd_regen_makefile = ACTION Regenerating $@
+cmd_regen_makefile = cd $(srcdir); /usr/share/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/pi/VSoRC/node_modules/node-pty/build/config.gypi -I/usr/share/node-gyp/addon.gypi -I/usr/include/nodejs/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/usr/include/nodejs" "-Dnode_gyp_dir=/usr/share/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/home/pi/VSoRC/node_modules/node-pty" binding.gyp
+Makefile: $(srcdir)/../../../../../usr/include/nodejs/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../usr/share/node-gyp/addon.gypi
+       $(call do_cmd,regen_makefile)
+
+# "all" is a concatenation of the "all" targets from all the included
+# sub-makefiles. This is just here to clarify.
+all:
+
+# Add in dependency-tracking rules.  $(all_deps) is the list of every single
+# target in our tree. Only consider the ones with .d (dependency) info:
+d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
+ifneq ($(d_files),)
+  include $(d_files)
+endif
diff --git a/node_modules/node-pty/build/Release/pty.node b/node_modules/node-pty/build/Release/pty.node
new file mode 100755 (executable)
index 0000000..9dd15cf
Binary files /dev/null and b/node_modules/node-pty/build/Release/pty.node differ
diff --git a/node_modules/node-pty/build/binding.Makefile b/node_modules/node-pty/build/binding.Makefile
new file mode 100644 (file)
index 0000000..059b76f
--- /dev/null
@@ -0,0 +1,6 @@
+# This file is generated by gyp; do not edit.
+
+export builddir_name ?= ./build/.
+.PHONY: all
+all:
+       $(MAKE) pty
diff --git a/node_modules/node-pty/build/config.gypi b/node_modules/node-pty/build/config.gypi
new file mode 100644 (file)
index 0000000..cf372b9
--- /dev/null
@@ -0,0 +1,151 @@
+# Do not edit. File was generated by node-gyp's "configure" step
+{
+  "target_defaults": {
+    "cflags": [],
+    "default_configuration": "Release",
+    "defines": [],
+    "include_dirs": [],
+    "libraries": []
+  },
+  "variables": {
+    "arm_float_abi": "hard",
+    "arm_fpu": "vfp",
+    "arm_thumb": 0,
+    "arm_version": "6",
+    "asan": 0,
+    "coverage": "false",
+    "debug_devtools": "node",
+    "debug_http2": "false",
+    "debug_nghttp2": "false",
+    "force_dynamic_crt": 0,
+    "host_arch": "arm",
+    "icu_gyp_path": "tools/icu/icu-system.gyp",
+    "icu_small": "false",
+    "llvm_version": 0,
+    "node_byteorder": "little",
+    "node_enable_d8": "false",
+    "node_enable_v8_vtunejit": "false",
+    "node_install_npm": "false",
+    "node_module_version": 57,
+    "node_no_browser_globals": "false",
+    "node_prefix": "/usr",
+    "node_release_urlbase": "",
+    "node_shared": "false",
+    "node_shared_cares": "true",
+    "node_shared_http_parser": "true",
+    "node_shared_libuv": "true",
+    "node_shared_nghttp2": "false",
+    "node_shared_openssl": "true",
+    "node_shared_zlib": "true",
+    "node_tag": "",
+    "node_use_bundled_v8": "true",
+    "node_use_dtrace": "false",
+    "node_use_etw": "false",
+    "node_use_lttng": "false",
+    "node_use_openssl": "true",
+    "node_use_perfctr": "false",
+    "node_use_v8_platform": "true",
+    "node_without_node_options": "false",
+    "openssl_fips": "",
+    "openssl_no_asm": 0,
+    "shlib_suffix": "so.57",
+    "target_arch": "arm",
+    "uv_parent_path": "/deps/uv/",
+    "uv_use_dtrace": "false",
+    "v8_enable_gdbjit": 0,
+    "v8_enable_i18n_support": 1,
+    "v8_enable_inspector": 1,
+    "v8_no_strict_aliasing": 1,
+    "v8_optimized_debug": 0,
+    "v8_promise_internal_field_count": 1,
+    "v8_random_seed": 0,
+    "v8_trace_maps": 0,
+    "v8_use_snapshot": "false",
+    "want_separate_host_toolset": 0,
+    "nodedir": "/usr/include/nodejs",
+    "copy_dev_lib": "true",
+    "standalone_static_library": 1,
+    "cache_lock_stale": "60000",
+    "sign_git_tag": "",
+    "user_agent": "npm/1.4.21 node/v8.11.1 linux arm",
+    "always_auth": "",
+    "bin_links": "true",
+    "key": "",
+    "description": "true",
+    "fetch_retries": "2",
+    "heading": "npm",
+    "user": "",
+    "force": "",
+    "cache_min": "10",
+    "init_license": "ISC",
+    "editor": "vi",
+    "rollback": "true",
+    "cache_max": "Infinity",
+    "userconfig": "/home/pi/.npmrc",
+    "engine_strict": "",
+    "init_author_name": "",
+    "init_author_url": "",
+    "tmp": "/tmp",
+    "depth": "Infinity",
+    "save_dev": "",
+    "usage": "",
+    "https_proxy": "",
+    "onload_script": "",
+    "rebuild_bundle": "true",
+    "save_bundle": "",
+    "shell": "/bin/bash",
+    "prefix": "/usr/local",
+    "registry": "https://registry.npmjs.org/",
+    "__DO_NOT_MODIFY_THIS_FILE___use__etc_npmrc_instead_": "true",
+    "browser": "",
+    "cache_lock_wait": "10000",
+    "save_optional": "",
+    "searchopts": "",
+    "versions": "",
+    "cache": "/home/pi/.npm",
+    "ignore_scripts": "",
+    "searchsort": "name",
+    "version": "",
+    "local_address": "",
+    "viewer": "man",
+    "color": "true",
+    "fetch_retry_mintimeout": "10000",
+    "umask": "18",
+    "fetch_retry_maxtimeout": "60000",
+    "message": "%s",
+    "ca": "",
+    "cert": "",
+    "global": "",
+    "link": "",
+    "save": "",
+    "unicode": "true",
+    "long": "",
+    "production": "",
+    "unsafe_perm": "true",
+    "node_version": "8.11.1",
+    "tag": "latest",
+    "git_tag_version": "true",
+    "shrinkwrap": "true",
+    "fetch_retry_factor": "10",
+    "npat": "",
+    "proprietary_attribs": "true",
+    "save_exact": "",
+    "strict_ssl": "true",
+    "username": "",
+    "globalconfig": "/etc/npmrc",
+    "dev": "",
+    "init_module": "/home/pi/.npm-init.js",
+    "parseable": "",
+    "globalignorefile": "/etc/npmignore",
+    "cache_lock_retries": "10",
+    "save_prefix": "^",
+    "group": "1000",
+    "init_author_email": "",
+    "searchexclude": "",
+    "git": "git",
+    "optional": "true",
+    "email": "",
+    "json": "",
+    "spin": "true"
+  }
+}
diff --git a/node_modules/node-pty/build/pty.target.mk b/node_modules/node-pty/build/pty.target.mk
new file mode 100644 (file)
index 0000000..528472f
--- /dev/null
@@ -0,0 +1,140 @@
+# This file is generated by gyp; do not edit.
+
+TOOLSET := target
+TARGET := pty
+DEFS_Debug := \
+       '-DNODE_GYP_MODULE_NAME=pty' \
+       '-DUSING_UV_SHARED=1' \
+       '-DUSING_V8_SHARED=1' \
+       '-DV8_DEPRECATION_WARNINGS=1' \
+       '-D_LARGEFILE_SOURCE' \
+       '-D_FILE_OFFSET_BITS=64' \
+       '-DBUILDING_NODE_EXTENSION' \
+       '-DDEBUG' \
+       '-D_DEBUG' \
+       '-DV8_ENABLE_CHECKS'
+
+# Flags passed to all source files.
+CFLAGS_Debug := \
+       -fPIC \
+       -pthread \
+       -Wall \
+       -Wextra \
+       -Wno-unused-parameter \
+       -g \
+       -O0
+
+# Flags passed to only C files.
+CFLAGS_C_Debug :=
+
+# Flags passed to only C++ files.
+CFLAGS_CC_Debug := \
+       -fno-rtti \
+       -fno-exceptions \
+       -std=gnu++0x
+
+INCS_Debug := \
+       -I/usr/include/nodejs/include/node \
+       -I/usr/include/nodejs/src \
+       -I/usr/include/nodejs/deps/uv/include \
+       -I/usr/include/nodejs/deps/v8/include \
+       -I$(srcdir)/node_modules/nan
+
+DEFS_Release := \
+       '-DNODE_GYP_MODULE_NAME=pty' \
+       '-DUSING_UV_SHARED=1' \
+       '-DUSING_V8_SHARED=1' \
+       '-DV8_DEPRECATION_WARNINGS=1' \
+       '-D_LARGEFILE_SOURCE' \
+       '-D_FILE_OFFSET_BITS=64' \
+       '-DBUILDING_NODE_EXTENSION'
+
+# Flags passed to all source files.
+CFLAGS_Release := \
+       -fPIC \
+       -pthread \
+       -Wall \
+       -Wextra \
+       -Wno-unused-parameter \
+       -O3 \
+       -fno-omit-frame-pointer
+
+# Flags passed to only C files.
+CFLAGS_C_Release :=
+
+# Flags passed to only C++ files.
+CFLAGS_CC_Release := \
+       -fno-rtti \
+       -fno-exceptions \
+       -std=gnu++0x
+
+INCS_Release := \
+       -I/usr/include/nodejs/include/node \
+       -I/usr/include/nodejs/src \
+       -I/usr/include/nodejs/deps/uv/include \
+       -I/usr/include/nodejs/deps/v8/include \
+       -I$(srcdir)/node_modules/nan
+
+OBJS := \
+       $(obj).target/$(TARGET)/src/unix/pty.o
+
+# Add to the list of files we specially track dependencies for.
+all_deps += $(OBJS)
+
+# CFLAGS et al overrides must be target-local.
+# See "Target-specific Variable Values" in the GNU Make manual.
+$(OBJS): TOOLSET := $(TOOLSET)
+$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE))  $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
+$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE))  $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
+
+# Suffix rules, putting all outputs into $(obj).
+
+$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+
+# Try building from generated source, too.
+
+$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+
+$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
+       @$(call do_cmd,cxx,1)
+
+# End of this set of suffix rules
+### Rules for final target.
+LDFLAGS_Debug := \
+       -pthread \
+       -rdynamic
+
+LDFLAGS_Release := \
+       -pthread \
+       -rdynamic
+
+LIBS := \
+       -lutil
+
+$(obj).target/pty.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
+$(obj).target/pty.node: LIBS := $(LIBS)
+$(obj).target/pty.node: TOOLSET := $(TOOLSET)
+$(obj).target/pty.node: $(OBJS) FORCE_DO_CMD
+       $(call do_cmd,solink_module)
+
+all_deps += $(obj).target/pty.node
+# Add target alias
+.PHONY: pty
+pty: $(builddir)/pty.node
+
+# Copy this to the executable output path.
+$(builddir)/pty.node: TOOLSET := $(TOOLSET)
+$(builddir)/pty.node: $(obj).target/pty.node FORCE_DO_CMD
+       $(call do_cmd,copy)
+
+all_deps += $(builddir)/pty.node
+# Short alias for building this executable.
+.PHONY: pty.node
+pty.node: $(obj).target/pty.node $(builddir)/pty.node
+
+# Add executable to "all" target.
+.PHONY: all
+all: $(builddir)/pty.node
+
diff --git a/node_modules/node-pty/deps/.editorconfig b/node_modules/node-pty/deps/.editorconfig
new file mode 100644 (file)
index 0000000..8a39199
--- /dev/null
@@ -0,0 +1,2 @@
+# Have editor config ignore this directory
+root = true
diff --git a/node_modules/node-pty/deps/winpty/.drone.yml b/node_modules/node-pty/deps/winpty/.drone.yml
new file mode 100644 (file)
index 0000000..63d853f
--- /dev/null
@@ -0,0 +1,17 @@
+# Build configure for https://www.tea-ci.org (fork of Drone CI with Msys2 support)
+build:
+  image: teaci/msys$$arch
+  pull: true
+  shell: msys$$arch
+  commands:
+    - pacman -S --needed --noconfirm --noprogressbar mingw-w64-cross-gcc mingw-w64-cross-crt-git
+    - ./configure
+    - make
+    - make tests
+    - build/trivial_test.exe
+    - mintty --log - --exec build/winpty.exe cmd /c ver | grep Windows
+
+matrix:
+  arch:
+    - 64
+    - 32
diff --git a/node_modules/node-pty/deps/winpty/.gitattributes b/node_modules/node-pty/deps/winpty/.gitattributes
new file mode 100644 (file)
index 0000000..36d4c60
--- /dev/null
@@ -0,0 +1,19 @@
+*               text=auto
+*.bat           text eol=crlf
+*.c             text
+*.cc            text
+*.gyp           text
+*.gypi          text
+*.h             text
+*.ps1           text eol=crlf
+*.rst           text
+*.sh            text
+*.txt           text
+.gitignore      text
+.gitattributes  text
+Makefile        text
+configure       text
+
+*.sh            eol=lf
+configure       eol=lf
+VERSION.txt     eol=lf
diff --git a/node_modules/node-pty/deps/winpty/.gitignore b/node_modules/node-pty/deps/winpty/.gitignore
new file mode 100644 (file)
index 0000000..89e60bd
--- /dev/null
@@ -0,0 +1,15 @@
+*.sln
+*.suo
+*.vcxproj
+*.vcxproj.filters
+*.pyc
+winpty.sdf
+winpty.opensdf
+/config.mk
+/build
+/build-gyp
+/build-libpty
+/ship/packages
+/src/Default
+/src/Release
+/src/gen
diff --git a/node_modules/node-pty/deps/winpty/LICENSE b/node_modules/node-pty/deps/winpty/LICENSE
new file mode 100644 (file)
index 0000000..246fbe0
--- /dev/null
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2011-2016 Ryan Prichard
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
diff --git a/node_modules/node-pty/deps/winpty/Makefile b/node_modules/node-pty/deps/winpty/Makefile
new file mode 100644 (file)
index 0000000..8b3d0ae
--- /dev/null
@@ -0,0 +1,166 @@
+# Copyright (c) 2011-2015 Ryan Prichard
+#
+# 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.
+
+# Use make -n to see the actual command-lines make would run.
+
+# The default "make install" prefix is /usr/local.  Pass PREFIX=<path> on the
+# command-line to override the default.
+
+.SECONDEXPANSION :
+
+.PHONY : default
+default : all
+
+PREFIX := /usr/local
+UNIX_ADAPTER_EXE := winpty.exe
+MINGW_ENABLE_CXX11_FLAG := -std=c++11
+USE_PCH := 1
+
+COMMON_CXXFLAGS :=
+UNIX_CXXFLAGS :=
+MINGW_CXXFLAGS :=
+MINGW_LDFLAGS :=
+UNIX_LDFLAGS :=
+
+# Include config.mk but complain if it hasn't been created yet.
+ifeq "$(wildcard config.mk)" ""
+    $(error config.mk does not exist.  Please run ./configure)
+endif
+include config.mk
+
+COMMON_CXXFLAGS += \
+       -MMD -Wall \
+       -DUNICODE \
+       -D_UNICODE \
+       -D_WIN32_WINNT=0x0501 \
+       -Ibuild/gen
+
+UNIX_CXXFLAGS += \
+       $(COMMON_CXXFLAGS)
+
+MINGW_CXXFLAGS += \
+       $(COMMON_CXXFLAGS) \
+       -O2 \
+       $(MINGW_ENABLE_CXX11_FLAG)
+
+MINGW_LDFLAGS += -static -static-libgcc -static-libstdc++
+UNIX_LDFLAGS += $(UNIX_LDFLAGS_STATIC)
+
+ifeq "$(USE_PCH)" "1"
+MINGW_CXXFLAGS += -include build/mingw/PrecompiledHeader.h
+PCH_DEP := build/mingw/PrecompiledHeader.h.gch
+else
+PCH_DEP :=
+endif
+
+build/gen/GenVersion.h : VERSION.txt $(COMMIT_HASH_DEP) | $$(@D)/.mkdir
+       $(info Updating build/gen/GenVersion.h)
+       @echo "const char GenVersion_Version[] = \"$(shell cat VERSION.txt | tr -d '\r\n')\";" > build/gen/GenVersion.h
+       @echo "const char GenVersion_Commit[] = \"$(COMMIT_HASH)\";" >> build/gen/GenVersion.h
+
+build/mingw/PrecompiledHeader.h : src/shared/PrecompiledHeader.h | $$(@D)/.mkdir
+       $(info Copying $< to $@)
+       @cp $< $@
+
+build/mingw/PrecompiledHeader.h.gch : build/mingw/PrecompiledHeader.h | $$(@D)/.mkdir
+       $(info Compiling $<)
+       @$(MINGW_CXX) $(MINGW_CXXFLAGS) -c -o $@ $<
+
+-include build/mingw/PrecompiledHeader.h.d
+
+define def_unix_target
+build/$1/%.o : src/%.cc | $$$$(@D)/.mkdir
+       $$(info Compiling $$<)
+       @$$(UNIX_CXX) $$(UNIX_CXXFLAGS) $2 -I src/include -c -o $$@ $$<
+endef
+
+define def_mingw_target
+build/$1/%.o : src/%.cc $$(PCH_DEP) | $$$$(@D)/.mkdir
+       $$(info Compiling $$<)
+       @$$(MINGW_CXX) $$(MINGW_CXXFLAGS) $2 -I src/include -c -o $$@ $$<
+endef
+
+include src/subdir.mk
+
+.PHONY : all
+all : $(ALL_TARGETS)
+
+.PHONY : tests
+tests : $(TEST_PROGRAMS)
+
+.PHONY : install-bin
+install-bin : all
+       mkdir -p $(PREFIX)/bin
+       install -m 755 -p -s build/$(UNIX_ADAPTER_EXE) $(PREFIX)/bin
+       install -m 755 -p -s build/winpty.dll $(PREFIX)/bin
+       install -m 755 -p -s build/winpty-agent.exe $(PREFIX)/bin
+
+.PHONY : install-debugserver
+install-debugserver : all
+       mkdir -p $(PREFIX)/bin
+       install -m 755 -p -s build/winpty-debugserver.exe $(PREFIX)/bin
+
+.PHONY : install-lib
+install-lib : all
+       mkdir -p $(PREFIX)/lib
+       install -m 644 -p build/winpty.lib $(PREFIX)/lib
+
+.PHONY : install-doc
+install-doc :
+       mkdir -p $(PREFIX)/share/doc/winpty
+       install -m 644 -p LICENSE $(PREFIX)/share/doc/winpty
+       install -m 644 -p README.md $(PREFIX)/share/doc/winpty
+       install -m 644 -p RELEASES.md $(PREFIX)/share/doc/winpty
+
+.PHONY : install-include
+install-include :
+       mkdir -p $(PREFIX)/include/winpty
+       install -m 644 -p src/include/winpty.h $(PREFIX)/include/winpty
+       install -m 644 -p src/include/winpty_constants.h $(PREFIX)/include/winpty
+
+.PHONY : install
+install : \
+       install-bin \
+       install-debugserver \
+       install-lib \
+       install-doc \
+       install-include
+
+.PHONY : clean
+clean :
+       rm -fr build
+
+.PHONY : clean-msvc
+clean-msvc :
+       rm -fr src/Default src/Release src/.vs src/gen
+       rm -f src/*.vcxproj src/*.vcxproj.filters src/*.sln src/*.sdf
+
+.PHONY : distclean
+distclean : clean
+       rm -f config.mk
+
+.PRECIOUS : %.mkdir
+%.mkdir :
+       $(info Creating directory $(dir $@))
+       @mkdir -p $(dir $@)
+       @touch $@
+
+src/%.h :
+       @echo "Missing header file $@ (stale dependency file?)"
diff --git a/node_modules/node-pty/deps/winpty/README.md b/node_modules/node-pty/deps/winpty/README.md
new file mode 100644 (file)
index 0000000..a6520fc
--- /dev/null
@@ -0,0 +1,151 @@
+# winpty
+
+[![Build Status](https://tea-ci.org/api/badges/rprichard/winpty/status.svg)](https://tea-ci.org/rprichard/winpty)
+
+winpty is a Windows software package providing an interface similar to a Unix
+pty-master for communicating with Windows console programs.  The package
+consists of a library (libwinpty) and a tool for Cygwin and MSYS for running
+Windows console programs in a Cygwin/MSYS pty.
+
+The software works by starting the `winpty-agent.exe` process with a new,
+hidden console window, which bridges between the console API and terminal
+input/output escape codes.  It polls the hidden console's screen buffer for
+changes and generates a corresponding stream of output.
+
+The Unix adapter allows running Windows console programs (e.g. CMD, PowerShell,
+IronPython, etc.) under `mintty` or Cygwin's `sshd` with
+properly-functioning input (e.g. arrow and function keys) and output (e.g. line
+buffering).  The library could be also useful for writing a non-Cygwin SSH
+server.
+
+## Supported Windows versions
+
+winpty runs on Windows XP through Windows 10, including server versions.  It
+can be compiled into either 32-bit or 64-bit binaries.
+
+## Cygwin/MSYS adapter (`winpty.exe`)
+
+### Prerequisites
+
+You need the following to build winpty:
+
+* A Cygwin or MSYS installation
+* GNU make
+* A MinGW g++ toolchain capable of compiling C++11 code to build `winpty.dll`
+  and `winpty-agent.exe`
+* A g++ toolchain targeting Cygwin or MSYS to build `winpty.exe`
+
+Winpty requires two g++ toolchains as it is split into two parts. The
+`winpty.dll` and `winpty-agent.exe` binaries interface with the native
+Windows command prompt window so they are compiled with the native MinGW
+toolchain.  The `winpty.exe` binary interfaces with the MSYS/Cygwin terminal so
+it is compiled with the MSYS/Cygwin toolchain.
+
+MinGW appears to be split into two distributions -- MinGW (creates 32-bit
+binaries) and MinGW-w64 (creates both 32-bit and 64-bit binaries).  Either
+one is generally acceptable.
+
+#### Cygwin packages
+
+The default g++ compiler for Cygwin targets Cygwin itself, but Cygwin also
+packages MinGW-w64 compilers.  As of this writing, the necessary packages are:
+
+* Either `mingw64-i686-gcc-g++` or `mingw64-x86_64-gcc-g++`.  Select the
+  appropriate compiler for your CPU architecture.
+* `gcc-g++`
+* `make`
+
+As of this writing (2016-01-23), only the MinGW-w64 compiler is acceptable.
+The MinGW compiler (e.g. from the `mingw-gcc-g++` package) is no longer
+maintained and is too buggy.
+
+#### MSYS packages
+
+For the original MSYS, use the `mingw-get` tool (MinGW Installation Manager),
+and select at least these components:
+
+* `mingw-developer-toolkit`
+* `mingw32-base`
+* `mingw32-gcc-g++`
+* `msys-base`
+* `msys-system-builder`
+
+When running `./configure`, make sure that `mingw32-g++` is in your
+`PATH`.  It will be in the `C:\MinGW\bin` directory.
+
+#### MSYS2 packages
+
+For MSYS2, use `pacman` and install at least these packages:
+
+* `msys/gcc`
+* `mingw32/mingw-w64-i686-gcc` or `mingw64/mingw-w64-x86_64-gcc`.  Select
+  the appropriate compiler for your CPU architecture.
+* `make`
+
+MSYS2 provides three start menu shortcuts for starting MSYS2:
+
+* MinGW-w64 Win32 Shell
+* MinGW-w64 Win64 Shell
+* MSYS2 Shell
+
+To build winpty, use the MinGW-w64 {Win32,Win64} shortcut of the architecture
+matching MSYS2.  These shortcuts will put the g++ compiler from the
+`{mingw32,mingw64}/mingw-w64-{i686,x86_64}-gcc` packages into the `PATH`.
+
+Alternatively, instead of installing `mingw32/mingw-w64-i686-gcc` or
+`mingw64/mingw-w64-x86_64-gcc`, install the `mingw-w64-cross-gcc` and
+`mingw-w64-cross-crt-git` packages.  These packages install cross-compilers
+into `/opt/bin`, and then any of the three shortcuts will work.
+
+### Building the Unix adapter
+
+In the project directory, run `./configure`, then `make`, then `make install`.
+By default, winpty is installed into `/usr/local`.  Pass `PREFIX=<path>` to
+`make install` to override this default.
+
+### Using the Unix adapter
+
+To run a Windows console program in `mintty` or Cygwin `sshd`, prepend
+`winpty` to the command-line:
+
+    $ winpty powershell
+    Windows PowerShell
+    Copyright (C) 2009 Microsoft Corporation. All rights reserved.
+
+    PS C:\rprichard\proj\winpty> 10 + 20
+    30
+    PS C:\rprichard\proj\winpty> exit
+
+## Embedding winpty / MSVC compilation
+
+See `src/include/winpty.h` for the prototypes of functions exported by
+`winpty.dll`.
+
+Only the `winpty.exe` binary uses Cygwin; all the other binaries work without
+it and can be compiled with either MinGW or MSVC.  To compile using MSVC,
+download gyp and run `gyp -I configurations.gypi` in the `src` subdirectory.
+This will generate a `winpty.sln` and associated project files.  See the
+`src/winpty.gyp` and `src/configurations.gypi` files for notes on dealing with
+MSVC versions and different architectures.
+
+Compiling winpty with MSVC currently requires MSVC 2013 or newer.
+
+## Debugging winpty
+
+winpty comes with a tool for collecting timestamped debugging output.  To use
+it:
+
+1. Run `winpty-debugserver.exe` on the same computer as winpty.
+2. Set the `WINPTY_DEBUG` environment variable to `trace` for the
+   `winpty.exe` process and/or the process using `libwinpty.dll`.
+
+winpty also recognizes a `WINPTY_SHOW_CONSOLE` environment variable.  Set it
+to 1 to prevent winpty from hiding the console window.
+
+## Copyright
+
+This project is distributed under the MIT license (see the `LICENSE` file in
+the project root).
+
+By submitting a pull request for this project, you agree to license your
+contribution under the MIT license to this project.
diff --git a/node_modules/node-pty/deps/winpty/RELEASES.md b/node_modules/node-pty/deps/winpty/RELEASES.md
new file mode 100644 (file)
index 0000000..768cdf9
--- /dev/null
@@ -0,0 +1,280 @@
+# Next Version
+
+Input handling changes:
+
+ * Improve Ctrl-C handling with programs that use unprocessed input. (e.g.
+   Ctrl-C now cancels input with PowerShell on Windows 10.)
+   [#116](https://github.com/rprichard/winpty/issues/116)
+ * Fix a theoretical issue with input event ordering.
+   [#117](https://github.com/rprichard/winpty/issues/117)
+ * Ctrl/Shift+{Arrow,Home,End} keys now work with IntelliJ.
+   [#118](https://github.com/rprichard/winpty/issues/118)
+
+# Version 0.4.3 (2017-05-17)
+
+Input handling changes:
+
+ * winpty sets `ENHANCED_KEY` for arrow and navigation keys.  This fixes an
+   issue with the Ruby REPL.
+   [#99](https://github.com/rprichard/winpty/issues/99)
+ * AltGr keys are handled better now.
+   [#109](https://github.com/rprichard/winpty/issues/109)
+ * In `ENABLE_VIRTUAL_TERMINAL_INPUT` mode, when typing Home/End with a
+   modifier (e.g. Ctrl), winpty now generates an H/F escape sequence like
+   `^[[1;5F` rather than a 1/4 escape like `^[[4;5~`.
+   [#114](https://github.com/rprichard/winpty/issues/114)
+
+Resizing and scraping fixes:
+
+ * winpty now synthesizes a `WINDOW_BUFFER_SIZE_EVENT` event after resizing
+   the console to better propagate window size changes to console programs.
+   In particular, this affects WSL and Cygwin.
+   [#110](https://github.com/rprichard/winpty/issues/110)
+ * Better handling of resizing for certain full-screen programs, like
+   WSL less.
+   [#112](https://github.com/rprichard/winpty/issues/112)
+ * Hide the cursor if it's currently outside the console window.  This change
+   fixes an issue with Far Manager.
+   [#113](https://github.com/rprichard/winpty/issues/113)
+ * winpty now avoids using console fonts smaller than 5px high to improve
+   half-vs-full-width character handling.  See
+   https://github.com/Microsoft/vscode/issues/19665.
+   [b4db322010](https://github.com/rprichard/winpty/commit/b4db322010d2d897e6c496fefc4f0ecc9b84c2f3)
+
+Cygwin/MSYS adapter fix:
+
+ * The way the `winpty` Cygwin/MSYS2 adapter searches for the program to
+   launch changed.  It now resolves symlinks and searches the PATH explicitly.
+   [#81](https://github.com/rprichard/winpty/issues/81)
+   [#98](https://github.com/rprichard/winpty/issues/98)
+
+This release does not include binaries for the old MSYS1 project anymore.
+MSYS2 will continue to be supported.  See
+https://github.com/rprichard/winpty/issues/97.
+
+# Version 0.4.2 (2017-01-18)
+
+This release improves WSL support (i.e. Bash-on-Windows):
+
+ * winpty generates more correct input escape sequences for WSL programs that
+   enable an alternate input mode using DECCKM.  This bug affected arrow keys
+   and Home/End in WSL programs such as `vim`, `mc`, and `less`.
+   [#90](https://github.com/rprichard/winpty/issues/90)
+ * winpty now recognizes the `COMMON_LVB_REVERSE_VIDEO` and
+   `COMMON_LVB_UNDERSCORE` text attributes.  The Windows console uses these
+   attributes to implement the SGR.4(Underline) and SGR.7(Negative) modes in
+   its VT handling.  This change affects WSL pager status bars, man pages, etc.
+
+The build system no longer has a "version suffix" mechanism, so passing
+`VERSION_SUFFIX=<suffix>` to make or `-D VERSION_SUFFIX=<suffix>` to gyp now
+has no effect.  AFAIK, the mechanism was never used publicly.
+[67a34b6c03](https://github.com/rprichard/winpty/commit/67a34b6c03557a5c2e0a2bdd502c2210921d8f3e)
+
+# Version 0.4.1 (2017-01-03)
+
+Bug fixes:
+
+ * This version fixes a bug where the `winpty-agent.exe` process could read
+   past the end of a buffer.
+   [#94](https://github.com/rprichard/winpty/issues/94)
+
+# Version 0.4.0 (2016-06-28)
+
+The winpty library has a new API that should be easier for embedding.
+[880c00c69e](https://github.com/rprichard/winpty/commit/880c00c69eeca73643ddb576f02c5badbec81f56)
+
+User-visible changes:
+
+ * winpty now automatically puts the terminal into mouse mode when it detects
+   that the console has left QuickEdit mode.  The `--mouse` option still forces
+   the terminal into mouse mode.  In principle, an option could be added to
+   suppress terminal mode, but hopefully it won't be necessary.  There is a
+   script in the `misc` subdirectory, `misc/ConinMode.ps1`, that can change
+   the QuickEdit mode from the command-line.
+ * winpty now passes keyboard escapes to `bash.exe` in the Windows Subsystem
+   for Linux.
+   [#82](https://github.com/rprichard/winpty/issues/82)
+
+Bug fixes:
+
+ * By default, `winpty.dll` avoids calling `SetProcessWindowStation` within
+   the calling process.
+   [#58](https://github.com/rprichard/winpty/issues/58)
+ * Fixed an uninitialized memory bug that could have crashed winpty.
+   [#80](https://github.com/rprichard/winpty/issues/80)
+ * winpty now works better with very large and very small terminal windows.
+   It resizes the console font according to the number of columns.
+   [#61](https://github.com/rprichard/winpty/issues/61)
+ * winpty no longer uses Mark to freeze the console on Windows 10.  The Mark
+   command could interfere with the cursor position, corrupting the data in
+   the screen buffer.
+   [#79](https://github.com/rprichard/winpty/issues/79)
+
+# Version 0.3.0 (2016-05-20)
+
+User-visible changes:
+
+ * The UNIX adapter is renamed from `console.exe` to `winpty.exe` to be
+   consistent with MSYS2.  The name `winpty.exe` is less likely to conflict
+   with another program and is easier to search for online (e.g. for someone
+   unfamiliar with winpty).
+ * The UNIX adapter now clears the `TERM` variable.
+   [#43](https://github.com/rprichard/winpty/issues/43)
+ * An escape character appearing in a console screen buffer cell is converted
+   to a '?'.
+   [#47](https://github.com/rprichard/winpty/issues/47)
+
+Bug fixes:
+
+ * A major bug affecting XP users was fixed.
+   [#67](https://github.com/rprichard/winpty/issues/67)
+ * Fixed an incompatibility with ConEmu where winpty hung if ConEmu's
+   "Process 'start'" feature was enabled.
+   [#70](https://github.com/rprichard/winpty/issues/70)
+ * Fixed a bug where `cmd.exe` sometimes printed the message,
+   `Not enough storage is available to process this command.`.
+   [#74](https://github.com/rprichard/winpty/issues/74)
+
+Many changes internally:
+
+ * The codebase is switched from C++03 to C++11 and uses exceptions internally.
+   No exceptions are thrown across the C APIs defined in `winpty.h`.
+ * This version drops support for the original MinGW compiler packaged with
+   Cygwin (`i686-pc-mingw32-g++`).  The MinGW-w64 compiler is still supported,
+   as is the MinGW distributed at mingw.org.  Compiling with MSVC now requires
+   MSVC 2013 or newer.  Windows XP is still supported.
+   [ec3eae8df5](https://github.com/rprichard/winpty/commit/ec3eae8df5bbbb36d7628d168b0815638d122f37)
+ * Pipe security is improved.  winpty works harder to produce unique pipe names
+   and includes a random component in the name.  winpty secures pipes with a
+   DACL that prevents arbitrary users from connecting to its pipes.  winpty now
+   passes `PIPE_REJECT_REMOTE_CLIENTS` on Vista and up, and it verifies that
+   the pipe client PID is correct, again on Vista and up.  When connecting to a
+   named pipe, winpty uses the `SECURITY_IDENTIFICATION` flag to restrict
+   impersonation.  Previous versions *should* still be secure.
+ * `winpty-debugserver.exe` now has an `--everyone` flag that allows capturing
+   debug output from other users.
+ * The code now compiles cleanly with MSVC's "Security Development Lifecycle"
+   (`/SDL`) checks enabled.
+
+# Version 0.2.2 (2016-02-25)
+
+Minor bug fixes and enhancements:
+
+ * Fix a bug that generated spurious mouse input records when an incomplete
+   mouse escape sequence was seen.
+ * Fix a buffer overflow bug in `winpty-debugserver.exe` affecting messages of
+   exactly 4096 bytes.
+ * For MSVC builds, add a `src/configurations.gypi` file that can be included
+   on the gyp command-line to enable 32-bit and 64-bit builds.
+ * `winpty-agent --show-input` mode: Flush stdout after each line.
+ * Makefile builds: generate a `build/winpty.lib` import library to accompany
+   `build/winpty.dll`.
+
+# Version 0.2.1 (2015-12-19)
+
+ * The main project source was moved into a `src` directory for better code
+   organization and to fix
+   [#51](https://github.com/rprichard/winpty/issues/51).
+ * winpty recognizes many more escape sequences, including:
+    * putty/rxvt's F1-F4 keys
+      [#40](https://github.com/rprichard/winpty/issues/40)
+    * the Linux virtual console's F1-F5 keys
+    * the "application numpad" keys (e.g. enabled with DECPAM)
+ * Fixed handling of Shift-Alt-O and Alt-[.
+ * Added support for mouse input.  The UNIX adapter has a `--mouse` argument
+   that puts the terminal into mouse mode, but the agent recognizes mouse
+   input even without the argument.  The agent recognizes double-clicks using
+   Windows' double-click interval setting (i.e. GetDoubleClickTime).
+   [#57](https://github.com/rprichard/winpty/issues/57)
+
+Changes to debugging interfaces:
+
+ * The `WINPTY_DEBUG` variable is now a comma-separated list.  The old
+   behavior (i.e. tracing) is enabled with `WINPTY_DEBUG=trace`.
+ * The UNIX adapter program now has a `--showkey` argument that dumps input
+   bytes.
+ * The `winpty-agent.exe` program has a `--show-input` argument that dumps
+   `INPUT_RECORD` records.  (It omits mouse events unless `--with-mouse` is
+   also specified.)  The agent also responds to `WINPTY_DEBUG=trace,input`,
+   which logs input bytes and synthesized console events, and it responds to
+   `WINPTY_DEBUG=trace,dump_input_map`, which dumps the internal table of
+   escape sequences.
+
+# Version 0.2.0 (2015-11-13)
+
+No changes to the API, but many small changes to the implementation.  The big
+changes include:
+
+ * Support for 64-bit Cygwin and MSYS2
+ * Support for Windows 10
+ * Better Unicode support (especially East Asian languages)
+
+Details:
+
+ * The `configure` script recognizes 64-bit Cygwin and MSYS2 environments and
+   selects the appropriate compiler.
+ * winpty works much better with the upgraded console in Windows 10.  The
+   `conhost.exe` hang can still occur, but only with certain programs, and
+   is much less likely to occur.  With the new console, use Mark instead of
+   SelectAll, for better performance.
+   [#31](https://github.com/rprichard/winpty/issues/31)
+   [#30](https://github.com/rprichard/winpty/issues/30)
+   [#53](https://github.com/rprichard/winpty/issues/53)
+ * The UNIX adapter now calls `setlocale(LC_ALL, "")` to set the locale.
+ * Improved Unicode support.  When a console is started with an East Asian code
+   page, winpty now chooses an East Asian font rather than Consolas / Lucida
+   Console.  Selecting the right font helps synchronize character widths
+   between the console and terminal.  (It's not perfect, though.)
+   [#41](https://github.com/rprichard/winpty/issues/41)
+ * winpty now more-or-less works with programs that change the screen buffer
+   or resize the original screen buffer.  If the screen buffer height changes,
+   winpty switches to a "direct mode", where it makes no effort to track
+   scrolling.  In direct mode, it merely syncs snapshots of the console to the
+   terminal.  Caveats:
+    * Changing the screen buffer (i.e. `SetConsoleActiveScreenBuffer`)
+      breaks winpty on Windows 7.  This problem can eventually be mitigated,
+      but never completely fixed, due to Windows 7 bugginess.
+    * Resizing the original screen buffer can hang `conhost.exe` on Windows 10.
+      Enabling the legacy console is a workaround.
+    * If a program changes the screen buffer and then exits, relying on the OS
+      to restore the original screen buffer, that restoration probably will not
+      happen with winpty.  winpty's behavior can probably be improved here.
+ * Improved color handling:
+    * DkGray-on-Black text was previously hiddenly completely.  Now it is
+      output as DkGray, with a fallback to LtGray on terminals that don't
+      recognize the intense colors.
+      [#39](https://github.com/rprichard/winpty/issues/39).
+    * The console is always initialized to LtGray-on-Black, regardless of the
+      user setting, which matches the console color heuristic, which translates
+      LtGray-on-Black to "reset SGR parameters."
+ * Shift-Tab is recognized correctly now.
+   [#19](https://github.com/rprichard/winpty/issues/19)
+ * Add a `--version` argument to `winpty-agent.exe` and the UNIX adapter.  The
+   argument reports the nominal version (i.e. the `VERSION.txt`) file, with a
+   "VERSION_SUFFIX" appended (defaulted to `-dev`), and a git commit hash, if
+   the `git` command successfully reports a hash during the build.  The `git`
+   command is invoked by either `make` or `gyp`.
+ * The agent now combines `ReadConsoleOutputW` calls when it polls the console
+   buffer for changes, which may slightly reduce its CPU overhead.
+   [#44](https://github.com/rprichard/winpty/issues/44).
+ * A `gyp` file is added to help compile with MSVC.
+ * The code can now be compiled as C++11 code, though it isn't by default.
+   [bde8922e08](https://github.com/rprichard/winpty/commit/bde8922e08c3638e01ecc7b581b676c314163e3c)
+ * If winpty can't create a new window station, it charges ahead rather than
+   aborting.  This situation might happen if winpty were started from an SSH
+   session.
+ * Debugging improvements:
+    * `WINPTYDBG` is renamed to `WINPTY_DEBUG`, and a new `WINPTY_SHOW_CONSOLE`
+      variable keeps the underlying console visible.
+    * A `winpty-debugserver.exe` program is built and shipped by default.  It
+      collects the trace output enabled with `WINPTY_DEBUG`.
+ * The `Makefile` build of winpty now compiles `winpty-agent.exe` and
+   `winpty.dll` with -O2.
+
+# Version 0.1.1 (2012-07-28)
+
+Minor bugfix release.
+
+# Version 0.1 (2012-04-17)
+
+Initial release.
diff --git a/node_modules/node-pty/deps/winpty/VERSION.txt b/node_modules/node-pty/deps/winpty/VERSION.txt
new file mode 100644 (file)
index 0000000..5d47ff8
--- /dev/null
@@ -0,0 +1 @@
+0.4.4-dev
diff --git a/node_modules/node-pty/deps/winpty/configure b/node_modules/node-pty/deps/winpty/configure
new file mode 100644 (file)
index 0000000..6d37d65
--- /dev/null
@@ -0,0 +1,167 @@
+#!/bin/bash
+#
+# Copyright (c) 2011-2015 Ryan Prichard
+#
+# 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.
+
+#
+# findTool(desc, commandList)
+#
+# Searches commandLine for the first command in the PATH and returns it.
+# Prints an error and aborts the script if no match is found.
+#
+FINDTOOL_OUT=""
+function findTool {
+    DESC=$1
+    OPTIONS=$2
+    for CMD in ${OPTIONS}; do
+        if (which $CMD &>/dev/null) then
+            echo "Found $DESC: $CMD"
+            FINDTOOL_OUT="$CMD"
+            return
+        fi
+    done
+    echo "Error: could not find $DESC.  One of these should be in your PATH:"
+    for CMD in ${OPTIONS}; do
+        echo " * $CMD"
+    done
+    exit 1
+}
+
+IS_CYGWIN=0
+IS_MSYS1=0
+IS_MSYS2=0
+
+# Link parts of the Cygwin binary statically to aid in redistribution?  The
+# binary still links dynamically against the main DLL.  The MinGW binaries are
+# also statically linked and therefore depend only on Windows DLLs.  I started
+# linking the Cygwin/MSYS binary statically, because G++ 4.7 changed the
+# Windows C++ ABI.
+UNIX_LDFLAGS_STATIC='-static -static-libgcc -static-libstdc++'
+
+# Detect the environment -- Cygwin or MSYS.
+case $(uname -s) in
+    CYGWIN*)
+        echo 'uname -s identifies a Cygwin environment.'
+        IS_CYGWIN=1
+           case $(uname -m) in
+            i686)
+                echo 'uname -m identifies an i686 environment.'
+                UNIX_CXX=i686-pc-cygwin-g++
+                MINGW_CXX=i686-w64-mingw32-g++
+                ;;
+            x86_64)
+                echo 'uname -m identifies an x86_64 environment.'
+                UNIX_CXX=x86_64-pc-cygwin-g++
+                MINGW_CXX=x86_64-w64-mingw32-g++
+                ;;
+            *)
+                echo 'Error: uname -m did not match either i686 or x86_64.'
+                exit 1
+                ;;
+           esac
+        ;;
+    MSYS*|MINGW*)
+        # MSYS2 notes:
+        #  - MSYS2 offers two shortcuts to open an environment:
+        #     - MinGW-w64 Win32 Shell.  This env reports a `uname -s` of
+        #       MINGW32_NT-6.1 on 32-bit Win7.  The MinGW-w64 compiler
+        #       (i686-w64-mingw32-g++.exe) is in the PATH.
+        #     - MSYS2 Shell.  `uname -s` instead reports MSYS_NT-6.1.
+        #       The i686-w64-mingw32-g++ compiler is not in the PATH.
+        #  - MSYS2 appears to use MinGW-w64, not the older mingw.org.
+        # MSYS notes:
+        #  - `uname -s` is always MINGW32_NT-6.1 on Win7.
+        echo 'uname -s identifies an MSYS/MSYS2 environment.'
+        case $(uname -m) in
+            i686)
+                echo 'uname -m identifies an i686 environment.'
+                UNIX_CXX=i686-pc-msys-g++
+                if echo "$(uname -r)" | grep '^1[.]' > /dev/null; then
+                    # The MSYS-targeting compiler for the original 32-bit-only
+                    # MSYS does not recognize the -static-libstdc++ flag, and
+                    # it does not work with -static, because it tries to link
+                    # statically with the core MSYS library and fails.
+                    #
+                    # Distinguish between the two using the major version
+                    # number of `uname -r`:
+                    #
+                    #   MSYS uname -r:  1.0.18(0.48/3/2)
+                    #   MSYS2 uname -r: 2.0.0(0.284/5/3)
+                    #
+                    # This is suboptimal because MSYS2 is not actually the
+                    # second version of MSYS--it's a brand-new fork of Cygwin.
+                    #
+                    IS_MSYS1=1
+                    UNIX_LDFLAGS_STATIC=
+                    MINGW_CXX=mingw32-g++
+                else
+                    IS_MSYS2=1
+                    MINGW_CXX=i686-w64-mingw32-g++.exe
+                fi
+                ;;
+            x86_64)
+                echo 'uname -m identifies an x86_64 environment.'
+                IS_MSYS2=1
+                UNIX_CXX=x86_64-pc-msys-g++
+                MINGW_CXX=x86_64-w64-mingw32-g++
+                ;;
+            *)
+                echo 'Error: uname -m did not match either i686 or x86_64.'
+                exit 1
+                ;;
+        esac
+        ;;
+    *)
+        echo 'Error: uname -s did not match either CYGWIN* or MINGW*.'
+        exit 1
+        ;;
+esac
+
+# Search the PATH and pick the first match.
+findTool "Cygwin/MSYS G++ compiler" "$UNIX_CXX"
+UNIX_CXX=$FINDTOOL_OUT
+findTool "MinGW G++ compiler" "$MINGW_CXX"
+MINGW_CXX=$FINDTOOL_OUT
+
+# Write config files.
+echo Writing config.mk
+echo UNIX_CXX=$UNIX_CXX > config.mk
+echo UNIX_LDFLAGS_STATIC=$UNIX_LDFLAGS_STATIC >> config.mk
+echo MINGW_CXX=$MINGW_CXX >> config.mk
+
+if test $IS_MSYS1 = 1; then
+    echo UNIX_CXXFLAGS += -DWINPTY_TARGET_MSYS1 >> config.mk
+    # The MSYS1 MinGW compiler has a bug that prevents inclusion of algorithm
+    # and math.h in normal C++11 mode.  The workaround is to enable the gnu++11
+    # mode instead.  The bug was fixed on 2015-07-31, but as of 2016-02-26, the
+    # fix apparently hasn't been released.  See
+    # http://ehc.ac/p/mingw/bugs/2250/.
+    echo MINGW_ENABLE_CXX11_FLAG := -std=gnu++11 >> config.mk
+fi
+
+if test -d .git -a -f .git/HEAD -a -f .git/index && git rev-parse HEAD >&/dev/null; then
+    echo "Commit info: git"
+    echo 'COMMIT_HASH = $(shell git rev-parse HEAD)' >> config.mk
+    echo 'COMMIT_HASH_DEP := config.mk .git/HEAD .git/index' >> config.mk
+else
+    echo "Commit info: none"
+    echo 'COMMIT_HASH := none' >> config.mk
+    echo 'COMMIT_HASH_DEP := config.mk' >> config.mk
+fi
diff --git a/node_modules/node-pty/deps/winpty/misc/.gitignore b/node_modules/node-pty/deps/winpty/misc/.gitignore
new file mode 100644 (file)
index 0000000..2375164
--- /dev/null
@@ -0,0 +1,2 @@
+*.exe
+UnixEcho
\ No newline at end of file
diff --git a/node_modules/node-pty/deps/winpty/misc/BufferResizeTests.cc b/node_modules/node-pty/deps/winpty/misc/BufferResizeTests.cc
new file mode 100644 (file)
index 0000000..a5bb074
--- /dev/null
@@ -0,0 +1,90 @@
+#include <windows.h>
+#include <cassert>
+
+#include "TestUtil.cc"
+
+void dumpInfoToTrace() {
+    CONSOLE_SCREEN_BUFFER_INFO info;
+    assert(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info));
+    trace("win=(%d,%d,%d,%d)",
+        (int)info.srWindow.Left,
+        (int)info.srWindow.Top,
+        (int)info.srWindow.Right,
+        (int)info.srWindow.Bottom);
+    trace("buf=(%d,%d)",
+        (int)info.dwSize.X,
+        (int)info.dwSize.Y);
+    trace("cur=(%d,%d)",
+        (int)info.dwCursorPosition.X,
+        (int)info.dwCursorPosition.Y);
+}
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    setWindowPos(0, 0, 1, 1);
+
+    if (false) {
+        // Reducing the buffer height can move the window up.
+        setBufferSize(80, 25);
+        setWindowPos(0, 20, 80, 5);
+        Sleep(2000);
+        setBufferSize(80, 10);
+    }
+
+    if (false) {
+        // Reducing the buffer height moves the window up and the buffer
+        // contents up too.
+        setBufferSize(80, 25);
+        setWindowPos(0, 20, 80, 5);
+        setCursorPos(0, 20);
+        printf("TEST1\nTEST2\nTEST3\nTEST4\n");
+        fflush(stdout);
+        Sleep(2000);
+        setBufferSize(80, 10);
+    }
+
+    if (false) {
+        // Reducing the buffer width can move the window left.
+        setBufferSize(80, 25);
+        setWindowPos(40, 0, 40, 25);
+        Sleep(2000);
+        setBufferSize(60, 25);
+    }
+
+    if (false) {
+        // Sometimes the buffer contents are shifted up; sometimes they're
+        // shifted down.  It seems to depend on the cursor position?
+
+        // setBufferSize(80, 25);
+        // setWindowPos(0, 20, 80, 5);
+        // setCursorPos(0, 20);
+        // printf("TESTa\nTESTb\nTESTc\nTESTd\nTESTe");
+        // fflush(stdout);
+        // setCursorPos(0, 0);
+        // printf("TEST1\nTEST2\nTEST3\nTEST4\nTEST5");
+        // fflush(stdout);
+        // setCursorPos(0, 24);
+        // Sleep(5000);
+        // setBufferSize(80, 24);
+
+        setBufferSize(80, 20);
+        setWindowPos(0, 10, 80, 10);
+        setCursorPos(0, 18);
+
+        printf("TEST1\nTEST2");
+        fflush(stdout);
+        setCursorPos(0, 18);
+
+        Sleep(2000);
+        setBufferSize(80, 18);
+    }
+
+    dumpInfoToTrace();
+    Sleep(30000);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ChangeScreenBuffer.cc b/node_modules/node-pty/deps/winpty/misc/ChangeScreenBuffer.cc
new file mode 100644 (file)
index 0000000..701a2cb
--- /dev/null
@@ -0,0 +1,53 @@
+// A test program for CreateConsoleScreenBuffer / SetConsoleActiveScreenBuffer
+//
+
+#include <windows.h>
+#include <stdio.h>
+#include <conio.h>
+#include <io.h>
+#include <cassert>
+
+#include "TestUtil.cc"
+
+int main()
+{
+    HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
+    HANDLE childBuffer = CreateConsoleScreenBuffer(
+            GENERIC_READ | GENERIC_WRITE,
+            FILE_SHARE_READ | FILE_SHARE_WRITE,
+            NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
+
+    SetConsoleActiveScreenBuffer(childBuffer);
+
+    while (true) {
+        char buf[1024];
+        CONSOLE_SCREEN_BUFFER_INFO info;
+
+        assert(GetConsoleScreenBufferInfo(origBuffer, &info));
+        trace("child.size=(%d,%d)", (int)info.dwSize.X, (int)info.dwSize.Y);
+        trace("child.cursor=(%d,%d)", (int)info.dwCursorPosition.X, (int)info.dwCursorPosition.Y);
+        trace("child.window=(%d,%d,%d,%d)",
+            (int)info.srWindow.Left, (int)info.srWindow.Top,
+            (int)info.srWindow.Right, (int)info.srWindow.Bottom);
+        trace("child.maxSize=(%d,%d)", (int)info.dwMaximumWindowSize.X, (int)info.dwMaximumWindowSize.Y);
+
+        int ch = getch();
+        sprintf(buf, "%02x\n", ch);
+        DWORD actual = 0;
+        WriteFile(childBuffer, buf, strlen(buf), &actual, NULL);
+        if (ch == 0x1b/*ESC*/ || ch == 0x03/*CTRL-C*/)
+            break;
+
+        if (ch == 'b') {
+            setBufferSize(origBuffer, 40, 25);
+        } else if (ch == 'w') {
+            setWindowPos(origBuffer, 1, 1, 38, 23);
+        } else if (ch == 'c') {
+            setCursorPos(origBuffer, 10, 10);
+        }
+    }
+
+    SetConsoleActiveScreenBuffer(origBuffer);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ClearConsole.cc b/node_modules/node-pty/deps/winpty/misc/ClearConsole.cc
new file mode 100644 (file)
index 0000000..f95f8c8
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Demonstrates that console clearing sets each cell's character to SP, not
+ * NUL, and it sets the attribute of each cell to the current text attribute.
+ *
+ * This confirms the MSDN instruction in the "Clearing the Screen" article.
+ * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682022(v=vs.85).aspx
+ * It advises using GetConsoleScreenBufferInfo to get the current text
+ * attribute, then FillConsoleOutputCharacter and FillConsoleOutputAttribute to
+ * write to the console buffer.
+ */
+
+#include <windows.h>
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    SetConsoleTextAttribute(conout, 0x24);
+    system("cls");
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(80, 25);
+    setWindowPos(0, 0, 80, 25);
+
+    CHAR_INFO buf;
+    COORD bufSize = { 1, 1 };
+    COORD bufCoord = { 0, 0 };
+    SMALL_RECT rect = { 5, 5, 5, 5 };
+    BOOL ret;
+    DWORD actual;
+    COORD writeCoord = { 5, 5 };
+
+    // After cls, each cell's character is a space, and its attributes are the
+    // default text attributes.
+    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
+    assert(ret && buf.Char.UnicodeChar == L' ' && buf.Attributes == 0x24);
+
+    // Nevertheless, it is possible to change a cell to NUL.
+    ret = FillConsoleOutputCharacterW(conout, L'\0', 1, writeCoord, &actual);
+    assert(ret && actual == 1);
+    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
+    assert(ret && buf.Char.UnicodeChar == L'\0' && buf.Attributes == 0x24);
+
+    // As well as a 0 attribute.  (As one would expect, the cell is
+    // black-on-black.)
+    ret = FillConsoleOutputAttribute(conout, 0, 1, writeCoord, &actual);
+    assert(ret && actual == 1);
+    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
+    assert(ret && buf.Char.UnicodeChar == L'\0' && buf.Attributes == 0);
+    ret = FillConsoleOutputCharacterW(conout, L'X', 1, writeCoord, &actual);
+    assert(ret && actual == 1);
+    ret = ReadConsoleOutputW(conout, &buf, bufSize, bufCoord, &rect);
+    assert(ret && buf.Char.UnicodeChar == L'X' && buf.Attributes == 0);
+
+    // The 'X' is invisible.
+    countDown(3);
+
+    ret = FillConsoleOutputAttribute(conout, 0x42, 1, writeCoord, &actual);
+    assert(ret && actual == 1);
+
+    countDown(5);
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ConinMode.cc b/node_modules/node-pty/deps/winpty/misc/ConinMode.cc
new file mode 100644 (file)
index 0000000..1e1428d
--- /dev/null
@@ -0,0 +1,117 @@
+#include <windows.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <string>
+#include <vector>
+
+static HANDLE getConin() {
+    HANDLE conin = GetStdHandle(STD_INPUT_HANDLE);
+    if (conin == INVALID_HANDLE_VALUE) {
+        fprintf(stderr, "error: cannot get stdin\n");
+        exit(1);
+    }
+    return conin;
+}
+
+static DWORD getConsoleMode() {
+    DWORD mode = 0;
+    if (!GetConsoleMode(getConin(), &mode)) {
+        fprintf(stderr, "error: GetConsoleMode failed (is stdin a console?)\n");
+        exit(1);
+    }
+    return mode;
+}
+
+static void setConsoleMode(DWORD mode) {
+    if (!SetConsoleMode(getConin(), mode)) {
+        fprintf(stderr, "error: SetConsoleMode failed (is stdin a console?)\n");
+        exit(1);
+    }
+}
+
+static long parseInt(const std::string &s) {
+    errno = 0;
+    char *endptr = nullptr;
+    long result = strtol(s.c_str(), &endptr, 0);
+    if (errno != 0 || !endptr || *endptr != '\0') {
+        fprintf(stderr, "error: could not parse integral argument '%s'\n", s.c_str());
+        exit(1);
+    }
+    return result;
+}
+
+static void usage() {
+    printf("Usage: ConinMode [verb] [options]\n");
+    printf("Verbs:\n");
+    printf("    [info]      Dumps info about mode flags.\n");
+    printf("    get         Prints the mode DWORD.\n");
+    printf("    set VALUE   Sets the mode to VALUE, which can be decimal, hex, or octal.\n");
+    printf("    set VALUE MASK\n");
+    printf("                Same as `set VALUE`, but only alters the bits in MASK.\n");
+    exit(1);
+}
+
+struct {
+    const char *name;
+    DWORD value;
+} kInputFlags[] = {
+    "ENABLE_PROCESSED_INPUT",           ENABLE_PROCESSED_INPUT,         // 0x0001
+    "ENABLE_LINE_INPUT",                ENABLE_LINE_INPUT,              // 0x0002
+    "ENABLE_ECHO_INPUT",                ENABLE_ECHO_INPUT,              // 0x0004
+    "ENABLE_WINDOW_INPUT",              ENABLE_WINDOW_INPUT,            // 0x0008
+    "ENABLE_MOUSE_INPUT",               ENABLE_MOUSE_INPUT,             // 0x0010
+    "ENABLE_INSERT_MODE",               ENABLE_INSERT_MODE,             // 0x0020
+    "ENABLE_QUICK_EDIT_MODE",           ENABLE_QUICK_EDIT_MODE,         // 0x0040
+    "ENABLE_EXTENDED_FLAGS",            ENABLE_EXTENDED_FLAGS,          // 0x0080
+    "ENABLE_VIRTUAL_TERMINAL_INPUT", 0x0200/*ENABLE_VIRTUAL_TERMINAL_INPUT*/, // 0x0200
+};
+
+int main(int argc, char *argv[]) {
+    std::vector<std::string> args;
+    for (size_t i = 1; i < argc; ++i) {
+        args.push_back(argv[i]);
+    }
+
+    if (args.empty() || args.size() == 1 && args[0] == "info") {
+        DWORD mode = getConsoleMode();
+        printf("mode: 0x%lx\n", mode);
+        for (const auto &flag : kInputFlags) {
+            printf("%-29s 0x%04lx %s\n", flag.name, flag.value, flag.value & mode ? "ON" : "off");
+            mode &= ~flag.value;
+        }
+        for (int i = 0; i < 32; ++i) {
+            if (mode & (1u << i)) {
+                printf("Unrecognized flag: %04x\n", (1u << i));
+            }
+        }
+        return 0;
+    }
+
+    const auto verb = args[0];
+
+    if (verb == "set") {
+        if (args.size() == 2) {
+            const DWORD newMode = parseInt(args[1]);
+            setConsoleMode(newMode);
+        } else if (args.size() == 3) {
+            const DWORD mode = parseInt(args[1]);
+            const DWORD mask = parseInt(args[2]);
+            const int newMode = (getConsoleMode() & ~mask) | (mode & mask);
+            setConsoleMode(newMode);
+        } else {
+            usage();
+        }
+    } else if (verb == "get") {
+        if (args.size() != 1) {
+            usage();
+        }
+        printf("0x%lx\n", getConsoleMode());
+    } else {
+        usage();
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ConinMode.ps1 b/node_modules/node-pty/deps/winpty/misc/ConinMode.ps1
new file mode 100644 (file)
index 0000000..ecfe8f0
--- /dev/null
@@ -0,0 +1,116 @@
+#
+# PowerShell script for controlling the console QuickEdit and InsertMode flags.
+#
+# Turn QuickEdit off to interact with mouse-driven console programs.
+#
+# Usage:
+#
+# powershell .\ConinMode.ps1 [Options]
+#
+# Options:
+#   -QuickEdit [on/off]
+#   -InsertMode [on/off]
+#   -Mode [integer]
+#
+
+param (
+    [ValidateSet("on", "off")][string] $QuickEdit,
+    [ValidateSet("on", "off")][string] $InsertMode,
+    [int] $Mode
+)
+
+$signature = @'
+[DllImport("kernel32.dll", SetLastError = true)]
+public static extern IntPtr GetStdHandle(int nStdHandle);
+
+[DllImport("kernel32.dll", SetLastError = true)]
+public static extern uint GetConsoleMode(
+    IntPtr hConsoleHandle,
+    out uint lpMode);
+
+[DllImport("kernel32.dll", SetLastError = true)]
+public static extern uint SetConsoleMode(
+    IntPtr hConsoleHandle,
+    uint dwMode);
+
+public const int STD_INPUT_HANDLE = -10;
+public const int ENABLE_INSERT_MODE = 0x0020;
+public const int ENABLE_QUICK_EDIT_MODE = 0x0040;
+public const int ENABLE_EXTENDED_FLAGS = 0x0080;
+'@
+
+$WinAPI = Add-Type -MemberDefinition $signature `
+    -Name WinAPI -Namespace ConinModeScript `
+    -PassThru
+
+function GetConIn {
+    $ret = $WinAPI::GetStdHandle($WinAPI::STD_INPUT_HANDLE)
+    if ($ret -eq -1) {
+        throw "error: cannot get stdin"
+    }
+    return $ret
+}
+
+function GetConsoleMode {
+    $conin = GetConIn
+    $mode = 0
+    $ret = $WinAPI::GetConsoleMode($conin, [ref]$mode)
+    if ($ret -eq 0) {
+        throw "GetConsoleMode failed (is stdin a console?)"
+    }
+    return $mode
+}
+
+function SetConsoleMode($mode) {
+    $conin = GetConIn
+    $ret = $WinAPI::SetConsoleMode($conin, $mode)
+    if ($ret -eq 0) {
+        throw "SetConsoleMode failed (is stdin a console?)"
+    }
+}
+
+$oldMode = GetConsoleMode
+$newMode = $oldMode
+$doingSomething = $false
+
+if ($PSBoundParameters.ContainsKey("Mode")) {
+    $newMode = $Mode
+    $doingSomething = $true
+}
+
+if ($QuickEdit + $InsertMode -ne "") {
+    if (!($newMode -band $WinAPI::ENABLE_EXTENDED_FLAGS)) {
+        # We can't enable an extended flag without overwriting the existing
+        # QuickEdit/InsertMode flags.  AFAICT, there is no way to query their
+        # existing values, so at least we can choose sensible defaults.
+        $newMode = $newMode -bor $WinAPI::ENABLE_EXTENDED_FLAGS
+        $newMode = $newMode -bor $WinAPI::ENABLE_QUICK_EDIT_MODE
+        $newMode = $newMode -bor $WinAPI::ENABLE_INSERT_MODE
+        $doingSomething = $true
+    }
+}
+
+if ($QuickEdit -eq "on") {
+    $newMode = $newMode -bor $WinAPI::ENABLE_QUICK_EDIT_MODE
+    $doingSomething = $true
+} elseif ($QuickEdit -eq "off") {
+    $newMode = $newMode -band (-bnot $WinAPI::ENABLE_QUICK_EDIT_MODE)
+    $doingSomething = $true
+}
+
+if ($InsertMode -eq "on") {
+    $newMode = $newMode -bor $WinAPI::ENABLE_INSERT_MODE
+    $doingSomething = $true
+} elseif ($InsertMode -eq "off") {
+    $newMode = $newMode -band (-bnot $WinAPI::ENABLE_INSERT_MODE)
+    $doingSomething = $true
+}
+
+if ($doingSomething) {
+    echo "old mode: $oldMode"
+    SetConsoleMode $newMode
+    $newMode = GetConsoleMode
+    echo "new mode: $newMode"
+} else {
+    echo "mode: $oldMode"
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ConoutMode.cc b/node_modules/node-pty/deps/winpty/misc/ConoutMode.cc
new file mode 100644 (file)
index 0000000..100e0c7
--- /dev/null
@@ -0,0 +1,113 @@
+#include <windows.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <string>
+#include <vector>
+
+static HANDLE getConout() {
+    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+    if (conout == INVALID_HANDLE_VALUE) {
+        fprintf(stderr, "error: cannot get stdout\n");
+        exit(1);
+    }
+    return conout;
+}
+
+static DWORD getConsoleMode() {
+    DWORD mode = 0;
+    if (!GetConsoleMode(getConout(), &mode)) {
+        fprintf(stderr, "error: GetConsoleMode failed (is stdout a console?)\n");
+        exit(1);
+    }
+    return mode;
+}
+
+static void setConsoleMode(DWORD mode) {
+    if (!SetConsoleMode(getConout(), mode)) {
+        fprintf(stderr, "error: SetConsoleMode failed (is stdout a console?)\n");
+        exit(1);
+    }
+}
+
+static long parseInt(const std::string &s) {
+    errno = 0;
+    char *endptr = nullptr;
+    long result = strtol(s.c_str(), &endptr, 0);
+    if (errno != 0 || !endptr || *endptr != '\0') {
+        fprintf(stderr, "error: could not parse integral argument '%s'\n", s.c_str());
+        exit(1);
+    }
+    return result;
+}
+
+static void usage() {
+    printf("Usage: ConoutMode [verb] [options]\n");
+    printf("Verbs:\n");
+    printf("    [info]      Dumps info about mode flags.\n");
+    printf("    get         Prints the mode DWORD.\n");
+    printf("    set VALUE   Sets the mode to VALUE, which can be decimal, hex, or octal.\n");
+    printf("    set VALUE MASK\n");
+    printf("                Same as `set VALUE`, but only alters the bits in MASK.\n");
+    exit(1);
+}
+
+struct {
+    const char *name;
+    DWORD value;
+} kOutputFlags[] = {
+    "ENABLE_PROCESSED_OUTPUT",          ENABLE_PROCESSED_OUTPUT,        // 0x0001
+    "ENABLE_WRAP_AT_EOL_OUTPUT",        ENABLE_WRAP_AT_EOL_OUTPUT,      // 0x0002
+    "ENABLE_VIRTUAL_TERMINAL_PROCESSING", 0x0004/*ENABLE_VIRTUAL_TERMINAL_PROCESSING*/, // 0x0004
+    "DISABLE_NEWLINE_AUTO_RETURN",      0x0008/*DISABLE_NEWLINE_AUTO_RETURN*/, // 0x0008
+    "ENABLE_LVB_GRID_WORLDWIDE",        0x0010/*ENABLE_LVB_GRID_WORLDWIDE*/, //0x0010
+};
+
+int main(int argc, char *argv[]) {
+    std::vector<std::string> args;
+    for (size_t i = 1; i < argc; ++i) {
+        args.push_back(argv[i]);
+    }
+
+    if (args.empty() || args.size() == 1 && args[0] == "info") {
+        DWORD mode = getConsoleMode();
+        printf("mode: 0x%lx\n", mode);
+        for (const auto &flag : kOutputFlags) {
+            printf("%-34s 0x%04lx %s\n", flag.name, flag.value, flag.value & mode ? "ON" : "off");
+            mode &= ~flag.value;
+        }
+        for (int i = 0; i < 32; ++i) {
+            if (mode & (1u << i)) {
+                printf("Unrecognized flag: %04x\n", (1u << i));
+            }
+        }
+        return 0;
+    }
+
+    const auto verb = args[0];
+
+    if (verb == "set") {
+        if (args.size() == 2) {
+            const DWORD newMode = parseInt(args[1]);
+            setConsoleMode(newMode);
+        } else if (args.size() == 3) {
+            const DWORD mode = parseInt(args[1]);
+            const DWORD mask = parseInt(args[2]);
+            const int newMode = (getConsoleMode() & ~mask) | (mode & mask);
+            setConsoleMode(newMode);
+        } else {
+            usage();
+        }
+    } else if (verb == "get") {
+        if (args.size() != 1) {
+            usage();
+        }
+        printf("0x%lx\n", getConsoleMode());
+    } else {
+        usage();
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/DebugClient.py b/node_modules/node-pty/deps/winpty/misc/DebugClient.py
new file mode 100644 (file)
index 0000000..cd12df8
--- /dev/null
@@ -0,0 +1,42 @@
+#!python
+# Run with native CPython.  Needs pywin32 extensions.
+
+# Copyright (c) 2011-2012 Ryan Prichard
+#
+# 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.
+
+import winerror
+import win32pipe
+import win32file
+import win32api
+import sys
+import pywintypes
+import time
+
+if len(sys.argv) != 2:
+    print("Usage: %s message" % sys.argv[0])
+    sys.exit(1)
+
+message = "[%05.3f %s]: %s" % (time.time() % 100000, sys.argv[0], sys.argv[1])
+
+win32pipe.CallNamedPipe(
+    "\\\\.\\pipe\\DebugServer",
+    message.encode(),
+    16,
+    win32pipe.NMPWAIT_WAIT_FOREVER)
diff --git a/node_modules/node-pty/deps/winpty/misc/DebugServer.py b/node_modules/node-pty/deps/winpty/misc/DebugServer.py
new file mode 100644 (file)
index 0000000..3fc068b
--- /dev/null
@@ -0,0 +1,63 @@
+#!python
+#
+# Run with native CPython.  Needs pywin32 extensions.
+
+# Copyright (c) 2011-2012 Ryan Prichard
+#
+# 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.
+
+import win32pipe
+import win32api
+import win32file
+import time
+import threading
+import sys
+
+# A message may not be larger than this size.
+MSG_SIZE=4096
+
+serverPipe = win32pipe.CreateNamedPipe(
+    "\\\\.\\pipe\\DebugServer",
+    win32pipe.PIPE_ACCESS_DUPLEX,
+    win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE,
+    win32pipe.PIPE_UNLIMITED_INSTANCES,
+    MSG_SIZE,
+    MSG_SIZE,
+    10 * 1000,
+    None)
+while True:
+    win32pipe.ConnectNamedPipe(serverPipe, None)
+    (ret, data) = win32file.ReadFile(serverPipe, MSG_SIZE)
+    print(data.decode())
+    sys.stdout.flush()
+
+    # The client uses CallNamedPipe to send its message.  CallNamedPipe waits
+    # for a reply message.  If I send a reply, however, using WriteFile, then
+    # sometimes WriteFile fails with:
+    #     pywintypes.error: (232, 'WriteFile', 'The pipe is being closed.')
+    # I can't figure out how to write a strictly correct pipe server, but if
+    # I comment out the WriteFile line, then everything seems to work.  I
+    # think the DisconnectNamedPipe call aborts the client's CallNamedPipe
+    # call normally.
+
+    try:
+        win32file.WriteFile(serverPipe, b'OK')
+    except:
+        pass
+    win32pipe.DisconnectNamedPipe(serverPipe)
diff --git a/node_modules/node-pty/deps/winpty/misc/DumpLines.py b/node_modules/node-pty/deps/winpty/misc/DumpLines.py
new file mode 100644 (file)
index 0000000..4004996
--- /dev/null
@@ -0,0 +1,5 @@
+#!/usr/bin/env python
+import sys
+
+for i in range(1, int(sys.argv[1]) + 1):
+    print i, "X" * 78
diff --git a/node_modules/node-pty/deps/winpty/misc/EnableExtendedFlags.txt b/node_modules/node-pty/deps/winpty/misc/EnableExtendedFlags.txt
new file mode 100644 (file)
index 0000000..37914da
--- /dev/null
@@ -0,0 +1,46 @@
+Note regarding ENABLE_EXTENDED_FLAGS (2016-05-30)
+
+There is a complicated interaction between the ENABLE_EXTENDED_FLAGS flag
+and the ENABLE_QUICK_EDIT_MODE and ENABLE_INSERT_MODE flags (presumably for
+backwards compatibility?).  I studied the behavior on Windows 7 and Windows
+10, with both the old and new consoles, and I didn't see any differences
+between versions.  Here's what I seemed to observe:
+
+ - The console has three flags internally:
+    - QuickEdit
+    - InsertMode
+    - ExtendedFlags
+
+ - SetConsoleMode psuedocode:
+      void SetConsoleMode(..., DWORD mode) {
+        ExtendedFlags = (mode & (ENABLE_EXTENDED_FLAGS
+                                  | ENABLE_QUICK_EDIT_MODE
+                                  | ENABLE_INSERT_MODE    )) != 0;
+        if (ExtendedFlags) {
+          QuickEdit = (mode & ENABLE_QUICK_EDIT_MODE) != 0;
+          InsertMode = (mode & ENABLE_INSERT_MODE) != 0;
+        }
+      }
+
+ - Setting QuickEdit or InsertMode from the properties dialog GUI does not
+   affect the ExtendedFlags setting -- it simply toggles the one flag.
+
+ - GetConsoleMode psuedocode:
+      GetConsoleMode(..., DWORD *result) {
+        if (ExtendedFlags) {
+          *result |= ENABLE_EXTENDED_FLAGS;
+          if (QuickEdit) { *result |= ENABLE_QUICK_EDIT_MODE; }
+          if (InsertMode) { *result |= ENABLE_INSERT_MODE; }
+        }
+      }
+
+Effectively, the ExtendedFlags flags controls whether the other two flags
+are visible/controlled by the user application.  If they aren't visible,
+though, there is no way for the user application to make them visible,
+except by overwriting their values!  Calling SetConsoleMode with just
+ENABLE_EXTENDED_FLAGS would clear the extended flags we want to read.
+
+Consequently, if a program temporarily alters the QuickEdit flag (e.g. to
+enable mouse input), it cannot restore the original values of the QuickEdit
+and InsertMode flags, UNLESS every other console program cooperates by
+keeping the ExtendedFlags flag set.
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Consolas.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Consolas.txt
new file mode 100644 (file)
index 0000000..067bd38
--- /dev/null
@@ -0,0 +1,528 @@
+==================================
+Code Page 437, Consolas font
+==================================
+
+Options: -face "Consolas" -family 0x36
+Chars: A2 A3 2014 3044 30FC 4000
+
+FontSurvey "-face \"Consolas\" -family 0x36"
+
+Windows 7
+---------
+
+Size   1: 1,3     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 1,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 2,5     BAD  (HHHHHH)
+Size   6: 3,6     BAD  (HHHHHH)
+Size   7: 3,6     BAD  (HHHHHH)
+Size   8: 4,8     BAD  (HHHHHH)
+Size   9: 4,9     BAD  (HHHHHH)
+Size  10: 5,10    BAD  (HHHHHH)
+Size  11: 5,11    BAD  (HHHHHH)
+Size  12: 6,12    BAD  (HHHHHH)
+Size  13: 6,13    BAD  (HHHHHH)
+Size  14: 7,14    BAD  (HHHHHH)
+Size  15: 7,15    BAD  (HHHHHH)
+Size  16: 8,16    BAD  (HHHHHH)
+Size  17: 8,17    BAD  (HHHHHH)
+Size  18: 8,18    BAD  (HHHHHH)
+Size  19: 9,19    BAD  (HHHHHH)
+Size  20: 9,20    BAD  (HHHHHH)
+Size  21: 10,22   BAD  (HHHHHH)
+Size  22: 10,22   BAD  (HHHHHH)
+Size  23: 11,23   BAD  (HHHHHH)
+Size  24: 11,24   BAD  (HHHHHH)
+Size  25: 12,25   BAD  (HHHHHH)
+Size  26: 12,26   BAD  (HHHHHH)
+Size  27: 13,27   BAD  (HHHHHH)
+Size  28: 13,28   BAD  (HHHHHH)
+Size  29: 14,29   BAD  (HHHHHH)
+Size  30: 14,30   BAD  (HHHHHH)
+Size  31: 15,31   BAD  (HHHHHH)
+Size  32: 15,32   BAD  (HHHHHH)
+Size  33: 15,33   BAD  (HHHHHH)
+Size  34: 16,34   BAD  (HHHHHH)
+Size  35: 16,36   BAD  (HHHHHH)
+Size  36: 17,36   BAD  (HHHHHH)
+Size  37: 17,37   BAD  (HHHHHH)
+Size  38: 18,38   BAD  (HHHHHH)
+Size  39: 18,39   BAD  (HHHHHH)
+Size  40: 19,40   BAD  (HHHHHH)
+Size  41: 19,41   BAD  (HHHHHH)
+Size  42: 20,42   BAD  (HHHHHH)
+Size  43: 20,43   BAD  (HHHHHH)
+Size  44: 21,44   BAD  (HHHHHH)
+Size  45: 21,45   BAD  (HHHHHH)
+Size  46: 22,46   BAD  (HHHHHH)
+Size  47: 22,47   BAD  (HHHHHH)
+Size  48: 23,48   BAD  (HHHHHH)
+Size  49: 23,49   BAD  (HHHHHH)
+Size  50: 23,50   BAD  (HHHHHH)
+Size  51: 24,51   BAD  (HHHHHH)
+Size  52: 24,52   BAD  (HHHHHH)
+Size  53: 25,53   BAD  (HHHHHH)
+Size  54: 25,54   BAD  (HHHHHH)
+Size  55: 26,55   BAD  (HHHHHH)
+Size  56: 26,56   BAD  (HHHHHH)
+Size  57: 27,57   BAD  (HHHHHH)
+Size  58: 27,58   BAD  (HHHHHH)
+Size  59: 28,59   BAD  (HHHHHH)
+Size  60: 28,60   BAD  (HHHHHH)
+Size  61: 29,61   BAD  (HHHHHH)
+Size  62: 29,62   BAD  (HHHHHH)
+Size  63: 30,64   BAD  (HHHHHH)
+Size  64: 30,64   BAD  (HHHHHH)
+Size  65: 31,65   BAD  (HHHHHH)
+Size  66: 31,66   BAD  (HHHHHH)
+Size  67: 31,67   BAD  (HHHHHH)
+Size  68: 32,68   BAD  (HHHHHH)
+Size  69: 32,69   BAD  (HHHHHH)
+Size  70: 33,70   BAD  (HHHHHH)
+Size  71: 33,71   BAD  (HHHHHH)
+Size  72: 34,72   BAD  (HHHHHH)
+Size  73: 34,73   BAD  (HHHHHH)
+Size  74: 35,74   BAD  (HHHHHH)
+Size  75: 35,75   BAD  (HHHHHH)
+Size  76: 36,76   BAD  (HHHHHH)
+Size  77: 36,77   BAD  (HHHHHH)
+Size  78: 37,78   BAD  (HHHHHH)
+Size  79: 37,79   BAD  (HHHHHH)
+Size  80: 38,80   BAD  (HHHHHH)
+Size  81: 38,81   BAD  (HHHHHH)
+Size  82: 39,82   BAD  (HHHHHH)
+Size  83: 39,83   BAD  (HHHHHH)
+Size  84: 39,84   BAD  (HHHHHH)
+Size  85: 40,85   BAD  (HHHHHH)
+Size  86: 40,86   BAD  (HHHHHH)
+Size  87: 41,87   BAD  (HHHHHH)
+Size  88: 41,88   BAD  (HHHHHH)
+Size  89: 42,89   BAD  (HHHHHH)
+Size  90: 42,90   BAD  (HHHHHH)
+Size  91: 43,91   BAD  (HHHHHH)
+Size  92: 43,92   BAD  (HHHHHH)
+Size  93: 44,93   BAD  (HHHHHH)
+Size  94: 44,94   BAD  (HHHHHH)
+Size  95: 45,95   BAD  (HHHHHH)
+Size  96: 45,96   BAD  (HHHHHH)
+Size  97: 46,97   BAD  (HHHHHH)
+Size  98: 46,98   BAD  (HHHHHH)
+Size  99: 46,99   BAD  (HHHHHH)
+Size 100: 47,100  BAD  (HHHHHH)
+
+Windows 8
+---------
+
+Size   1: 1,3     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 1,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 2,5     BAD  (HHHHHH)
+Size   6: 3,6     BAD  (HHHHHH)
+Size   7: 3,6     BAD  (HHHHHH)
+Size   8: 4,8     BAD  (HHHHHH)
+Size   9: 4,9     BAD  (HHHHHH)
+Size  10: 5,10    BAD  (HHHHHH)
+Size  11: 5,11    BAD  (HHHHHH)
+Size  12: 6,12    BAD  (HHHHHH)
+Size  13: 6,13    BAD  (HHHHHH)
+Size  14: 7,14    BAD  (HHHHHH)
+Size  15: 7,15    BAD  (HHHHHH)
+Size  16: 8,16    BAD  (HHHHHH)
+Size  17: 8,17    BAD  (HHHHHH)
+Size  18: 8,18    BAD  (HHHHHH)
+Size  19: 9,19    BAD  (HHHHHH)
+Size  20: 9,20    BAD  (HHHHHH)
+Size  21: 10,22   BAD  (HHHHHH)
+Size  22: 10,22   BAD  (HHHHHH)
+Size  23: 11,23   BAD  (HHHHHH)
+Size  24: 11,24   BAD  (HHHHHH)
+Size  25: 12,25   BAD  (HHHHHH)
+Size  26: 12,26   BAD  (HHHHHH)
+Size  27: 13,27   BAD  (HHHHHH)
+Size  28: 13,28   BAD  (HHHHHH)
+Size  29: 14,29   BAD  (HHHHHH)
+Size  30: 14,30   BAD  (HHHHHH)
+Size  31: 15,31   BAD  (HHHHHH)
+Size  32: 15,32   BAD  (HHHHHH)
+Size  33: 15,33   BAD  (HHHHHH)
+Size  34: 16,34   BAD  (HHHHHH)
+Size  35: 16,36   BAD  (HHHHHH)
+Size  36: 17,36   BAD  (HHHHHH)
+Size  37: 17,37   BAD  (HHHHHH)
+Size  38: 18,38   BAD  (HHHHHH)
+Size  39: 18,39   BAD  (HHHHHH)
+Size  40: 19,40   BAD  (HHHHHH)
+Size  41: 19,41   BAD  (HHHHHH)
+Size  42: 20,42   BAD  (HHHHHH)
+Size  43: 20,43   BAD  (HHHHHH)
+Size  44: 21,44   BAD  (HHHHHH)
+Size  45: 21,45   BAD  (HHHHHH)
+Size  46: 22,46   BAD  (HHHHHH)
+Size  47: 22,47   BAD  (HHHHHH)
+Size  48: 23,48   BAD  (HHHHHH)
+Size  49: 23,49   BAD  (HHHHHH)
+Size  50: 23,50   BAD  (HHHHHH)
+Size  51: 24,51   BAD  (HHHHHH)
+Size  52: 24,52   BAD  (HHHHHH)
+Size  53: 25,53   BAD  (HHHHHH)
+Size  54: 25,54   BAD  (HHHHHH)
+Size  55: 26,55   BAD  (HHHHHH)
+Size  56: 26,56   BAD  (HHHHHH)
+Size  57: 27,57   BAD  (HHHHHH)
+Size  58: 27,58   BAD  (HHHHHH)
+Size  59: 28,59   BAD  (HHHHHH)
+Size  60: 28,60   BAD  (HHHHHH)
+Size  61: 29,61   BAD  (HHHHHH)
+Size  62: 29,62   BAD  (HHHHHH)
+Size  63: 30,64   BAD  (HHHHHH)
+Size  64: 30,64   BAD  (HHHHHH)
+Size  65: 31,65   BAD  (HHHHHH)
+Size  66: 31,66   BAD  (HHHHHH)
+Size  67: 31,67   BAD  (HHHHHH)
+Size  68: 32,68   BAD  (HHHHHH)
+Size  69: 32,69   BAD  (HHHHHH)
+Size  70: 33,70   BAD  (HHHHHH)
+Size  71: 33,71   BAD  (HHHHHH)
+Size  72: 34,72   BAD  (HHHHHH)
+Size  73: 34,73   BAD  (HHHHHH)
+Size  74: 35,74   BAD  (HHHHHH)
+Size  75: 35,75   BAD  (HHHHHH)
+Size  76: 36,76   BAD  (HHHHHH)
+Size  77: 36,77   BAD  (HHHHHH)
+Size  78: 37,78   BAD  (HHHHHH)
+Size  79: 37,79   BAD  (HHHHHH)
+Size  80: 38,80   BAD  (HHHHHH)
+Size  81: 38,81   BAD  (HHHHHH)
+Size  82: 39,82   BAD  (HHHHHH)
+Size  83: 39,83   BAD  (HHHHHH)
+Size  84: 39,84   BAD  (HHHHHH)
+Size  85: 40,85   BAD  (HHHHHH)
+Size  86: 40,86   BAD  (HHHHHH)
+Size  87: 41,87   BAD  (HHHHHH)
+Size  88: 41,88   BAD  (HHHHHH)
+Size  89: 42,89   BAD  (HHHHHH)
+Size  90: 42,90   BAD  (HHHHHH)
+Size  91: 43,91   BAD  (HHHHHH)
+Size  92: 43,92   BAD  (HHHHHH)
+Size  93: 44,93   BAD  (HHHHHH)
+Size  94: 44,94   BAD  (HHHHHH)
+Size  95: 45,95   BAD  (HHHHHH)
+Size  96: 45,96   BAD  (HHHHHH)
+Size  97: 46,97   BAD  (HHHHHH)
+Size  98: 46,98   BAD  (HHHHHH)
+Size  99: 46,99   BAD  (HHHHHH)
+Size 100: 47,100  BAD  (HHHHHH)
+
+Windows 8.1
+-----------
+
+Size   1: 1,3     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 1,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 2,5     BAD  (HHHHHH)
+Size   6: 3,6     BAD  (HHHHHH)
+Size   7: 3,6     BAD  (HHHHHH)
+Size   8: 4,8     BAD  (HHHHHH)
+Size   9: 4,9     BAD  (HHHHHH)
+Size  10: 5,10    BAD  (HHHHHH)
+Size  11: 5,11    BAD  (HHHHHH)
+Size  12: 6,12    BAD  (HHHHHH)
+Size  13: 6,13    BAD  (HHHHHH)
+Size  14: 7,14    BAD  (HHHHHH)
+Size  15: 7,15    BAD  (HHHHHH)
+Size  16: 8,16    BAD  (HHHHHH)
+Size  17: 8,17    BAD  (HHHHHH)
+Size  18: 8,18    BAD  (HHHHHH)
+Size  19: 9,19    BAD  (HHHHHH)
+Size  20: 9,20    BAD  (HHHHHH)
+Size  21: 10,22   BAD  (HHHHHH)
+Size  22: 10,22   BAD  (HHHHHH)
+Size  23: 11,23   BAD  (HHHHHH)
+Size  24: 11,24   BAD  (HHHHHH)
+Size  25: 12,25   BAD  (HHHHHH)
+Size  26: 12,26   BAD  (HHHHHH)
+Size  27: 13,27   BAD  (HHHHHH)
+Size  28: 13,28   BAD  (HHHHHH)
+Size  29: 14,29   BAD  (HHHHHH)
+Size  30: 14,30   BAD  (HHHHHH)
+Size  31: 15,31   BAD  (HHHHHH)
+Size  32: 15,32   BAD  (HHHHHH)
+Size  33: 15,33   BAD  (HHHHHH)
+Size  34: 16,34   BAD  (HHHHHH)
+Size  35: 16,36   BAD  (HHHHHH)
+Size  36: 17,36   BAD  (HHHHHH)
+Size  37: 17,37   BAD  (HHHHHH)
+Size  38: 18,38   BAD  (HHHHHH)
+Size  39: 18,39   BAD  (HHHHHH)
+Size  40: 19,40   BAD  (HHHHHH)
+Size  41: 19,41   BAD  (HHHHHH)
+Size  42: 20,42   BAD  (HHHHHH)
+Size  43: 20,43   BAD  (HHHHHH)
+Size  44: 21,44   BAD  (HHHHHH)
+Size  45: 21,45   BAD  (HHHHHH)
+Size  46: 22,46   BAD  (HHHHHH)
+Size  47: 22,47   BAD  (HHHHHH)
+Size  48: 23,48   BAD  (HHHHHH)
+Size  49: 23,49   BAD  (HHHHHH)
+Size  50: 23,50   BAD  (HHHHHH)
+Size  51: 24,51   BAD  (HHHHHH)
+Size  52: 24,52   BAD  (HHHHHH)
+Size  53: 25,53   BAD  (HHHHHH)
+Size  54: 25,54   BAD  (HHHHHH)
+Size  55: 26,55   BAD  (HHHHHH)
+Size  56: 26,56   BAD  (HHHHHH)
+Size  57: 27,57   BAD  (HHHHHH)
+Size  58: 27,58   BAD  (HHHHHH)
+Size  59: 28,59   BAD  (HHHHHH)
+Size  60: 28,60   BAD  (HHHHHH)
+Size  61: 29,61   BAD  (HHHHHH)
+Size  62: 29,62   BAD  (HHHHHH)
+Size  63: 30,64   BAD  (HHHHHH)
+Size  64: 30,64   BAD  (HHHHHH)
+Size  65: 31,65   BAD  (HHHHHH)
+Size  66: 31,66   BAD  (HHHHHH)
+Size  67: 31,67   BAD  (HHHHHH)
+Size  68: 32,68   BAD  (HHHHHH)
+Size  69: 32,69   BAD  (HHHHHH)
+Size  70: 33,70   BAD  (HHHHHH)
+Size  71: 33,71   BAD  (HHHHHH)
+Size  72: 34,72   BAD  (HHHHHH)
+Size  73: 34,73   BAD  (HHHHHH)
+Size  74: 35,74   BAD  (HHHHHH)
+Size  75: 35,75   BAD  (HHHHHH)
+Size  76: 36,76   BAD  (HHHHHH)
+Size  77: 36,77   BAD  (HHHHHH)
+Size  78: 37,78   BAD  (HHHHHH)
+Size  79: 37,79   BAD  (HHHHHH)
+Size  80: 38,80   BAD  (HHHHHH)
+Size  81: 38,81   BAD  (HHHHHH)
+Size  82: 39,82   BAD  (HHHHHH)
+Size  83: 39,83   BAD  (HHHHHH)
+Size  84: 39,84   BAD  (HHHHHH)
+Size  85: 40,85   BAD  (HHHHHH)
+Size  86: 40,86   BAD  (HHHHHH)
+Size  87: 41,87   BAD  (HHHHHH)
+Size  88: 41,88   BAD  (HHHHHH)
+Size  89: 42,89   BAD  (HHHHHH)
+Size  90: 42,90   BAD  (HHHHHH)
+Size  91: 43,91   BAD  (HHHHHH)
+Size  92: 43,92   BAD  (HHHHHH)
+Size  93: 44,93   BAD  (HHHHHH)
+Size  94: 44,94   BAD  (HHHHHH)
+Size  95: 45,95   BAD  (HHHHHH)
+Size  96: 45,96   BAD  (HHHHHH)
+Size  97: 46,97   BAD  (HHHHHH)
+Size  98: 46,98   BAD  (HHHHHH)
+Size  99: 46,99   BAD  (HHHHHH)
+Size 100: 47,100  BAD  (HHHHHH)
+
+Windows 10 14342 Old Console
+----------------------------
+
+Size   1: 1,3     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 1,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 2,5     BAD  (HHHHHH)
+Size   6: 3,6     BAD  (HHHHHH)
+Size   7: 3,6     BAD  (HHHHHH)
+Size   8: 4,8     BAD  (HHHHHH)
+Size   9: 4,9     BAD  (HHHHHH)
+Size  10: 5,10    BAD  (HHHHHH)
+Size  11: 5,11    BAD  (HHHHHH)
+Size  12: 6,12    BAD  (HHHHHH)
+Size  13: 6,13    BAD  (HHHHHH)
+Size  14: 7,14    BAD  (HHHHHH)
+Size  15: 7,15    BAD  (HHHHHH)
+Size  16: 8,16    BAD  (HHHHHH)
+Size  17: 8,17    BAD  (HHHHHH)
+Size  18: 8,18    BAD  (HHHHHH)
+Size  19: 9,19    BAD  (HHHHHH)
+Size  20: 9,20    BAD  (HHHHHH)
+Size  21: 10,22   BAD  (HHHHHH)
+Size  22: 10,22   BAD  (HHHHHH)
+Size  23: 11,23   BAD  (HHHHHH)
+Size  24: 11,24   BAD  (HHHHHH)
+Size  25: 12,25   BAD  (HHHHHH)
+Size  26: 12,26   BAD  (HHHHHH)
+Size  27: 13,27   BAD  (HHHHHH)
+Size  28: 13,28   BAD  (HHHHHH)
+Size  29: 14,29   BAD  (HHHHHH)
+Size  30: 14,30   BAD  (HHHHHH)
+Size  31: 15,31   BAD  (HHHHHH)
+Size  32: 15,32   BAD  (HHHHHH)
+Size  33: 15,33   BAD  (HHHHHH)
+Size  34: 16,34   BAD  (HHHHHH)
+Size  35: 16,36   BAD  (HHHHHH)
+Size  36: 17,36   BAD  (HHHHHH)
+Size  37: 17,37   BAD  (HHHHHH)
+Size  38: 18,38   BAD  (HHHHHH)
+Size  39: 18,39   BAD  (HHHHHH)
+Size  40: 19,40   BAD  (HHHHHH)
+Size  41: 19,41   BAD  (HHHHHH)
+Size  42: 20,42   BAD  (HHHHHH)
+Size  43: 20,43   BAD  (HHHHHH)
+Size  44: 21,44   BAD  (HHHHHH)
+Size  45: 21,45   BAD  (HHHHHH)
+Size  46: 22,46   BAD  (HHHHHH)
+Size  47: 22,47   BAD  (HHHHHH)
+Size  48: 23,48   BAD  (HHHHHH)
+Size  49: 23,49   BAD  (HHHHHH)
+Size  50: 23,50   BAD  (HHHHHH)
+Size  51: 24,51   BAD  (HHHHHH)
+Size  52: 24,52   BAD  (HHHHHH)
+Size  53: 25,53   BAD  (HHHHHH)
+Size  54: 25,54   BAD  (HHHHHH)
+Size  55: 26,55   BAD  (HHHHHH)
+Size  56: 26,56   BAD  (HHHHHH)
+Size  57: 27,57   BAD  (HHHHHH)
+Size  58: 27,58   BAD  (HHHHHH)
+Size  59: 28,59   BAD  (HHHHHH)
+Size  60: 28,60   BAD  (HHHHHH)
+Size  61: 29,61   BAD  (HHHHHH)
+Size  62: 29,62   BAD  (HHHHHH)
+Size  63: 30,64   BAD  (HHHHHH)
+Size  64: 30,64   BAD  (HHHHHH)
+Size  65: 31,65   BAD  (HHHHHH)
+Size  66: 31,66   BAD  (HHHHHH)
+Size  67: 31,67   BAD  (HHHHHH)
+Size  68: 32,68   BAD  (HHHHHH)
+Size  69: 32,69   BAD  (HHHHHH)
+Size  70: 33,70   BAD  (HHHHHH)
+Size  71: 33,71   BAD  (HHHHHH)
+Size  72: 34,72   BAD  (HHHHHH)
+Size  73: 34,73   BAD  (HHHHHH)
+Size  74: 35,74   BAD  (HHHHHH)
+Size  75: 35,75   BAD  (HHHHHH)
+Size  76: 36,76   BAD  (HHHHHH)
+Size  77: 36,77   BAD  (HHHHHH)
+Size  78: 37,78   BAD  (HHHHHH)
+Size  79: 37,79   BAD  (HHHHHH)
+Size  80: 38,80   BAD  (HHHHHH)
+Size  81: 38,81   BAD  (HHHHHH)
+Size  82: 39,82   BAD  (HHHHHH)
+Size  83: 39,83   BAD  (HHHHHH)
+Size  84: 39,84   BAD  (HHHHHH)
+Size  85: 40,85   BAD  (HHHHHH)
+Size  86: 40,86   BAD  (HHHHHH)
+Size  87: 41,87   BAD  (HHHHHH)
+Size  88: 41,88   BAD  (HHHHHH)
+Size  89: 42,89   BAD  (HHHHHH)
+Size  90: 42,90   BAD  (HHHHHH)
+Size  91: 43,91   BAD  (HHHHHH)
+Size  92: 43,92   BAD  (HHHHHH)
+Size  93: 44,93   BAD  (HHHHHH)
+Size  94: 44,94   BAD  (HHHHHH)
+Size  95: 45,95   BAD  (HHHHHH)
+Size  96: 45,96   BAD  (HHHHHH)
+Size  97: 46,97   BAD  (HHHHHH)
+Size  98: 46,98   BAD  (HHHHHH)
+Size  99: 46,99   BAD  (HHHHHH)
+Size 100: 47,100  BAD  (HHHHHH)
+
+Windows 10 14342 New Console
+----------------------------
+
+Size   1: 1,1     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 1,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 2,5     BAD  (HHHHHH)
+Size   6: 3,6     BAD  (HHHHHH)
+Size   7: 3,7     BAD  (HHHHHH)
+Size   8: 4,8     BAD  (HHHHHH)
+Size   9: 4,9     BAD  (HHHHHH)
+Size  10: 5,10    BAD  (HHHHHH)
+Size  11: 5,11    BAD  (HHHHHH)
+Size  12: 6,12    BAD  (HHHHHH)
+Size  13: 6,13    BAD  (HHHHHH)
+Size  14: 7,14    BAD  (HHHHHH)
+Size  15: 7,15    BAD  (HHHHHH)
+Size  16: 8,16    BAD  (HHHHHH)
+Size  17: 8,17    BAD  (HHHHHH)
+Size  18: 8,18    BAD  (HHHHHH)
+Size  19: 9,19    BAD  (HHHHHH)
+Size  20: 9,20    BAD  (HHHHHH)
+Size  21: 10,21   BAD  (HHHHHH)
+Size  22: 10,22   BAD  (HHHHHH)
+Size  23: 11,23   BAD  (HHHHHH)
+Size  24: 11,24   BAD  (HHHHHH)
+Size  25: 12,25   BAD  (HHHHHH)
+Size  26: 12,26   BAD  (HHHHHH)
+Size  27: 13,27   BAD  (HHHHHH)
+Size  28: 13,28   BAD  (HHHHHH)
+Size  29: 14,29   BAD  (HHHHHH)
+Size  30: 14,30   BAD  (HHHHHH)
+Size  31: 15,31   BAD  (HHHHHH)
+Size  32: 15,32   BAD  (HHHHHH)
+Size  33: 15,33   BAD  (HHHHHH)
+Size  34: 16,34   BAD  (HHHHHH)
+Size  35: 16,35   BAD  (HHHHHH)
+Size  36: 17,36   BAD  (HHHHHH)
+Size  37: 17,37   BAD  (HHHHHH)
+Size  38: 18,38   BAD  (HHHHHH)
+Size  39: 18,39   BAD  (HHHHHH)
+Size  40: 19,40   BAD  (HHHHHH)
+Size  41: 19,41   BAD  (HHHHHH)
+Size  42: 20,42   BAD  (HHHHHH)
+Size  43: 20,43   BAD  (HHHHHH)
+Size  44: 21,44   BAD  (HHHHHH)
+Size  45: 21,45   BAD  (HHHHHH)
+Size  46: 22,46   BAD  (HHHHHH)
+Size  47: 22,47   BAD  (HHHHHH)
+Size  48: 23,48   BAD  (HHHHHH)
+Size  49: 23,49   BAD  (HHHHHH)
+Size  50: 23,50   BAD  (HHHHHH)
+Size  51: 24,51   BAD  (HHHHHH)
+Size  52: 24,52   BAD  (HHHHHH)
+Size  53: 25,53   BAD  (HHHHHH)
+Size  54: 25,54   BAD  (HHHHHH)
+Size  55: 26,55   BAD  (HHHHHH)
+Size  56: 26,56   BAD  (HHHHHH)
+Size  57: 27,57   BAD  (HHHHHH)
+Size  58: 27,58   BAD  (HHHHHH)
+Size  59: 28,59   BAD  (HHHHHH)
+Size  60: 28,60   BAD  (HHHHHH)
+Size  61: 29,61   BAD  (HHHHHH)
+Size  62: 29,62   BAD  (HHHHHH)
+Size  63: 30,63   BAD  (HHHHHH)
+Size  64: 30,64   BAD  (HHHHHH)
+Size  65: 31,65   BAD  (HHHHHH)
+Size  66: 31,66   BAD  (HHHHHH)
+Size  67: 31,67   BAD  (HHHHHH)
+Size  68: 32,68   BAD  (HHHHHH)
+Size  69: 32,69   BAD  (HHHHHH)
+Size  70: 33,70   BAD  (HHHHHH)
+Size  71: 33,71   BAD  (HHHHHH)
+Size  72: 34,72   BAD  (HHHHHH)
+Size  73: 34,73   BAD  (HHHHHH)
+Size  74: 35,74   BAD  (HHHHHH)
+Size  75: 35,75   BAD  (HHHHHH)
+Size  76: 36,76   BAD  (HHHHHH)
+Size  77: 36,77   BAD  (HHHHHH)
+Size  78: 37,78   BAD  (HHHHHH)
+Size  79: 37,79   BAD  (HHHHHH)
+Size  80: 38,80   BAD  (HHHHHH)
+Size  81: 38,81   BAD  (HHHHHH)
+Size  82: 39,82   BAD  (HHHHHH)
+Size  83: 39,83   BAD  (HHHHHH)
+Size  84: 39,84   BAD  (HHHHHH)
+Size  85: 40,85   BAD  (HHHHHH)
+Size  86: 40,86   BAD  (HHHHHH)
+Size  87: 41,87   BAD  (HHHHHH)
+Size  88: 41,88   BAD  (HHHHHH)
+Size  89: 42,89   BAD  (HHHHHH)
+Size  90: 42,90   BAD  (HHHHHH)
+Size  91: 43,91   BAD  (HHHHHH)
+Size  92: 43,92   BAD  (HHHHHH)
+Size  93: 44,93   BAD  (HHHHHH)
+Size  94: 44,94   BAD  (HHHHHH)
+Size  95: 45,95   BAD  (HHHHHH)
+Size  96: 45,96   BAD  (HHHHHH)
+Size  97: 46,97   BAD  (HHHHHH)
+Size  98: 46,98   BAD  (HHHHHH)
+Size  99: 46,99   BAD  (HHHHHH)
+Size 100: 47,100  BAD  (HHHHHH)
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Lucida.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP437-Lucida.txt
new file mode 100644 (file)
index 0000000..0eed93a
--- /dev/null
@@ -0,0 +1,633 @@
+==================================
+Code Page 437, Lucida Console font
+==================================
+
+Options: -face "Lucida Console" -family 0x36
+Chars: A2 A3 2014 3044 30FC 4000
+
+FontSurvey "-face \"Lucida Console\" -family 0x36"
+
+Vista
+-----
+
+Size   1: 1,2     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 2,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 3,5     BAD  (HHHHHH)
+Size   6: 4,6     BAD  (HHHHHH)
+Size   7: 4,7     BAD  (HHHHHH)
+Size   8: 5,8     BAD  (HHHHHH)
+Size   9: 5,9     BAD  (HHHHHH)
+Size  10: 6,10    BAD  (HHHHHH)
+Size  11: 7,11    BAD  (HHHHHH)
+Size  12: 7,12    BAD  (HHHHHH)
+Size  13: 8,13    BAD  (HHHHHH)
+Size  14: 8,14    BAD  (HHHHHH)
+Size  15: 9,15    BAD  (HHHHHH)
+Size  16: 10,16   BAD  (HHHHHH)
+Size  17: 10,17   BAD  (HHHHHH)
+Size  18: 11,18   BAD  (HHHHHH)
+Size  19: 11,19   BAD  (HHHHHH)
+Size  20: 12,20   BAD  (HHHHHH)
+Size  21: 13,21   BAD  (HHHHHH)
+Size  22: 13,22   BAD  (HHHHHH)
+Size  23: 14,23   BAD  (HHHHHH)
+Size  24: 14,24   BAD  (HHHHHH)
+Size  25: 15,25   BAD  (HHHHHH)
+Size  26: 16,26   BAD  (HHHHHH)
+Size  27: 16,27   BAD  (HHHHHH)
+Size  28: 17,28   BAD  (HHHHHH)
+Size  29: 17,29   BAD  (HHHHHH)
+Size  30: 18,30   BAD  (HHHHHH)
+Size  31: 19,31   BAD  (HHHHHH)
+Size  32: 19,32   BAD  (HHHHHH)
+Size  33: 20,33   BAD  (HHHHHH)
+Size  34: 20,34   BAD  (HHHHHH)
+Size  35: 21,35   BAD  (HHHHHH)
+Size  36: 22,36   BAD  (HHHHHH)
+Size  37: 22,37   BAD  (HHHHHH)
+Size  38: 23,38   BAD  (HHHHHH)
+Size  39: 23,39   BAD  (HHHHHH)
+Size  40: 24,40   BAD  (HHHHHH)
+Size  41: 25,41   BAD  (HHHHHH)
+Size  42: 25,42   BAD  (HHHHHH)
+Size  43: 26,43   BAD  (HHHHHH)
+Size  44: 27,44   BAD  (HHHHHH)
+Size  45: 27,45   BAD  (HHHHHH)
+Size  46: 28,46   BAD  (HHHHHH)
+Size  47: 28,47   BAD  (HHHHHH)
+Size  48: 29,48   BAD  (HHHHHH)
+Size  49: 30,49   BAD  (HHHHHH)
+Size  50: 30,50   BAD  (HHHHHH)
+Size  51: 31,51   BAD  (HHHHHH)
+Size  52: 31,52   BAD  (HHHHHH)
+Size  53: 32,53   BAD  (HHHHHH)
+Size  54: 33,54   BAD  (HHHHHH)
+Size  55: 33,55   BAD  (HHHHHH)
+Size  56: 34,56   BAD  (HHHHHH)
+Size  57: 34,57   BAD  (HHHHHH)
+Size  58: 35,58   BAD  (HHHHHH)
+Size  59: 36,59   BAD  (HHHHHH)
+Size  60: 36,60   BAD  (HHHHHH)
+Size  61: 37,61   BAD  (HHHHHH)
+Size  62: 37,62   BAD  (HHHHHH)
+Size  63: 38,63   BAD  (HHHHHH)
+Size  64: 39,65   BAD  (HHHHHH)
+Size  65: 39,65   BAD  (HHHHHH)
+Size  66: 40,66   BAD  (HHHHHH)
+Size  67: 40,67   BAD  (HHHHHH)
+Size  68: 41,68   BAD  (HHHHHH)
+Size  69: 42,69   BAD  (HHHHHH)
+Size  70: 42,70   BAD  (HHHHHH)
+Size  71: 43,71   BAD  (HHHHHH)
+Size  72: 43,72   BAD  (HHHHHH)
+Size  73: 44,73   BAD  (HHHHHH)
+Size  74: 45,74   BAD  (HHHHHH)
+Size  75: 45,75   BAD  (HHHHHH)
+Size  76: 46,76   BAD  (HHHHHH)
+Size  77: 46,77   BAD  (HHHHHH)
+Size  78: 47,78   BAD  (HHHHHH)
+Size  79: 48,79   BAD  (HHHHHH)
+Size  80: 48,80   BAD  (HHHHHH)
+Size  81: 49,81   BAD  (HHHHHH)
+Size  82: 49,82   BAD  (HHHHHH)
+Size  83: 50,83   BAD  (HHHHHH)
+Size  84: 51,84   BAD  (HHHHHH)
+Size  85: 51,85   BAD  (HHHHHH)
+Size  86: 52,86   BAD  (HHHHHH)
+Size  87: 52,87   BAD  (HHHHHH)
+Size  88: 53,88   BAD  (HHHHHH)
+Size  89: 54,89   BAD  (HHHHHH)
+Size  90: 54,90   BAD  (HHHHHH)
+Size  91: 55,91   BAD  (HHHHHH)
+Size  92: 55,92   BAD  (HHHHHH)
+Size  93: 56,93   BAD  (HHHHHH)
+Size  94: 57,94   BAD  (HHHHHH)
+Size  95: 57,95   BAD  (HHHHHH)
+Size  96: 58,96   BAD  (HHHHHH)
+Size  97: 58,97   BAD  (HHHHHH)
+Size  98: 59,98   BAD  (HHHHHH)
+Size  99: 60,99   BAD  (HHHHHH)
+Size 100: 60,100  BAD  (HHHHHH)
+
+
+Windows 7
+---------
+
+Size   1: 1,2     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 2,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 3,5     BAD  (HHHHHH)
+Size   6: 4,6     BAD  (HHHHHH)
+Size   7: 4,7     BAD  (HHHHHH)
+Size   8: 5,8     BAD  (HHHHHH)
+Size   9: 5,9     BAD  (HHHHHH)
+Size  10: 6,10    BAD  (HHHHHH)
+Size  11: 7,11    BAD  (HHHHHH)
+Size  12: 7,12    BAD  (HHHHHH)
+Size  13: 8,13    BAD  (HHHHHH)
+Size  14: 8,14    BAD  (HHHHHH)
+Size  15: 9,15    BAD  (HHHHHH)
+Size  16: 10,16   BAD  (HHHHHH)
+Size  17: 10,17   BAD  (HHHHHH)
+Size  18: 11,18   BAD  (HHHHHH)
+Size  19: 11,19   BAD  (HHHHHH)
+Size  20: 12,20   BAD  (HHHHHH)
+Size  21: 13,21   BAD  (HHHHHH)
+Size  22: 13,22   BAD  (HHHHHH)
+Size  23: 14,23   BAD  (HHHHHH)
+Size  24: 14,24   BAD  (HHHHHH)
+Size  25: 15,25   BAD  (HHHHHH)
+Size  26: 16,26   BAD  (HHHHHH)
+Size  27: 16,27   BAD  (HHHHHH)
+Size  28: 17,28   BAD  (HHHHHH)
+Size  29: 17,29   BAD  (HHHHHH)
+Size  30: 18,30   BAD  (HHHHHH)
+Size  31: 19,31   BAD  (HHHHHH)
+Size  32: 19,32   BAD  (HHHHHH)
+Size  33: 20,33   BAD  (HHHHHH)
+Size  34: 20,34   BAD  (HHHHHH)
+Size  35: 21,35   BAD  (HHHHHH)
+Size  36: 22,36   BAD  (HHHHHH)
+Size  37: 22,37   BAD  (HHHHHH)
+Size  38: 23,38   BAD  (HHHHHH)
+Size  39: 23,39   BAD  (HHHHHH)
+Size  40: 24,40   BAD  (HHHHHH)
+Size  41: 25,41   BAD  (HHHHHH)
+Size  42: 25,42   BAD  (HHHHHH)
+Size  43: 26,43   BAD  (HHHHHH)
+Size  44: 27,44   BAD  (HHHHHH)
+Size  45: 27,45   BAD  (HHHHHH)
+Size  46: 28,46   BAD  (HHHHHH)
+Size  47: 28,47   BAD  (HHHHHH)
+Size  48: 29,48   BAD  (HHHHHH)
+Size  49: 30,49   BAD  (HHHHHH)
+Size  50: 30,50   BAD  (HHHHHH)
+Size  51: 31,51   BAD  (HHHHHH)
+Size  52: 31,52   BAD  (HHHHHH)
+Size  53: 32,53   BAD  (HHHHHH)
+Size  54: 33,54   BAD  (HHHHHH)
+Size  55: 33,55   BAD  (HHHHHH)
+Size  56: 34,56   BAD  (HHHHHH)
+Size  57: 34,57   BAD  (HHHHHH)
+Size  58: 35,58   BAD  (HHHHHH)
+Size  59: 36,59   BAD  (HHHHHH)
+Size  60: 36,60   BAD  (HHHHHH)
+Size  61: 37,61   BAD  (HHHHHH)
+Size  62: 37,62   BAD  (HHHHHH)
+Size  63: 38,63   BAD  (HHHHHH)
+Size  64: 39,65   BAD  (HHHHHH)
+Size  65: 39,65   BAD  (HHHHHH)
+Size  66: 40,66   BAD  (HHHHHH)
+Size  67: 40,67   BAD  (HHHHHH)
+Size  68: 41,68   BAD  (HHHHHH)
+Size  69: 42,69   BAD  (HHHHHH)
+Size  70: 42,70   BAD  (HHHHHH)
+Size  71: 43,71   BAD  (HHHHHH)
+Size  72: 43,72   BAD  (HHHHHH)
+Size  73: 44,73   BAD  (HHHHHH)
+Size  74: 45,74   BAD  (HHHHHH)
+Size  75: 45,75   BAD  (HHHHHH)
+Size  76: 46,76   BAD  (HHHHHH)
+Size  77: 46,77   BAD  (HHHHHH)
+Size  78: 47,78   BAD  (HHHHHH)
+Size  79: 48,79   BAD  (HHHHHH)
+Size  80: 48,80   BAD  (HHHHHH)
+Size  81: 49,81   BAD  (HHHHHH)
+Size  82: 49,82   BAD  (HHHHHH)
+Size  83: 50,83   BAD  (HHHHHH)
+Size  84: 51,84   BAD  (HHHHHH)
+Size  85: 51,85   BAD  (HHHHHH)
+Size  86: 52,86   BAD  (HHHHHH)
+Size  87: 52,87   BAD  (HHHHHH)
+Size  88: 53,88   BAD  (HHHHHH)
+Size  89: 54,89   BAD  (HHHHHH)
+Size  90: 54,90   BAD  (HHHHHH)
+Size  91: 55,91   BAD  (HHHHHH)
+Size  92: 55,92   BAD  (HHHHHH)
+Size  93: 56,93   BAD  (HHHHHH)
+Size  94: 57,94   BAD  (HHHHHH)
+Size  95: 57,95   BAD  (HHHHHH)
+Size  96: 58,96   BAD  (HHHHHH)
+Size  97: 58,97   BAD  (HHHHHH)
+Size  98: 59,98   BAD  (HHHHHH)
+Size  99: 60,99   BAD  (HHHHHH)
+Size 100: 60,100  BAD  (HHHHHH)
+
+Windows 8
+---------
+
+Size   1: 1,2     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 2,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 3,5     BAD  (HHHHHH)
+Size   6: 4,6     BAD  (HHHHHH)
+Size   7: 4,7     BAD  (HHHHHH)
+Size   8: 5,8     BAD  (HHHHHH)
+Size   9: 5,9     BAD  (HHHHHH)
+Size  10: 6,10    BAD  (HHHHHH)
+Size  11: 7,11    BAD  (HHHHHH)
+Size  12: 7,12    BAD  (HHHHHH)
+Size  13: 8,13    BAD  (HHHHHH)
+Size  14: 8,14    BAD  (HHHHHH)
+Size  15: 9,15    BAD  (HHHHHH)
+Size  16: 10,16   BAD  (HHHHHH)
+Size  17: 10,17   BAD  (HHHHHH)
+Size  18: 11,18   BAD  (HHHHHH)
+Size  19: 11,19   BAD  (HHHHHH)
+Size  20: 12,20   BAD  (HHHHHH)
+Size  21: 13,21   BAD  (HHHHHH)
+Size  22: 13,22   BAD  (HHHHHH)
+Size  23: 14,23   BAD  (HHHHHH)
+Size  24: 14,24   BAD  (HHHHHH)
+Size  25: 15,25   BAD  (HHHHHH)
+Size  26: 16,26   BAD  (HHHHHH)
+Size  27: 16,27   BAD  (HHHHHH)
+Size  28: 17,28   BAD  (HHHHHH)
+Size  29: 17,29   BAD  (HHHHHH)
+Size  30: 18,30   BAD  (HHHHHH)
+Size  31: 19,31   BAD  (HHHHHH)
+Size  32: 19,32   BAD  (HHHHHH)
+Size  33: 20,33   BAD  (HHHHHH)
+Size  34: 20,34   BAD  (HHHHHH)
+Size  35: 21,35   BAD  (HHHHHH)
+Size  36: 22,36   BAD  (HHHHHH)
+Size  37: 22,37   BAD  (HHHHHH)
+Size  38: 23,38   BAD  (HHHHHH)
+Size  39: 23,39   BAD  (HHHHHH)
+Size  40: 24,40   BAD  (HHHHHH)
+Size  41: 25,41   BAD  (HHHHHH)
+Size  42: 25,42   BAD  (HHHHHH)
+Size  43: 26,43   BAD  (HHHHHH)
+Size  44: 27,44   BAD  (HHHHHH)
+Size  45: 27,45   BAD  (HHHHHH)
+Size  46: 28,46   BAD  (HHHHHH)
+Size  47: 28,47   BAD  (HHHHHH)
+Size  48: 29,48   BAD  (HHHHHH)
+Size  49: 30,49   BAD  (HHHHHH)
+Size  50: 30,50   BAD  (HHHHHH)
+Size  51: 31,51   BAD  (HHHHHH)
+Size  52: 31,52   BAD  (HHHHHH)
+Size  53: 32,53   BAD  (HHHHHH)
+Size  54: 33,54   BAD  (HHHHHH)
+Size  55: 33,55   BAD  (HHHHHH)
+Size  56: 34,56   BAD  (HHHHHH)
+Size  57: 34,57   BAD  (HHHHHH)
+Size  58: 35,58   BAD  (HHHHHH)
+Size  59: 36,59   BAD  (HHHHHH)
+Size  60: 36,60   BAD  (HHHHHH)
+Size  61: 37,61   BAD  (HHHHHH)
+Size  62: 37,62   BAD  (HHHHHH)
+Size  63: 38,63   BAD  (HHHHHH)
+Size  64: 39,65   BAD  (HHHHHH)
+Size  65: 39,65   BAD  (HHHHHH)
+Size  66: 40,66   BAD  (HHHHHH)
+Size  67: 40,67   BAD  (HHHHHH)
+Size  68: 41,68   BAD  (HHHHHH)
+Size  69: 42,69   BAD  (HHHHHH)
+Size  70: 42,70   BAD  (HHHHHH)
+Size  71: 43,71   BAD  (HHHHHH)
+Size  72: 43,72   BAD  (HHHHHH)
+Size  73: 44,73   BAD  (HHHHHH)
+Size  74: 45,74   BAD  (HHHHHH)
+Size  75: 45,75   BAD  (HHHHHH)
+Size  76: 46,76   BAD  (HHHHHH)
+Size  77: 46,77   BAD  (HHHHHH)
+Size  78: 47,78   BAD  (HHHHHH)
+Size  79: 48,79   BAD  (HHHHHH)
+Size  80: 48,80   BAD  (HHHHHH)
+Size  81: 49,81   BAD  (HHHHHH)
+Size  82: 49,82   BAD  (HHHHHH)
+Size  83: 50,83   BAD  (HHHHHH)
+Size  84: 51,84   BAD  (HHHHHH)
+Size  85: 51,85   BAD  (HHHHHH)
+Size  86: 52,86   BAD  (HHHHHH)
+Size  87: 52,87   BAD  (HHHHHH)
+Size  88: 53,88   BAD  (HHHHHH)
+Size  89: 54,89   BAD  (HHHHHH)
+Size  90: 54,90   BAD  (HHHHHH)
+Size  91: 55,91   BAD  (HHHHHH)
+Size  92: 55,92   BAD  (HHHHHH)
+Size  93: 56,93   BAD  (HHHHHH)
+Size  94: 57,94   BAD  (HHHHHH)
+Size  95: 57,95   BAD  (HHHHHH)
+Size  96: 58,96   BAD  (HHHHHH)
+Size  97: 58,97   BAD  (HHHHHH)
+Size  98: 59,98   BAD  (HHHHHH)
+Size  99: 60,99   BAD  (HHHHHH)
+Size 100: 60,100  BAD  (HHHHHH)
+
+Windows 8.1
+-----------
+
+Size   1: 1,2     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 2,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 3,5     BAD  (HHHHHH)
+Size   6: 4,6     BAD  (HHHHHH)
+Size   7: 4,7     BAD  (HHHHHH)
+Size   8: 5,8     BAD  (HHHHHH)
+Size   9: 5,9     BAD  (HHHHHH)
+Size  10: 6,10    BAD  (HHHHHH)
+Size  11: 7,11    BAD  (HHHHHH)
+Size  12: 7,12    BAD  (HHHHHH)
+Size  13: 8,13    BAD  (HHHHHH)
+Size  14: 8,14    BAD  (HHHHHH)
+Size  15: 9,15    BAD  (HHHHHH)
+Size  16: 10,16   BAD  (HHHHHH)
+Size  17: 10,17   BAD  (HHHHHH)
+Size  18: 11,18   BAD  (HHHHHH)
+Size  19: 11,19   BAD  (HHHHHH)
+Size  20: 12,20   BAD  (HHHHHH)
+Size  21: 13,21   BAD  (HHHHHH)
+Size  22: 13,22   BAD  (HHHHHH)
+Size  23: 14,23   BAD  (HHHHHH)
+Size  24: 14,24   BAD  (HHHHHH)
+Size  25: 15,25   BAD  (HHHHHH)
+Size  26: 16,26   BAD  (HHHHHH)
+Size  27: 16,27   BAD  (HHHHHH)
+Size  28: 17,28   BAD  (HHHHHH)
+Size  29: 17,29   BAD  (HHHHHH)
+Size  30: 18,30   BAD  (HHHHHH)
+Size  31: 19,31   BAD  (HHHHHH)
+Size  32: 19,32   BAD  (HHHHHH)
+Size  33: 20,33   BAD  (HHHHHH)
+Size  34: 20,34   BAD  (HHHHHH)
+Size  35: 21,35   BAD  (HHHHHH)
+Size  36: 22,36   BAD  (HHHHHH)
+Size  37: 22,37   BAD  (HHHHHH)
+Size  38: 23,38   BAD  (HHHHHH)
+Size  39: 23,39   BAD  (HHHHHH)
+Size  40: 24,40   BAD  (HHHHHH)
+Size  41: 25,41   BAD  (HHHHHH)
+Size  42: 25,42   BAD  (HHHHHH)
+Size  43: 26,43   BAD  (HHHHHH)
+Size  44: 27,44   BAD  (HHHHHH)
+Size  45: 27,45   BAD  (HHHHHH)
+Size  46: 28,46   BAD  (HHHHHH)
+Size  47: 28,47   BAD  (HHHHHH)
+Size  48: 29,48   BAD  (HHHHHH)
+Size  49: 30,49   BAD  (HHHHHH)
+Size  50: 30,50   BAD  (HHHHHH)
+Size  51: 31,51   BAD  (HHHHHH)
+Size  52: 31,52   BAD  (HHHHHH)
+Size  53: 32,53   BAD  (HHHHHH)
+Size  54: 33,54   BAD  (HHHHHH)
+Size  55: 33,55   BAD  (HHHHHH)
+Size  56: 34,56   BAD  (HHHHHH)
+Size  57: 34,57   BAD  (HHHHHH)
+Size  58: 35,58   BAD  (HHHHHH)
+Size  59: 36,59   BAD  (HHHHHH)
+Size  60: 36,60   BAD  (HHHHHH)
+Size  61: 37,61   BAD  (HHHHHH)
+Size  62: 37,62   BAD  (HHHHHH)
+Size  63: 38,63   BAD  (HHHHHH)
+Size  64: 39,65   BAD  (HHHHHH)
+Size  65: 39,65   BAD  (HHHHHH)
+Size  66: 40,66   BAD  (HHHHHH)
+Size  67: 40,67   BAD  (HHHHHH)
+Size  68: 41,68   BAD  (HHHHHH)
+Size  69: 42,69   BAD  (HHHHHH)
+Size  70: 42,70   BAD  (HHHHHH)
+Size  71: 43,71   BAD  (HHHHHH)
+Size  72: 43,72   BAD  (HHHHHH)
+Size  73: 44,73   BAD  (HHHHHH)
+Size  74: 45,74   BAD  (HHHHHH)
+Size  75: 45,75   BAD  (HHHHHH)
+Size  76: 46,76   BAD  (HHHHHH)
+Size  77: 46,77   BAD  (HHHHHH)
+Size  78: 47,78   BAD  (HHHHHH)
+Size  79: 48,79   BAD  (HHHHHH)
+Size  80: 48,80   BAD  (HHHHHH)
+Size  81: 49,81   BAD  (HHHHHH)
+Size  82: 49,82   BAD  (HHHHHH)
+Size  83: 50,83   BAD  (HHHHHH)
+Size  84: 51,84   BAD  (HHHHHH)
+Size  85: 51,85   BAD  (HHHHHH)
+Size  86: 52,86   BAD  (HHHHHH)
+Size  87: 52,87   BAD  (HHHHHH)
+Size  88: 53,88   BAD  (HHHHHH)
+Size  89: 54,89   BAD  (HHHHHH)
+Size  90: 54,90   BAD  (HHHHHH)
+Size  91: 55,91   BAD  (HHHHHH)
+Size  92: 55,92   BAD  (HHHHHH)
+Size  93: 56,93   BAD  (HHHHHH)
+Size  94: 57,94   BAD  (HHHHHH)
+Size  95: 57,95   BAD  (HHHHHH)
+Size  96: 58,96   BAD  (HHHHHH)
+Size  97: 58,97   BAD  (HHHHHH)
+Size  98: 59,98   BAD  (HHHHHH)
+Size  99: 60,99   BAD  (HHHHHH)
+Size 100: 60,100  BAD  (HHHHHH)
+
+Windows 10 14342 Old Console
+----------------------------
+
+Size   1: 1,2     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 2,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 3,5     BAD  (HHHHHH)
+Size   6: 4,6     BAD  (HHHHHH)
+Size   7: 4,7     BAD  (HHHHHH)
+Size   8: 5,8     BAD  (HHHHHH)
+Size   9: 5,9     BAD  (HHHHHH)
+Size  10: 6,10    BAD  (HHHHHH)
+Size  11: 7,11    BAD  (HHHHHH)
+Size  12: 7,12    BAD  (HHHHHH)
+Size  13: 8,13    BAD  (HHHHHH)
+Size  14: 8,14    BAD  (HHHHHH)
+Size  15: 9,15    BAD  (HHHHHH)
+Size  16: 10,16   BAD  (HHHHHH)
+Size  17: 10,17   BAD  (HHHHHH)
+Size  18: 11,18   BAD  (HHHHHH)
+Size  19: 11,19   BAD  (HHHHHH)
+Size  20: 12,20   BAD  (HHHHHH)
+Size  21: 13,21   BAD  (HHHHHH)
+Size  22: 13,22   BAD  (HHHHHH)
+Size  23: 14,23   BAD  (HHHHHH)
+Size  24: 14,24   BAD  (HHHHHH)
+Size  25: 15,25   BAD  (HHHHHH)
+Size  26: 16,26   BAD  (HHHHHH)
+Size  27: 16,27   BAD  (HHHHHH)
+Size  28: 17,28   BAD  (HHHHHH)
+Size  29: 17,29   BAD  (HHHHHH)
+Size  30: 18,30   BAD  (HHHHHH)
+Size  31: 19,31   BAD  (HHHHHH)
+Size  32: 19,32   BAD  (HHHHHH)
+Size  33: 20,33   BAD  (HHHHHH)
+Size  34: 20,34   BAD  (HHHHHH)
+Size  35: 21,35   BAD  (HHHHHH)
+Size  36: 22,36   BAD  (HHHHHH)
+Size  37: 22,37   BAD  (HHHHHH)
+Size  38: 23,38   BAD  (HHHHHH)
+Size  39: 23,39   BAD  (HHHHHH)
+Size  40: 24,40   BAD  (HHHHHH)
+Size  41: 25,41   BAD  (HHHHHH)
+Size  42: 25,42   BAD  (HHHHHH)
+Size  43: 26,43   BAD  (HHHHHH)
+Size  44: 27,44   BAD  (HHHHHH)
+Size  45: 27,45   BAD  (HHHHHH)
+Size  46: 28,46   BAD  (HHHHHH)
+Size  47: 28,47   BAD  (HHHHHH)
+Size  48: 29,48   BAD  (HHHHHH)
+Size  49: 30,49   BAD  (HHHHHH)
+Size  50: 30,50   BAD  (HHHHHH)
+Size  51: 31,51   BAD  (HHHHHH)
+Size  52: 31,52   BAD  (HHHHHH)
+Size  53: 32,53   BAD  (HHHHHH)
+Size  54: 33,54   BAD  (HHHHHH)
+Size  55: 33,55   BAD  (HHHHHH)
+Size  56: 34,56   BAD  (HHHHHH)
+Size  57: 34,57   BAD  (HHHHHH)
+Size  58: 35,58   BAD  (HHHHHH)
+Size  59: 36,59   BAD  (HHHHHH)
+Size  60: 36,60   BAD  (HHHHHH)
+Size  61: 37,61   BAD  (HHHHHH)
+Size  62: 37,62   BAD  (HHHHHH)
+Size  63: 38,63   BAD  (HHHHHH)
+Size  64: 39,65   BAD  (HHHHHH)
+Size  65: 39,65   BAD  (HHHHHH)
+Size  66: 40,66   BAD  (HHHHHH)
+Size  67: 40,67   BAD  (HHHHHH)
+Size  68: 41,68   BAD  (HHHHHH)
+Size  69: 42,69   BAD  (HHHHHH)
+Size  70: 42,70   BAD  (HHHHHH)
+Size  71: 43,71   BAD  (HHHHHH)
+Size  72: 43,72   BAD  (HHHHHH)
+Size  73: 44,73   BAD  (HHHHHH)
+Size  74: 45,74   BAD  (HHHHHH)
+Size  75: 45,75   BAD  (HHHHHH)
+Size  76: 46,76   BAD  (HHHHHH)
+Size  77: 46,77   BAD  (HHHHHH)
+Size  78: 47,78   BAD  (HHHHHH)
+Size  79: 48,79   BAD  (HHHHHH)
+Size  80: 48,80   BAD  (HHHHHH)
+Size  81: 49,81   BAD  (HHHHHH)
+Size  82: 49,82   BAD  (HHHHHH)
+Size  83: 50,83   BAD  (HHHHHH)
+Size  84: 51,84   BAD  (HHHHHH)
+Size  85: 51,85   BAD  (HHHHHH)
+Size  86: 52,86   BAD  (HHHHHH)
+Size  87: 52,87   BAD  (HHHHHH)
+Size  88: 53,88   BAD  (HHHHHH)
+Size  89: 54,89   BAD  (HHHHHH)
+Size  90: 54,90   BAD  (HHHHHH)
+Size  91: 55,91   BAD  (HHHHHH)
+Size  92: 55,92   BAD  (HHHHHH)
+Size  93: 56,93   BAD  (HHHHHH)
+Size  94: 57,94   BAD  (HHHHHH)
+Size  95: 57,95   BAD  (HHHHHH)
+Size  96: 58,96   BAD  (HHHHHH)
+Size  97: 58,97   BAD  (HHHHHH)
+Size  98: 59,98   BAD  (HHHHHH)
+Size  99: 60,99   BAD  (HHHHHH)
+Size 100: 60,100  BAD  (HHHHHH)
+
+Windows 10 14342 New Console
+----------------------------
+
+Size   1: 1,1     BAD  (HHHHHH)
+Size   2: 1,2     BAD  (HHHHHH)
+Size   3: 2,3     BAD  (HHHHHH)
+Size   4: 2,4     BAD  (HHHHHH)
+Size   5: 3,5     BAD  (HHHHHH)
+Size   6: 4,6     BAD  (HHHHHH)
+Size   7: 4,7     BAD  (HHHHHH)
+Size   8: 5,8     BAD  (HHHHHH)
+Size   9: 5,9     BAD  (HHHHHH)
+Size  10: 6,10    BAD  (HHHHHH)
+Size  11: 7,11    BAD  (HHHHHH)
+Size  12: 7,12    BAD  (HHHHHH)
+Size  13: 8,13    BAD  (HHHHHH)
+Size  14: 8,14    BAD  (HHHHHH)
+Size  15: 9,15    BAD  (HHHHHH)
+Size  16: 10,16   BAD  (HHHHHH)
+Size  17: 10,17   BAD  (HHHHHH)
+Size  18: 11,18   BAD  (HHHHHH)
+Size  19: 11,19   BAD  (HHHHHH)
+Size  20: 12,20   BAD  (HHHHHH)
+Size  21: 13,21   BAD  (HHHHHH)
+Size  22: 13,22   BAD  (HHHHHH)
+Size  23: 14,23   BAD  (HHHHHH)
+Size  24: 14,24   BAD  (HHHHHH)
+Size  25: 15,25   BAD  (HHHHHH)
+Size  26: 16,26   BAD  (HHHHHH)
+Size  27: 16,27   BAD  (HHHHHH)
+Size  28: 17,28   BAD  (HHHHHH)
+Size  29: 17,29   BAD  (HHHHHH)
+Size  30: 18,30   BAD  (HHHHHH)
+Size  31: 19,31   BAD  (HHHHHH)
+Size  32: 19,32   BAD  (HHHHHH)
+Size  33: 20,33   BAD  (HHHHHH)
+Size  34: 20,34   BAD  (HHHHHH)
+Size  35: 21,35   BAD  (HHHHHH)
+Size  36: 22,36   BAD  (HHHHHH)
+Size  37: 22,37   BAD  (HHHHHH)
+Size  38: 23,38   BAD  (HHHHHH)
+Size  39: 23,39   BAD  (HHHHHH)
+Size  40: 24,40   BAD  (HHHHHH)
+Size  41: 25,41   BAD  (HHHHHH)
+Size  42: 25,42   BAD  (HHHHHH)
+Size  43: 26,43   BAD  (HHHHHH)
+Size  44: 27,44   BAD  (HHHHHH)
+Size  45: 27,45   BAD  (HHHHHH)
+Size  46: 28,46   BAD  (HHHHHH)
+Size  47: 28,47   BAD  (HHHHHH)
+Size  48: 29,48   BAD  (HHHHHH)
+Size  49: 30,49   BAD  (HHHHHH)
+Size  50: 30,50   BAD  (HHHHHH)
+Size  51: 31,51   BAD  (HHHHHH)
+Size  52: 31,52   BAD  (HHHHHH)
+Size  53: 32,53   BAD  (HHHHHH)
+Size  54: 33,54   BAD  (HHHHHH)
+Size  55: 33,55   BAD  (HHHHHH)
+Size  56: 34,56   BAD  (HHHHHH)
+Size  57: 34,57   BAD  (HHHHHH)
+Size  58: 35,58   BAD  (HHHHHH)
+Size  59: 36,59   BAD  (HHHHHH)
+Size  60: 36,60   BAD  (HHHHHH)
+Size  61: 37,61   BAD  (HHHHHH)
+Size  62: 37,62   BAD  (HHHHHH)
+Size  63: 38,63   BAD  (HHHHHH)
+Size  64: 39,64   BAD  (HHHHHH)
+Size  65: 39,65   BAD  (HHHHHH)
+Size  66: 40,66   BAD  (HHHHHH)
+Size  67: 40,67   BAD  (HHHHHH)
+Size  68: 41,68   BAD  (HHHHHH)
+Size  69: 42,69   BAD  (HHHHHH)
+Size  70: 42,70   BAD  (HHHHHH)
+Size  71: 43,71   BAD  (HHHHHH)
+Size  72: 43,72   BAD  (HHHHHH)
+Size  73: 44,73   BAD  (HHHHHH)
+Size  74: 45,74   BAD  (HHHHHH)
+Size  75: 45,75   BAD  (HHHHHH)
+Size  76: 46,76   BAD  (HHHHHH)
+Size  77: 46,77   BAD  (HHHHHH)
+Size  78: 47,78   BAD  (HHHHHH)
+Size  79: 48,79   BAD  (HHHHHH)
+Size  80: 48,80   BAD  (HHHHHH)
+Size  81: 49,81   BAD  (HHHHHH)
+Size  82: 49,82   BAD  (HHHHHH)
+Size  83: 50,83   BAD  (HHHHHH)
+Size  84: 51,84   BAD  (HHHHHH)
+Size  85: 51,85   BAD  (HHHHHH)
+Size  86: 52,86   BAD  (HHHHHH)
+Size  87: 52,87   BAD  (HHHHHH)
+Size  88: 53,88   BAD  (HHHHHH)
+Size  89: 54,89   BAD  (HHHHHH)
+Size  90: 54,90   BAD  (HHHHHH)
+Size  91: 55,91   BAD  (HHHHHH)
+Size  92: 55,92   BAD  (HHHHHH)
+Size  93: 56,93   BAD  (HHHHHH)
+Size  94: 57,94   BAD  (HHHHHH)
+Size  95: 57,95   BAD  (HHHHHH)
+Size  96: 58,96   BAD  (HHHHHH)
+Size  97: 58,97   BAD  (HHHHHH)
+Size  98: 59,98   BAD  (HHHHHH)
+Size  99: 60,99   BAD  (HHHHHH)
+Size 100: 60,100  BAD  (HHHHHH)
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP932.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP932.txt
new file mode 100644 (file)
index 0000000..ed3637e
--- /dev/null
@@ -0,0 +1,630 @@
+=======================================
+Code Page 932, Japanese, MS Gothic font
+=======================================
+
+Options: -face-gothic -family 0x36
+Chars: A2 A3 2014 3044 30FC 4000
+
+Vista
+-----
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,4     OK   (HHHFFF)
+Size   5: 3,5     OK   (HHHFFF)
+Size   6: 3,6     OK   (HHHFFF)
+Size   7: 4,7     OK   (HHHFFF)
+Size   8: 4,8     OK   (HHHFFF)
+Size   9: 5,9     OK   (HHHFFF)
+Size  10: 5,10    OK   (HHHFFF)
+Size  11: 6,11    OK   (HHHFFF)
+Size  12: 6,12    OK   (HHHFFF)
+Size  13: 7,13    OK   (HHHFFF)
+Size  14: 7,14    BAD  (HHHFHH)
+Size  15: 8,15    OK   (HHHFFF)
+Size  16: 8,16    BAD  (HHHFHH)
+Size  17: 9,17    OK   (HHHFFF)
+Size  18: 9,18    BAD  (HHHFHH)
+Size  19: 10,19   OK   (HHHFFF)
+Size  20: 10,20   BAD  (HHHFHH)
+Size  21: 11,21   OK   (HHHFFF)
+Size  22: 11,22   BAD  (HHHFHH)
+Size  23: 12,23   BAD  (HHHFHH)
+Size  24: 12,24   BAD  (HHHFHH)
+Size  25: 13,25   BAD  (HHHFHH)
+Size  26: 13,26   BAD  (HHHFHH)
+Size  27: 14,27   BAD  (HHHFHH)
+Size  28: 14,28   BAD  (HHHFHH)
+Size  29: 15,29   BAD  (HHHFHH)
+Size  30: 15,30   BAD  (HHHFHH)
+Size  31: 16,31   BAD  (HHHFHH)
+Size  32: 16,33   BAD  (HHHFHH)
+Size  33: 17,33   BAD  (HHHFHH)
+Size  34: 17,34   BAD  (HHHFHH)
+Size  35: 18,35   BAD  (HHHFHH)
+Size  36: 18,36   BAD  (HHHFHH)
+Size  37: 19,37   BAD  (HHHFHH)
+Size  38: 19,38   BAD  (HHHFHH)
+Size  39: 20,39   BAD  (HHHFHH)
+Size  40: 20,40   BAD  (HHHFHH)
+Size  41: 21,41   BAD  (HHHFHH)
+Size  42: 21,42   BAD  (HHHFHH)
+Size  43: 22,43   BAD  (HHHFHH)
+Size  44: 22,44   BAD  (HHHFHH)
+Size  45: 23,45   BAD  (HHHFHH)
+Size  46: 23,46   BAD  (HHHFHH)
+Size  47: 24,47   BAD  (HHHFHH)
+Size  48: 24,48   BAD  (HHHFHH)
+Size  49: 25,49   BAD  (HHHFHH)
+Size  50: 25,50   BAD  (HHHFHH)
+Size  51: 26,51   BAD  (HHHFHH)
+Size  52: 26,52   BAD  (HHHFHH)
+Size  53: 27,53   BAD  (HHHFHH)
+Size  54: 27,54   BAD  (HHHFHH)
+Size  55: 28,55   BAD  (HHHFHH)
+Size  56: 28,56   BAD  (HHHFHH)
+Size  57: 29,57   BAD  (HHHFHH)
+Size  58: 29,58   BAD  (HHHFHH)
+Size  59: 30,59   BAD  (HHHFHH)
+Size  60: 30,60   BAD  (HHHFHH)
+Size  61: 31,61   BAD  (HHHFHH)
+Size  62: 31,62   BAD  (HHHFHH)
+Size  63: 32,63   BAD  (HHHFHH)
+Size  64: 32,64   BAD  (HHHFHH)
+Size  65: 33,65   BAD  (HHHFHH)
+Size  66: 33,66   BAD  (HHHFHH)
+Size  67: 34,67   BAD  (HHHFHH)
+Size  68: 34,68   BAD  (HHHFHH)
+Size  69: 35,69   BAD  (HHHFHH)
+Size  70: 35,70   BAD  (HHHFHH)
+Size  71: 36,71   BAD  (HHHFHH)
+Size  72: 36,72   BAD  (HHHFHH)
+Size  73: 37,73   BAD  (HHHFHH)
+Size  74: 37,74   BAD  (HHHFHH)
+Size  75: 38,75   BAD  (HHHFHH)
+Size  76: 38,76   BAD  (HHHFHH)
+Size  77: 39,77   BAD  (HHHFHH)
+Size  78: 39,78   BAD  (HHHFHH)
+Size  79: 40,79   BAD  (HHHFHH)
+Size  80: 40,80   BAD  (HHHFHH)
+Size  81: 41,81   BAD  (HHHFHH)
+Size  82: 41,82   BAD  (HHHFHH)
+Size  83: 42,83   BAD  (HHHFHH)
+Size  84: 42,84   BAD  (HHHFHH)
+Size  85: 43,85   BAD  (HHHFHH)
+Size  86: 43,86   BAD  (HHHFHH)
+Size  87: 44,87   BAD  (HHHFHH)
+Size  88: 44,88   BAD  (HHHFHH)
+Size  89: 45,89   BAD  (HHHFHH)
+Size  90: 45,90   BAD  (HHHFHH)
+Size  91: 46,91   BAD  (HHHFHH)
+Size  92: 46,92   BAD  (HHHFHH)
+Size  93: 47,93   BAD  (HHHFHH)
+Size  94: 47,94   BAD  (HHHFHH)
+Size  95: 48,95   BAD  (HHHFHH)
+Size  96: 48,97   BAD  (HHHFHH)
+Size  97: 49,97   BAD  (HHHFHH)
+Size  98: 49,98   BAD  (HHHFHH)
+Size  99: 50,99   BAD  (HHHFHH)
+Size 100: 50,100  BAD  (HHHFHH)
+
+Windows 7
+---------
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,4     OK   (HHHFFF)
+Size   5: 3,5     OK   (HHHFFF)
+Size   6: 3,6     OK   (HHHFFF)
+Size   7: 4,7     OK   (HHHFFF)
+Size   8: 4,8     OK   (HHHFFF)
+Size   9: 5,9     OK   (HHHFFF)
+Size  10: 5,10    OK   (HHHFFF)
+Size  11: 6,11    OK   (HHHFFF)
+Size  12: 6,12    OK   (HHHFFF)
+Size  13: 7,13    OK   (HHHFFF)
+Size  14: 7,14    BAD  (FFFFFF)
+Size  15: 8,15    OK   (HHHFFF)
+Size  16: 8,16    BAD  (FFFFFF)
+Size  17: 9,17    OK   (HHHFFF)
+Size  18: 9,18    BAD  (FFFFFF)
+Size  19: 10,19   OK   (HHHFFF)
+Size  20: 10,20   BAD  (FFFFFF)
+Size  21: 11,21   OK   (HHHFFF)
+Size  22: 11,22   BAD  (FFFFFF)
+Size  23: 12,23   BAD  (FFFFFF)
+Size  24: 12,24   BAD  (FFFFFF)
+Size  25: 13,25   BAD  (FFFFFF)
+Size  26: 13,26   BAD  (FFFFFF)
+Size  27: 14,27   BAD  (FFFFFF)
+Size  28: 14,28   BAD  (FFFFFF)
+Size  29: 15,29   BAD  (FFFFFF)
+Size  30: 15,30   BAD  (FFFFFF)
+Size  31: 16,31   BAD  (FFFFFF)
+Size  32: 16,33   BAD  (FFFFFF)
+Size  33: 17,33   BAD  (FFFFFF)
+Size  34: 17,34   BAD  (FFFFFF)
+Size  35: 18,35   BAD  (FFFFFF)
+Size  36: 18,36   BAD  (FFFFFF)
+Size  37: 19,37   BAD  (FFFFFF)
+Size  38: 19,38   BAD  (FFFFFF)
+Size  39: 20,39   BAD  (FFFFFF)
+Size  40: 20,40   BAD  (FFFFFF)
+Size  41: 21,41   BAD  (FFFFFF)
+Size  42: 21,42   BAD  (FFFFFF)
+Size  43: 22,43   BAD  (FFFFFF)
+Size  44: 22,44   BAD  (FFFFFF)
+Size  45: 23,45   BAD  (FFFFFF)
+Size  46: 23,46   BAD  (FFFFFF)
+Size  47: 24,47   BAD  (FFFFFF)
+Size  48: 24,48   BAD  (FFFFFF)
+Size  49: 25,49   BAD  (FFFFFF)
+Size  50: 25,50   BAD  (FFFFFF)
+Size  51: 26,51   BAD  (FFFFFF)
+Size  52: 26,52   BAD  (FFFFFF)
+Size  53: 27,53   BAD  (FFFFFF)
+Size  54: 27,54   BAD  (FFFFFF)
+Size  55: 28,55   BAD  (FFFFFF)
+Size  56: 28,56   BAD  (FFFFFF)
+Size  57: 29,57   BAD  (FFFFFF)
+Size  58: 29,58   BAD  (FFFFFF)
+Size  59: 30,59   BAD  (FFFFFF)
+Size  60: 30,60   BAD  (FFFFFF)
+Size  61: 31,61   BAD  (FFFFFF)
+Size  62: 31,62   BAD  (FFFFFF)
+Size  63: 32,63   BAD  (FFFFFF)
+Size  64: 32,64   BAD  (FFFFFF)
+Size  65: 33,65   BAD  (FFFFFF)
+Size  66: 33,66   BAD  (FFFFFF)
+Size  67: 34,67   BAD  (FFFFFF)
+Size  68: 34,68   BAD  (FFFFFF)
+Size  69: 35,69   BAD  (FFFFFF)
+Size  70: 35,70   BAD  (FFFFFF)
+Size  71: 36,71   BAD  (FFFFFF)
+Size  72: 36,72   BAD  (FFFFFF)
+Size  73: 37,73   BAD  (FFFFFF)
+Size  74: 37,74   BAD  (FFFFFF)
+Size  75: 38,75   BAD  (FFFFFF)
+Size  76: 38,76   BAD  (FFFFFF)
+Size  77: 39,77   BAD  (FFFFFF)
+Size  78: 39,78   BAD  (FFFFFF)
+Size  79: 40,79   BAD  (FFFFFF)
+Size  80: 40,80   BAD  (FFFFFF)
+Size  81: 41,81   BAD  (FFFFFF)
+Size  82: 41,82   BAD  (FFFFFF)
+Size  83: 42,83   BAD  (FFFFFF)
+Size  84: 42,84   BAD  (FFFFFF)
+Size  85: 43,85   BAD  (FFFFFF)
+Size  86: 43,86   BAD  (FFFFFF)
+Size  87: 44,87   BAD  (FFFFFF)
+Size  88: 44,88   BAD  (FFFFFF)
+Size  89: 45,89   BAD  (FFFFFF)
+Size  90: 45,90   BAD  (FFFFFF)
+Size  91: 46,91   BAD  (FFFFFF)
+Size  92: 46,92   BAD  (FFFFFF)
+Size  93: 47,93   BAD  (FFFFFF)
+Size  94: 47,94   BAD  (FFFFFF)
+Size  95: 48,95   BAD  (FFFFFF)
+Size  96: 48,97   BAD  (FFFFFF)
+Size  97: 49,97   BAD  (FFFFFF)
+Size  98: 49,98   BAD  (FFFFFF)
+Size  99: 50,99   BAD  (FFFFFF)
+Size 100: 50,100  BAD  (FFFFFF)
+
+Windows 8
+---------
+
+Size   1: 1,2     BAD  (FFFFHH)
+Size   2: 1,2     BAD  (FFFFHH)
+Size   3: 2,3     BAD  (FFFFFF)
+Size   4: 2,4     BAD  (FFFFHH)
+Size   5: 3,5     BAD  (FFFFFF)
+Size   6: 3,6     BAD  (FFFFHH)
+Size   7: 4,7     BAD  (FFFFFF)
+Size   8: 4,8     BAD  (FFFFHH)
+Size   9: 5,9     BAD  (FFFFFF)
+Size  10: 5,10    BAD  (FFFFHH)
+Size  11: 6,11    BAD  (FFFFFF)
+Size  12: 6,12    BAD  (FFFFHH)
+Size  13: 7,13    BAD  (FFFFFF)
+Size  14: 7,14    BAD  (FFFFHH)
+Size  15: 8,15    BAD  (FFFFFF)
+Size  16: 8,16    BAD  (FFFFHH)
+Size  17: 9,17    BAD  (FFFFFF)
+Size  18: 9,18    BAD  (FFFFHH)
+Size  19: 10,19   BAD  (FFFFFF)
+Size  20: 10,20   BAD  (FFFFFF)
+Size  21: 11,21   BAD  (FFFFFF)
+Size  22: 11,22   BAD  (FFFFFF)
+Size  23: 12,23   BAD  (FFFFFF)
+Size  24: 12,24   BAD  (FFFFFF)
+Size  25: 13,25   BAD  (FFFFFF)
+Size  26: 13,26   BAD  (FFFFFF)
+Size  27: 14,27   BAD  (FFFFFF)
+Size  28: 14,28   BAD  (FFFFFF)
+Size  29: 15,29   BAD  (FFFFFF)
+Size  30: 15,30   BAD  (FFFFFF)
+Size  31: 16,31   BAD  (FFFFFF)
+Size  32: 16,33   BAD  (FFFFFF)
+Size  33: 17,33   BAD  (FFFFFF)
+Size  34: 17,34   BAD  (FFFFFF)
+Size  35: 18,35   BAD  (FFFFFF)
+Size  36: 18,36   BAD  (FFFFFF)
+Size  37: 19,37   BAD  (FFFFFF)
+Size  38: 19,38   BAD  (FFFFFF)
+Size  39: 20,39   BAD  (FFFFFF)
+Size  40: 20,40   BAD  (FFFFFF)
+Size  41: 21,41   BAD  (FFFFFF)
+Size  42: 21,42   BAD  (FFFFFF)
+Size  43: 22,43   BAD  (FFFFFF)
+Size  44: 22,44   BAD  (FFFFFF)
+Size  45: 23,45   BAD  (FFFFFF)
+Size  46: 23,46   BAD  (FFFFFF)
+Size  47: 24,47   BAD  (FFFFFF)
+Size  48: 24,48   BAD  (FFFFFF)
+Size  49: 25,49   BAD  (FFFFFF)
+Size  50: 25,50   BAD  (FFFFFF)
+Size  51: 26,51   BAD  (FFFFFF)
+Size  52: 26,52   BAD  (FFFFFF)
+Size  53: 27,53   BAD  (FFFFFF)
+Size  54: 27,54   BAD  (FFFFFF)
+Size  55: 28,55   BAD  (FFFFFF)
+Size  56: 28,56   BAD  (FFFFFF)
+Size  57: 29,57   BAD  (FFFFFF)
+Size  58: 29,58   BAD  (FFFFFF)
+Size  59: 30,59   BAD  (FFFFFF)
+Size  60: 30,60   BAD  (FFFFFF)
+Size  61: 31,61   BAD  (FFFFFF)
+Size  62: 31,62   BAD  (FFFFFF)
+Size  63: 32,63   BAD  (FFFFFF)
+Size  64: 32,64   BAD  (FFFFFF)
+Size  65: 33,65   BAD  (FFFFFF)
+Size  66: 33,66   BAD  (FFFFFF)
+Size  67: 34,67   BAD  (FFFFFF)
+Size  68: 34,68   BAD  (FFFFFF)
+Size  69: 35,69   BAD  (FFFFFF)
+Size  70: 35,70   BAD  (FFFFFF)
+Size  71: 36,71   BAD  (FFFFFF)
+Size  72: 36,72   BAD  (FFFFFF)
+Size  73: 37,73   BAD  (FFFFFF)
+Size  74: 37,74   BAD  (FFFFFF)
+Size  75: 38,75   BAD  (FFFFFF)
+Size  76: 38,76   BAD  (FFFFFF)
+Size  77: 39,77   BAD  (FFFFFF)
+Size  78: 39,78   BAD  (FFFFFF)
+Size  79: 40,79   BAD  (FFFFFF)
+Size  80: 40,80   BAD  (FFFFFF)
+Size  81: 41,81   BAD  (FFFFFF)
+Size  82: 41,82   BAD  (FFFFFF)
+Size  83: 42,83   BAD  (FFFFFF)
+Size  84: 42,84   BAD  (FFFFFF)
+Size  85: 43,85   BAD  (FFFFFF)
+Size  86: 43,86   BAD  (FFFFFF)
+Size  87: 44,87   BAD  (FFFFFF)
+Size  88: 44,88   BAD  (FFFFFF)
+Size  89: 45,89   BAD  (FFFFFF)
+Size  90: 45,90   BAD  (FFFFFF)
+Size  91: 46,91   BAD  (FFFFFF)
+Size  92: 46,92   BAD  (FFFFFF)
+Size  93: 47,93   BAD  (FFFFFF)
+Size  94: 47,94   BAD  (FFFFFF)
+Size  95: 48,95   BAD  (FFFFFF)
+Size  96: 48,97   BAD  (FFFFFF)
+Size  97: 49,97   BAD  (FFFFFF)
+Size  98: 49,98   BAD  (FFFFFF)
+Size  99: 50,99   BAD  (FFFFFF)
+Size 100: 50,100  BAD  (FFFFFF)
+
+Windows 8.1
+-----------
+
+Size   1: 1,2     BAD  (FFFFHH)
+Size   2: 1,2     BAD  (FFFFHH)
+Size   3: 2,3     BAD  (FFFFFF)
+Size   4: 2,4     BAD  (FFFFHH)
+Size   5: 3,5     BAD  (FFFFFF)
+Size   6: 3,6     BAD  (FFFFHH)
+Size   7: 4,7     BAD  (FFFFFF)
+Size   8: 4,8     BAD  (FFFFHH)
+Size   9: 5,9     BAD  (FFFFFF)
+Size  10: 5,10    BAD  (FFFFHH)
+Size  11: 6,11    BAD  (FFFFFF)
+Size  12: 6,12    BAD  (FFFFHH)
+Size  13: 7,13    BAD  (FFFFFF)
+Size  14: 7,14    BAD  (FFFFHH)
+Size  15: 8,15    BAD  (FFFFFF)
+Size  16: 8,16    BAD  (FFFFHH)
+Size  17: 9,17    BAD  (FFFFFF)
+Size  18: 9,18    BAD  (FFFFHH)
+Size  19: 10,19   BAD  (FFFFFF)
+Size  20: 10,20   BAD  (FFFFFF)
+Size  21: 11,21   BAD  (FFFFFF)
+Size  22: 11,22   BAD  (FFFFFF)
+Size  23: 12,23   BAD  (FFFFFF)
+Size  24: 12,24   BAD  (FFFFFF)
+Size  25: 13,25   BAD  (FFFFFF)
+Size  26: 13,26   BAD  (FFFFFF)
+Size  27: 14,27   BAD  (FFFFFF)
+Size  28: 14,28   BAD  (FFFFFF)
+Size  29: 15,29   BAD  (FFFFFF)
+Size  30: 15,30   BAD  (FFFFFF)
+Size  31: 16,31   BAD  (FFFFFF)
+Size  32: 16,33   BAD  (FFFFFF)
+Size  33: 17,33   BAD  (FFFFFF)
+Size  34: 17,34   BAD  (FFFFFF)
+Size  35: 18,35   BAD  (FFFFFF)
+Size  36: 18,36   BAD  (FFFFFF)
+Size  37: 19,37   BAD  (FFFFFF)
+Size  38: 19,38   BAD  (FFFFFF)
+Size  39: 20,39   BAD  (FFFFFF)
+Size  40: 20,40   BAD  (FFFFFF)
+Size  41: 21,41   BAD  (FFFFFF)
+Size  42: 21,42   BAD  (FFFFFF)
+Size  43: 22,43   BAD  (FFFFFF)
+Size  44: 22,44   BAD  (FFFFFF)
+Size  45: 23,45   BAD  (FFFFFF)
+Size  46: 23,46   BAD  (FFFFFF)
+Size  47: 24,47   BAD  (FFFFFF)
+Size  48: 24,48   BAD  (FFFFFF)
+Size  49: 25,49   BAD  (FFFFFF)
+Size  50: 25,50   BAD  (FFFFFF)
+Size  51: 26,51   BAD  (FFFFFF)
+Size  52: 26,52   BAD  (FFFFFF)
+Size  53: 27,53   BAD  (FFFFFF)
+Size  54: 27,54   BAD  (FFFFFF)
+Size  55: 28,55   BAD  (FFFFFF)
+Size  56: 28,56   BAD  (FFFFFF)
+Size  57: 29,57   BAD  (FFFFFF)
+Size  58: 29,58   BAD  (FFFFFF)
+Size  59: 30,59   BAD  (FFFFFF)
+Size  60: 30,60   BAD  (FFFFFF)
+Size  61: 31,61   BAD  (FFFFFF)
+Size  62: 31,62   BAD  (FFFFFF)
+Size  63: 32,63   BAD  (FFFFFF)
+Size  64: 32,64   BAD  (FFFFFF)
+Size  65: 33,65   BAD  (FFFFFF)
+Size  66: 33,66   BAD  (FFFFFF)
+Size  67: 34,67   BAD  (FFFFFF)
+Size  68: 34,68   BAD  (FFFFFF)
+Size  69: 35,69   BAD  (FFFFFF)
+Size  70: 35,70   BAD  (FFFFFF)
+Size  71: 36,71   BAD  (FFFFFF)
+Size  72: 36,72   BAD  (FFFFFF)
+Size  73: 37,73   BAD  (FFFFFF)
+Size  74: 37,74   BAD  (FFFFFF)
+Size  75: 38,75   BAD  (FFFFFF)
+Size  76: 38,76   BAD  (FFFFFF)
+Size  77: 39,77   BAD  (FFFFFF)
+Size  78: 39,78   BAD  (FFFFFF)
+Size  79: 40,79   BAD  (FFFFFF)
+Size  80: 40,80   BAD  (FFFFFF)
+Size  81: 41,81   BAD  (FFFFFF)
+Size  82: 41,82   BAD  (FFFFFF)
+Size  83: 42,83   BAD  (FFFFFF)
+Size  84: 42,84   BAD  (FFFFFF)
+Size  85: 43,85   BAD  (FFFFFF)
+Size  86: 43,86   BAD  (FFFFFF)
+Size  87: 44,87   BAD  (FFFFFF)
+Size  88: 44,88   BAD  (FFFFFF)
+Size  89: 45,89   BAD  (FFFFFF)
+Size  90: 45,90   BAD  (FFFFFF)
+Size  91: 46,91   BAD  (FFFFFF)
+Size  92: 46,92   BAD  (FFFFFF)
+Size  93: 47,93   BAD  (FFFFFF)
+Size  94: 47,94   BAD  (FFFFFF)
+Size  95: 48,95   BAD  (FFFFFF)
+Size  96: 48,97   BAD  (FFFFFF)
+Size  97: 49,97   BAD  (FFFFFF)
+Size  98: 49,98   BAD  (FFFFFF)
+Size  99: 50,99   BAD  (FFFFFF)
+Size 100: 50,100  BAD  (FFFFFF)
+
+Windows 10 14342 Old Console
+----------------------------
+
+Size   1: 1,2     BAD  (FFFFHH)
+Size   2: 1,2     BAD  (FFFFHH)
+Size   3: 2,3     BAD  (FFFFFF)
+Size   4: 2,4     BAD  (FFFFHH)
+Size   5: 3,5     BAD  (FFFFFF)
+Size   6: 3,6     BAD  (FFFFHH)
+Size   7: 4,7     BAD  (FFFFFF)
+Size   8: 4,8     BAD  (FFFFHH)
+Size   9: 5,9     BAD  (FFFFFF)
+Size  10: 5,10    BAD  (FFFFHH)
+Size  11: 6,11    BAD  (FFFFFF)
+Size  12: 6,12    BAD  (FFFFHH)
+Size  13: 7,13    BAD  (FFFFFF)
+Size  14: 7,14    BAD  (FFFFHH)
+Size  15: 8,15    BAD  (FFFFFF)
+Size  16: 8,16    BAD  (FFFFHH)
+Size  17: 9,17    BAD  (FFFFFF)
+Size  18: 9,18    BAD  (FFFFHH)
+Size  19: 10,19   BAD  (FFFFFF)
+Size  20: 10,20   BAD  (FFFFFF)
+Size  21: 11,21   BAD  (FFFFFF)
+Size  22: 11,22   BAD  (FFFFFF)
+Size  23: 12,23   BAD  (FFFFFF)
+Size  24: 12,24   BAD  (FFFFFF)
+Size  25: 13,25   BAD  (FFFFFF)
+Size  26: 13,26   BAD  (FFFFFF)
+Size  27: 14,27   BAD  (FFFFFF)
+Size  28: 14,28   BAD  (FFFFFF)
+Size  29: 15,29   BAD  (FFFFFF)
+Size  30: 15,30   BAD  (FFFFFF)
+Size  31: 16,31   BAD  (FFFFFF)
+Size  32: 16,33   BAD  (FFFFFF)
+Size  33: 17,33   BAD  (FFFFFF)
+Size  34: 17,34   BAD  (FFFFFF)
+Size  35: 18,35   BAD  (FFFFFF)
+Size  36: 18,36   BAD  (FFFFFF)
+Size  37: 19,37   BAD  (FFFFFF)
+Size  38: 19,38   BAD  (FFFFFF)
+Size  39: 20,39   BAD  (FFFFFF)
+Size  40: 20,40   BAD  (FFFFFF)
+Size  41: 21,41   BAD  (FFFFFF)
+Size  42: 21,42   BAD  (FFFFFF)
+Size  43: 22,43   BAD  (FFFFFF)
+Size  44: 22,44   BAD  (FFFFFF)
+Size  45: 23,45   BAD  (FFFFFF)
+Size  46: 23,46   BAD  (FFFFFF)
+Size  47: 24,47   BAD  (FFFFFF)
+Size  48: 24,48   BAD  (FFFFFF)
+Size  49: 25,49   BAD  (FFFFFF)
+Size  50: 25,50   BAD  (FFFFFF)
+Size  51: 26,51   BAD  (FFFFFF)
+Size  52: 26,52   BAD  (FFFFFF)
+Size  53: 27,53   BAD  (FFFFFF)
+Size  54: 27,54   BAD  (FFFFFF)
+Size  55: 28,55   BAD  (FFFFFF)
+Size  56: 28,56   BAD  (FFFFFF)
+Size  57: 29,57   BAD  (FFFFFF)
+Size  58: 29,58   BAD  (FFFFFF)
+Size  59: 30,59   BAD  (FFFFFF)
+Size  60: 30,60   BAD  (FFFFFF)
+Size  61: 31,61   BAD  (FFFFFF)
+Size  62: 31,62   BAD  (FFFFFF)
+Size  63: 32,63   BAD  (FFFFFF)
+Size  64: 32,64   BAD  (FFFFFF)
+Size  65: 33,65   BAD  (FFFFFF)
+Size  66: 33,66   BAD  (FFFFFF)
+Size  67: 34,67   BAD  (FFFFFF)
+Size  68: 34,68   BAD  (FFFFFF)
+Size  69: 35,69   BAD  (FFFFFF)
+Size  70: 35,70   BAD  (FFFFFF)
+Size  71: 36,71   BAD  (FFFFFF)
+Size  72: 36,72   BAD  (FFFFFF)
+Size  73: 37,73   BAD  (FFFFFF)
+Size  74: 37,74   BAD  (FFFFFF)
+Size  75: 38,75   BAD  (FFFFFF)
+Size  76: 38,76   BAD  (FFFFFF)
+Size  77: 39,77   BAD  (FFFFFF)
+Size  78: 39,78   BAD  (FFFFFF)
+Size  79: 40,79   BAD  (FFFFFF)
+Size  80: 40,80   BAD  (FFFFFF)
+Size  81: 41,81   BAD  (FFFFFF)
+Size  82: 41,82   BAD  (FFFFFF)
+Size  83: 42,83   BAD  (FFFFFF)
+Size  84: 42,84   BAD  (FFFFFF)
+Size  85: 43,85   BAD  (FFFFFF)
+Size  86: 43,86   BAD  (FFFFFF)
+Size  87: 44,87   BAD  (FFFFFF)
+Size  88: 44,88   BAD  (FFFFFF)
+Size  89: 45,89   BAD  (FFFFFF)
+Size  90: 45,90   BAD  (FFFFFF)
+Size  91: 46,91   BAD  (FFFFFF)
+Size  92: 46,92   BAD  (FFFFFF)
+Size  93: 47,93   BAD  (FFFFFF)
+Size  94: 47,94   BAD  (FFFFFF)
+Size  95: 48,95   BAD  (FFFFFF)
+Size  96: 48,97   BAD  (FFFFFF)
+Size  97: 49,97   BAD  (FFFFFF)
+Size  98: 49,98   BAD  (FFFFFF)
+Size  99: 50,99   BAD  (FFFFFF)
+Size 100: 50,100  BAD  (FFFFFF)
+
+Windows 10 14342 New Console
+----------------------------
+
+Size   1: 1,1     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     OK   (HHHFFF)
+Size   4: 2,4     OK   (HHHFFF)
+Size   5: 3,5     OK   (HHHFFF)
+Size   6: 3,6     OK   (HHHFFF)
+Size   7: 4,7     OK   (HHHFFF)
+Size   8: 4,8     OK   (HHHFFF)
+Size   9: 5,9     OK   (HHHFFF)
+Size  10: 5,10    OK   (HHHFFF)
+Size  11: 6,11    OK   (HHHFFF)
+Size  12: 6,12    OK   (HHHFFF)
+Size  13: 7,13    OK   (HHHFFF)
+Size  14: 7,14    OK   (HHHFFF)
+Size  15: 8,15    OK   (HHHFFF)
+Size  16: 8,16    OK   (HHHFFF)
+Size  17: 9,17    OK   (HHHFFF)
+Size  18: 9,18    OK   (HHHFFF)
+Size  19: 10,19   OK   (HHHFFF)
+Size  20: 10,20   OK   (HHHFFF)
+Size  21: 11,21   OK   (HHHFFF)
+Size  22: 11,22   OK   (HHHFFF)
+Size  23: 12,23   OK   (HHHFFF)
+Size  24: 12,24   OK   (HHHFFF)
+Size  25: 13,25   OK   (HHHFFF)
+Size  26: 13,26   OK   (HHHFFF)
+Size  27: 14,27   OK   (HHHFFF)
+Size  28: 14,28   OK   (HHHFFF)
+Size  29: 15,29   OK   (HHHFFF)
+Size  30: 15,30   OK   (HHHFFF)
+Size  31: 16,31   OK   (HHHFFF)
+Size  32: 16,32   OK   (HHHFFF)
+Size  33: 17,33   OK   (HHHFFF)
+Size  34: 17,34   OK   (HHHFFF)
+Size  35: 18,35   OK   (HHHFFF)
+Size  36: 18,36   OK   (HHHFFF)
+Size  37: 19,37   OK   (HHHFFF)
+Size  38: 19,38   OK   (HHHFFF)
+Size  39: 20,39   OK   (HHHFFF)
+Size  40: 20,40   OK   (HHHFFF)
+Size  41: 21,41   OK   (HHHFFF)
+Size  42: 21,42   OK   (HHHFFF)
+Size  43: 22,43   OK   (HHHFFF)
+Size  44: 22,44   OK   (HHHFFF)
+Size  45: 23,45   OK   (HHHFFF)
+Size  46: 23,46   OK   (HHHFFF)
+Size  47: 24,47   OK   (HHHFFF)
+Size  48: 24,48   OK   (HHHFFF)
+Size  49: 25,49   OK   (HHHFFF)
+Size  50: 25,50   OK   (HHHFFF)
+Size  51: 26,51   OK   (HHHFFF)
+Size  52: 26,52   OK   (HHHFFF)
+Size  53: 27,53   OK   (HHHFFF)
+Size  54: 27,54   OK   (HHHFFF)
+Size  55: 28,55   OK   (HHHFFF)
+Size  56: 28,56   OK   (HHHFFF)
+Size  57: 29,57   OK   (HHHFFF)
+Size  58: 29,58   OK   (HHHFFF)
+Size  59: 30,59   OK   (HHHFFF)
+Size  60: 30,60   OK   (HHHFFF)
+Size  61: 31,61   OK   (HHHFFF)
+Size  62: 31,62   OK   (HHHFFF)
+Size  63: 32,63   OK   (HHHFFF)
+Size  64: 32,64   OK   (HHHFFF)
+Size  65: 33,65   OK   (HHHFFF)
+Size  66: 33,66   OK   (HHHFFF)
+Size  67: 34,67   OK   (HHHFFF)
+Size  68: 34,68   OK   (HHHFFF)
+Size  69: 35,69   OK   (HHHFFF)
+Size  70: 35,70   OK   (HHHFFF)
+Size  71: 36,71   OK   (HHHFFF)
+Size  72: 36,72   OK   (HHHFFF)
+Size  73: 37,73   OK   (HHHFFF)
+Size  74: 37,74   OK   (HHHFFF)
+Size  75: 38,75   OK   (HHHFFF)
+Size  76: 38,76   OK   (HHHFFF)
+Size  77: 39,77   OK   (HHHFFF)
+Size  78: 39,78   OK   (HHHFFF)
+Size  79: 40,79   OK   (HHHFFF)
+Size  80: 40,80   OK   (HHHFFF)
+Size  81: 41,81   OK   (HHHFFF)
+Size  82: 41,82   OK   (HHHFFF)
+Size  83: 42,83   OK   (HHHFFF)
+Size  84: 42,84   OK   (HHHFFF)
+Size  85: 43,85   OK   (HHHFFF)
+Size  86: 43,86   OK   (HHHFFF)
+Size  87: 44,87   OK   (HHHFFF)
+Size  88: 44,88   OK   (HHHFFF)
+Size  89: 45,89   OK   (HHHFFF)
+Size  90: 45,90   OK   (HHHFFF)
+Size  91: 46,91   OK   (HHHFFF)
+Size  92: 46,92   OK   (HHHFFF)
+Size  93: 47,93   OK   (HHHFFF)
+Size  94: 47,94   OK   (HHHFFF)
+Size  95: 48,95   OK   (HHHFFF)
+Size  96: 48,96   OK   (HHHFFF)
+Size  97: 49,97   OK   (HHHFFF)
+Size  98: 49,98   OK   (HHHFFF)
+Size  99: 50,99   OK   (HHHFFF)
+Size 100: 50,100  OK   (HHHFFF)
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP936.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP936.txt
new file mode 100644 (file)
index 0000000..43210da
--- /dev/null
@@ -0,0 +1,630 @@
+==========================================================
+Code Page 936, Chinese Simplified (China/PRC), SimSun font
+==========================================================
+
+Options: -face-simsun -family 0x36
+Chars: A2 A3 2014 3044 30FC 4000
+
+Vista
+-----
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (HHHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (HHHFHH)
+Size   8: 4,9     GOOD (HHFFFF)
+Size   9: 5,10    BAD  (HHHFHH)
+Size  10: 5,11    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (HHHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,15    BAD  (HHHFHH)
+Size  14: 7,16    GOOD (HHFFFF)
+Size  15: 8,17    BAD  (HHHFHH)
+Size  16: 8,18    GOOD (HHFFFF)
+Size  17: 9,19    BAD  (HHHFHH)
+Size  18: 9,21    GOOD (HHFFFF)
+Size  19: 10,22   BAD  (HHHFHH)
+Size  20: 10,23   GOOD (HHFFFF)
+Size  21: 11,24   BAD  (HHHFHH)
+Size  22: 11,25   GOOD (HHFFFF)
+Size  23: 12,26   BAD  (HHHFHH)
+Size  24: 12,27   GOOD (HHFFFF)
+Size  25: 13,29   BAD  (HHHFHH)
+Size  26: 13,30   GOOD (HHFFFF)
+Size  27: 14,31   BAD  (HHHFHH)
+Size  28: 14,32   GOOD (HHFFFF)
+Size  29: 15,33   BAD  (HHHFHH)
+Size  30: 15,34   GOOD (HHFFFF)
+Size  31: 16,35   BAD  (HHHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,38   BAD  (HHHFHH)
+Size  34: 17,39   GOOD (HHFFFF)
+Size  35: 18,40   BAD  (HHHFHH)
+Size  36: 18,41   GOOD (HHFFFF)
+Size  37: 19,42   BAD  (HHHFHH)
+Size  38: 19,43   GOOD (HHFFFF)
+Size  39: 20,44   BAD  (HHHFHH)
+Size  40: 20,46   GOOD (HHFFFF)
+Size  41: 21,47   BAD  (HHHFHH)
+Size  42: 21,48   GOOD (HHFFFF)
+Size  43: 22,49   BAD  (HHHFHH)
+Size  44: 22,50   GOOD (HHFFFF)
+Size  45: 23,51   BAD  (HHHFHH)
+Size  46: 23,52   GOOD (HHFFFF)
+Size  47: 24,54   BAD  (HHHFHH)
+Size  48: 24,55   GOOD (HHFFFF)
+Size  49: 25,56   BAD  (HHHFHH)
+Size  50: 25,57   GOOD (HHFFFF)
+Size  51: 26,58   BAD  (HHHFHH)
+Size  52: 26,59   GOOD (HHFFFF)
+Size  53: 27,60   BAD  (HHHFHH)
+Size  54: 27,62   GOOD (HHFFFF)
+Size  55: 28,63   BAD  (HHHFHH)
+Size  56: 28,64   GOOD (HHFFFF)
+Size  57: 29,65   BAD  (HHHFHH)
+Size  58: 29,66   GOOD (HHFFFF)
+Size  59: 30,67   BAD  (HHHFHH)
+Size  60: 30,68   GOOD (HHFFFF)
+Size  61: 31,70   BAD  (HHHFHH)
+Size  62: 31,71   GOOD (HHFFFF)
+Size  63: 32,72   BAD  (HHHFHH)
+Size  64: 32,73   GOOD (HHFFFF)
+Size  65: 33,74   GOOD (HHFFFF)
+Size  66: 33,75   GOOD (HHFFFF)
+Size  67: 34,76   GOOD (HHFFFF)
+Size  68: 34,78   GOOD (HHFFFF)
+Size  69: 35,79   GOOD (HHFFFF)
+Size  70: 35,80   GOOD (HHFFFF)
+Size  71: 36,81   GOOD (HHFFFF)
+Size  72: 36,82   GOOD (HHFFFF)
+Size  73: 37,83   GOOD (HHFFFF)
+Size  74: 37,84   GOOD (HHFFFF)
+Size  75: 38,86   GOOD (HHFFFF)
+Size  76: 38,87   GOOD (HHFFFF)
+Size  77: 39,88   GOOD (HHFFFF)
+Size  78: 39,89   GOOD (HHFFFF)
+Size  79: 40,90   GOOD (HHFFFF)
+Size  80: 40,91   GOOD (HHFFFF)
+Size  81: 41,92   GOOD (HHFFFF)
+Size  82: 41,94   GOOD (HHFFFF)
+Size  83: 42,95   GOOD (HHFFFF)
+Size  84: 42,96   GOOD (HHFFFF)
+Size  85: 43,97   GOOD (HHFFFF)
+Size  86: 43,98   GOOD (HHFFFF)
+Size  87: 44,99   GOOD (HHFFFF)
+Size  88: 44,100  GOOD (HHFFFF)
+Size  89: 45,102  GOOD (HHFFFF)
+Size  90: 45,103  GOOD (HHFFFF)
+Size  91: 46,104  GOOD (HHFFFF)
+Size  92: 46,105  GOOD (HHFFFF)
+Size  93: 47,106  GOOD (HHFFFF)
+Size  94: 47,107  GOOD (HHFFFF)
+Size  95: 48,108  GOOD (HHFFFF)
+Size  96: 48,111  GOOD (HHFFFF)
+Size  97: 49,111  GOOD (HHFFFF)
+Size  98: 49,112  GOOD (HHFFFF)
+Size  99: 50,113  GOOD (HHFFFF)
+Size 100: 50,114  GOOD (HHFFFF)
+
+Windows 7
+---------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,9     GOOD (HHFFFF)
+Size   9: 5,10    BAD  (FFHFHH)
+Size  10: 5,11    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,15    BAD  (FFHFHH)
+Size  14: 7,16    GOOD (HHFFFF)
+Size  15: 8,17    BAD  (FFHFHH)
+Size  16: 8,18    GOOD (HHFFFF)
+Size  17: 9,19    BAD  (FFHFHH)
+Size  18: 9,21    GOOD (HHFFFF)
+Size  19: 10,22   BAD  (FFHFHH)
+Size  20: 10,23   GOOD (HHFFFF)
+Size  21: 11,24   BAD  (FFHFHH)
+Size  22: 11,25   GOOD (HHFFFF)
+Size  23: 12,26   BAD  (FFHFHH)
+Size  24: 12,27   GOOD (HHFFFF)
+Size  25: 13,29   BAD  (FFHFHH)
+Size  26: 13,30   GOOD (HHFFFF)
+Size  27: 14,31   BAD  (FFHFHH)
+Size  28: 14,32   GOOD (HHFFFF)
+Size  29: 15,33   BAD  (FFHFHH)
+Size  30: 15,34   GOOD (HHFFFF)
+Size  31: 16,35   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,38   BAD  (FFHFHH)
+Size  34: 17,39   GOOD (HHFFFF)
+Size  35: 18,40   BAD  (FFHFHH)
+Size  36: 18,41   GOOD (HHFFFF)
+Size  37: 19,42   BAD  (FFHFHH)
+Size  38: 19,43   GOOD (HHFFFF)
+Size  39: 20,44   BAD  (FFHFHH)
+Size  40: 20,46   GOOD (HHFFFF)
+Size  41: 21,47   BAD  (FFHFHH)
+Size  42: 21,48   GOOD (HHFFFF)
+Size  43: 22,49   BAD  (FFHFHH)
+Size  44: 22,50   GOOD (HHFFFF)
+Size  45: 23,51   BAD  (FFHFHH)
+Size  46: 23,52   GOOD (HHFFFF)
+Size  47: 24,54   BAD  (FFHFHH)
+Size  48: 24,55   GOOD (HHFFFF)
+Size  49: 25,56   BAD  (FFHFHH)
+Size  50: 25,57   GOOD (HHFFFF)
+Size  51: 26,58   BAD  (FFHFHH)
+Size  52: 26,59   GOOD (HHFFFF)
+Size  53: 27,60   BAD  (FFHFHH)
+Size  54: 27,62   GOOD (HHFFFF)
+Size  55: 28,63   BAD  (FFHFHH)
+Size  56: 28,64   GOOD (HHFFFF)
+Size  57: 29,65   BAD  (FFHFHH)
+Size  58: 29,66   GOOD (HHFFFF)
+Size  59: 30,67   BAD  (FFHFHH)
+Size  60: 30,68   GOOD (HHFFFF)
+Size  61: 31,70   BAD  (FFHFHH)
+Size  62: 31,71   GOOD (HHFFFF)
+Size  63: 32,72   BAD  (FFHFHH)
+Size  64: 32,73   GOOD (HHFFFF)
+Size  65: 33,74   GOOD (HHFFFF)
+Size  66: 33,75   GOOD (HHFFFF)
+Size  67: 34,76   GOOD (HHFFFF)
+Size  68: 34,78   GOOD (HHFFFF)
+Size  69: 35,79   GOOD (HHFFFF)
+Size  70: 35,80   GOOD (HHFFFF)
+Size  71: 36,81   GOOD (HHFFFF)
+Size  72: 36,82   GOOD (HHFFFF)
+Size  73: 37,83   GOOD (HHFFFF)
+Size  74: 37,84   GOOD (HHFFFF)
+Size  75: 38,86   GOOD (HHFFFF)
+Size  76: 38,87   GOOD (HHFFFF)
+Size  77: 39,88   GOOD (HHFFFF)
+Size  78: 39,89   GOOD (HHFFFF)
+Size  79: 40,90   GOOD (HHFFFF)
+Size  80: 40,91   GOOD (HHFFFF)
+Size  81: 41,92   GOOD (HHFFFF)
+Size  82: 41,94   GOOD (HHFFFF)
+Size  83: 42,95   GOOD (HHFFFF)
+Size  84: 42,96   GOOD (HHFFFF)
+Size  85: 43,97   GOOD (HHFFFF)
+Size  86: 43,98   GOOD (HHFFFF)
+Size  87: 44,99   GOOD (HHFFFF)
+Size  88: 44,100  GOOD (HHFFFF)
+Size  89: 45,102  GOOD (HHFFFF)
+Size  90: 45,103  GOOD (HHFFFF)
+Size  91: 46,104  GOOD (HHFFFF)
+Size  92: 46,105  GOOD (HHFFFF)
+Size  93: 47,106  GOOD (HHFFFF)
+Size  94: 47,107  GOOD (HHFFFF)
+Size  95: 48,108  GOOD (HHFFFF)
+Size  96: 48,111  GOOD (HHFFFF)
+Size  97: 49,111  GOOD (HHFFFF)
+Size  98: 49,112  GOOD (HHFFFF)
+Size  99: 50,113  GOOD (HHFFFF)
+Size 100: 50,114  GOOD (HHFFFF)
+
+Windows 8
+---------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,9     GOOD (HHFFFF)
+Size   9: 5,10    BAD  (FFHFHH)
+Size  10: 5,11    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,15    BAD  (FFHFHH)
+Size  14: 7,16    GOOD (HHFFFF)
+Size  15: 8,17    BAD  (FFHFHH)
+Size  16: 8,18    GOOD (HHFFFF)
+Size  17: 9,19    BAD  (FFHFHH)
+Size  18: 9,21    GOOD (HHFFFF)
+Size  19: 10,22   BAD  (FFHFHH)
+Size  20: 10,23   GOOD (HHFFFF)
+Size  21: 11,24   BAD  (FFHFHH)
+Size  22: 11,25   GOOD (HHFFFF)
+Size  23: 12,26   BAD  (FFHFHH)
+Size  24: 12,27   GOOD (HHFFFF)
+Size  25: 13,29   BAD  (FFHFHH)
+Size  26: 13,30   GOOD (HHFFFF)
+Size  27: 14,31   BAD  (FFHFHH)
+Size  28: 14,32   GOOD (HHFFFF)
+Size  29: 15,33   BAD  (FFHFHH)
+Size  30: 15,34   GOOD (HHFFFF)
+Size  31: 16,35   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,38   BAD  (FFHFHH)
+Size  34: 17,39   GOOD (HHFFFF)
+Size  35: 18,40   BAD  (FFHFHH)
+Size  36: 18,41   GOOD (HHFFFF)
+Size  37: 19,42   BAD  (FFHFHH)
+Size  38: 19,43   GOOD (HHFFFF)
+Size  39: 20,44   BAD  (FFHFHH)
+Size  40: 20,46   GOOD (HHFFFF)
+Size  41: 21,47   BAD  (FFHFHH)
+Size  42: 21,48   GOOD (HHFFFF)
+Size  43: 22,49   BAD  (FFHFHH)
+Size  44: 22,50   GOOD (HHFFFF)
+Size  45: 23,51   BAD  (FFHFHH)
+Size  46: 23,52   GOOD (HHFFFF)
+Size  47: 24,54   BAD  (FFHFHH)
+Size  48: 24,55   GOOD (HHFFFF)
+Size  49: 25,56   BAD  (FFHFHH)
+Size  50: 25,57   GOOD (HHFFFF)
+Size  51: 26,58   BAD  (FFHFHH)
+Size  52: 26,59   GOOD (HHFFFF)
+Size  53: 27,60   BAD  (FFHFHH)
+Size  54: 27,62   GOOD (HHFFFF)
+Size  55: 28,63   BAD  (FFHFHH)
+Size  56: 28,64   GOOD (HHFFFF)
+Size  57: 29,65   BAD  (FFHFHH)
+Size  58: 29,66   GOOD (HHFFFF)
+Size  59: 30,67   BAD  (FFHFHH)
+Size  60: 30,68   GOOD (HHFFFF)
+Size  61: 31,70   BAD  (FFHFHH)
+Size  62: 31,71   GOOD (HHFFFF)
+Size  63: 32,72   BAD  (FFHFHH)
+Size  64: 32,73   GOOD (HHFFFF)
+Size  65: 33,74   GOOD (HHFFFF)
+Size  66: 33,75   GOOD (HHFFFF)
+Size  67: 34,76   GOOD (HHFFFF)
+Size  68: 34,78   GOOD (HHFFFF)
+Size  69: 35,79   GOOD (HHFFFF)
+Size  70: 35,80   GOOD (HHFFFF)
+Size  71: 36,81   GOOD (HHFFFF)
+Size  72: 36,82   GOOD (HHFFFF)
+Size  73: 37,83   GOOD (HHFFFF)
+Size  74: 37,84   GOOD (HHFFFF)
+Size  75: 38,86   GOOD (HHFFFF)
+Size  76: 38,87   GOOD (HHFFFF)
+Size  77: 39,88   GOOD (HHFFFF)
+Size  78: 39,89   GOOD (HHFFFF)
+Size  79: 40,90   GOOD (HHFFFF)
+Size  80: 40,91   GOOD (HHFFFF)
+Size  81: 41,92   GOOD (HHFFFF)
+Size  82: 41,94   GOOD (HHFFFF)
+Size  83: 42,95   GOOD (HHFFFF)
+Size  84: 42,96   GOOD (HHFFFF)
+Size  85: 43,97   GOOD (HHFFFF)
+Size  86: 43,98   GOOD (HHFFFF)
+Size  87: 44,99   GOOD (HHFFFF)
+Size  88: 44,100  GOOD (HHFFFF)
+Size  89: 45,102  GOOD (HHFFFF)
+Size  90: 45,103  GOOD (HHFFFF)
+Size  91: 46,104  GOOD (HHFFFF)
+Size  92: 46,105  GOOD (HHFFFF)
+Size  93: 47,106  GOOD (HHFFFF)
+Size  94: 47,107  GOOD (HHFFFF)
+Size  95: 48,108  GOOD (HHFFFF)
+Size  96: 48,111  GOOD (HHFFFF)
+Size  97: 49,111  GOOD (HHFFFF)
+Size  98: 49,112  GOOD (HHFFFF)
+Size  99: 50,113  GOOD (HHFFFF)
+Size 100: 50,114  GOOD (HHFFFF)
+
+Windows 8.1
+-----------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,9     GOOD (HHFFFF)
+Size   9: 5,10    BAD  (FFHFHH)
+Size  10: 5,11    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,15    BAD  (FFHFHH)
+Size  14: 7,16    GOOD (HHFFFF)
+Size  15: 8,17    BAD  (FFHFHH)
+Size  16: 8,18    GOOD (HHFFFF)
+Size  17: 9,19    BAD  (FFHFHH)
+Size  18: 9,21    GOOD (HHFFFF)
+Size  19: 10,22   BAD  (FFHFHH)
+Size  20: 10,23   GOOD (HHFFFF)
+Size  21: 11,24   BAD  (FFHFHH)
+Size  22: 11,25   GOOD (HHFFFF)
+Size  23: 12,26   BAD  (FFHFHH)
+Size  24: 12,27   GOOD (HHFFFF)
+Size  25: 13,29   BAD  (FFHFHH)
+Size  26: 13,30   GOOD (HHFFFF)
+Size  27: 14,31   BAD  (FFHFHH)
+Size  28: 14,32   GOOD (HHFFFF)
+Size  29: 15,33   BAD  (FFHFHH)
+Size  30: 15,34   GOOD (HHFFFF)
+Size  31: 16,35   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,38   BAD  (FFHFHH)
+Size  34: 17,39   GOOD (HHFFFF)
+Size  35: 18,40   BAD  (FFHFHH)
+Size  36: 18,41   GOOD (HHFFFF)
+Size  37: 19,42   BAD  (FFHFHH)
+Size  38: 19,43   GOOD (HHFFFF)
+Size  39: 20,44   BAD  (FFHFHH)
+Size  40: 20,46   GOOD (HHFFFF)
+Size  41: 21,47   BAD  (FFHFHH)
+Size  42: 21,48   GOOD (HHFFFF)
+Size  43: 22,49   BAD  (FFHFHH)
+Size  44: 22,50   GOOD (HHFFFF)
+Size  45: 23,51   BAD  (FFHFHH)
+Size  46: 23,52   GOOD (HHFFFF)
+Size  47: 24,54   BAD  (FFHFHH)
+Size  48: 24,55   GOOD (HHFFFF)
+Size  49: 25,56   BAD  (FFHFHH)
+Size  50: 25,57   GOOD (HHFFFF)
+Size  51: 26,58   BAD  (FFHFHH)
+Size  52: 26,59   GOOD (HHFFFF)
+Size  53: 27,60   BAD  (FFHFHH)
+Size  54: 27,62   GOOD (HHFFFF)
+Size  55: 28,63   BAD  (FFHFHH)
+Size  56: 28,64   GOOD (HHFFFF)
+Size  57: 29,65   BAD  (FFHFHH)
+Size  58: 29,66   GOOD (HHFFFF)
+Size  59: 30,67   BAD  (FFHFHH)
+Size  60: 30,68   GOOD (HHFFFF)
+Size  61: 31,70   BAD  (FFHFHH)
+Size  62: 31,71   GOOD (HHFFFF)
+Size  63: 32,72   BAD  (FFHFHH)
+Size  64: 32,73   GOOD (HHFFFF)
+Size  65: 33,74   GOOD (HHFFFF)
+Size  66: 33,75   GOOD (HHFFFF)
+Size  67: 34,76   GOOD (HHFFFF)
+Size  68: 34,78   GOOD (HHFFFF)
+Size  69: 35,79   GOOD (HHFFFF)
+Size  70: 35,80   GOOD (HHFFFF)
+Size  71: 36,81   GOOD (HHFFFF)
+Size  72: 36,82   GOOD (HHFFFF)
+Size  73: 37,83   GOOD (HHFFFF)
+Size  74: 37,84   GOOD (HHFFFF)
+Size  75: 38,86   GOOD (HHFFFF)
+Size  76: 38,87   GOOD (HHFFFF)
+Size  77: 39,88   GOOD (HHFFFF)
+Size  78: 39,89   GOOD (HHFFFF)
+Size  79: 40,90   GOOD (HHFFFF)
+Size  80: 40,91   GOOD (HHFFFF)
+Size  81: 41,92   GOOD (HHFFFF)
+Size  82: 41,94   GOOD (HHFFFF)
+Size  83: 42,95   GOOD (HHFFFF)
+Size  84: 42,96   GOOD (HHFFFF)
+Size  85: 43,97   GOOD (HHFFFF)
+Size  86: 43,98   GOOD (HHFFFF)
+Size  87: 44,99   GOOD (HHFFFF)
+Size  88: 44,100  GOOD (HHFFFF)
+Size  89: 45,102  GOOD (HHFFFF)
+Size  90: 45,103  GOOD (HHFFFF)
+Size  91: 46,104  GOOD (HHFFFF)
+Size  92: 46,105  GOOD (HHFFFF)
+Size  93: 47,106  GOOD (HHFFFF)
+Size  94: 47,107  GOOD (HHFFFF)
+Size  95: 48,108  GOOD (HHFFFF)
+Size  96: 48,111  GOOD (HHFFFF)
+Size  97: 49,111  GOOD (HHFFFF)
+Size  98: 49,112  GOOD (HHFFFF)
+Size  99: 50,113  GOOD (HHFFFF)
+Size 100: 50,114  GOOD (HHFFFF)
+
+Windows 10 14342 Old Console
+----------------------------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,9     GOOD (HHFFFF)
+Size   9: 5,10    BAD  (FFHFHH)
+Size  10: 5,11    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,15    BAD  (FFHFHH)
+Size  14: 7,16    GOOD (HHFFFF)
+Size  15: 8,17    BAD  (FFHFHH)
+Size  16: 8,18    GOOD (HHFFFF)
+Size  17: 9,19    BAD  (FFHFHH)
+Size  18: 9,21    GOOD (HHFFFF)
+Size  19: 10,22   BAD  (FFHFHH)
+Size  20: 10,23   GOOD (HHFFFF)
+Size  21: 11,24   BAD  (FFHFHH)
+Size  22: 11,25   GOOD (HHFFFF)
+Size  23: 12,26   BAD  (FFHFHH)
+Size  24: 12,27   GOOD (HHFFFF)
+Size  25: 13,29   BAD  (FFHFHH)
+Size  26: 13,30   GOOD (HHFFFF)
+Size  27: 14,31   BAD  (FFHFHH)
+Size  28: 14,32   GOOD (HHFFFF)
+Size  29: 15,33   BAD  (FFHFHH)
+Size  30: 15,34   GOOD (HHFFFF)
+Size  31: 16,35   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,38   BAD  (FFHFHH)
+Size  34: 17,39   GOOD (HHFFFF)
+Size  35: 18,40   BAD  (FFHFHH)
+Size  36: 18,41   GOOD (HHFFFF)
+Size  37: 19,42   BAD  (FFHFHH)
+Size  38: 19,43   GOOD (HHFFFF)
+Size  39: 20,44   BAD  (FFHFHH)
+Size  40: 20,46   GOOD (HHFFFF)
+Size  41: 21,47   BAD  (FFHFHH)
+Size  42: 21,48   GOOD (HHFFFF)
+Size  43: 22,49   BAD  (FFHFHH)
+Size  44: 22,50   GOOD (HHFFFF)
+Size  45: 23,51   BAD  (FFHFHH)
+Size  46: 23,52   GOOD (HHFFFF)
+Size  47: 24,54   BAD  (FFHFHH)
+Size  48: 24,55   GOOD (HHFFFF)
+Size  49: 25,56   BAD  (FFHFHH)
+Size  50: 25,57   GOOD (HHFFFF)
+Size  51: 26,58   BAD  (FFHFHH)
+Size  52: 26,59   GOOD (HHFFFF)
+Size  53: 27,60   BAD  (FFHFHH)
+Size  54: 27,62   GOOD (HHFFFF)
+Size  55: 28,63   BAD  (FFHFHH)
+Size  56: 28,64   GOOD (HHFFFF)
+Size  57: 29,65   BAD  (FFHFHH)
+Size  58: 29,66   GOOD (HHFFFF)
+Size  59: 30,67   BAD  (FFHFHH)
+Size  60: 30,68   GOOD (HHFFFF)
+Size  61: 31,70   BAD  (FFHFHH)
+Size  62: 31,71   GOOD (HHFFFF)
+Size  63: 32,72   BAD  (FFHFHH)
+Size  64: 32,73   GOOD (HHFFFF)
+Size  65: 33,74   GOOD (HHFFFF)
+Size  66: 33,75   GOOD (HHFFFF)
+Size  67: 34,76   GOOD (HHFFFF)
+Size  68: 34,78   GOOD (HHFFFF)
+Size  69: 35,79   GOOD (HHFFFF)
+Size  70: 35,80   GOOD (HHFFFF)
+Size  71: 36,81   GOOD (HHFFFF)
+Size  72: 36,82   GOOD (HHFFFF)
+Size  73: 37,83   GOOD (HHFFFF)
+Size  74: 37,84   GOOD (HHFFFF)
+Size  75: 38,86   GOOD (HHFFFF)
+Size  76: 38,87   GOOD (HHFFFF)
+Size  77: 39,88   GOOD (HHFFFF)
+Size  78: 39,89   GOOD (HHFFFF)
+Size  79: 40,90   GOOD (HHFFFF)
+Size  80: 40,91   GOOD (HHFFFF)
+Size  81: 41,92   GOOD (HHFFFF)
+Size  82: 41,94   GOOD (HHFFFF)
+Size  83: 42,95   GOOD (HHFFFF)
+Size  84: 42,96   GOOD (HHFFFF)
+Size  85: 43,97   GOOD (HHFFFF)
+Size  86: 43,98   GOOD (HHFFFF)
+Size  87: 44,99   GOOD (HHFFFF)
+Size  88: 44,100  GOOD (HHFFFF)
+Size  89: 45,102  GOOD (HHFFFF)
+Size  90: 45,103  GOOD (HHFFFF)
+Size  91: 46,104  GOOD (HHFFFF)
+Size  92: 46,105  GOOD (HHFFFF)
+Size  93: 47,106  GOOD (HHFFFF)
+Size  94: 47,107  GOOD (HHFFFF)
+Size  95: 48,108  GOOD (HHFFFF)
+Size  96: 48,111  GOOD (HHFFFF)
+Size  97: 49,111  GOOD (HHFFFF)
+Size  98: 49,112  GOOD (HHFFFF)
+Size  99: 50,113  GOOD (HHFFFF)
+Size 100: 50,114  GOOD (HHFFFF)
+
+Windows 10 14342 New Console
+----------------------------
+
+Size   1: 1,1     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     GOOD (HHFFFF)
+Size   4: 2,4     GOOD (HHFFFF)
+Size   5: 3,5     GOOD (HHFFFF)
+Size   6: 3,6     GOOD (HHFFFF)
+Size   7: 4,7     GOOD (HHFFFF)
+Size   8: 4,8     GOOD (HHFFFF)
+Size   9: 5,9     GOOD (HHFFFF)
+Size  10: 5,10    GOOD (HHFFFF)
+Size  11: 6,11    GOOD (HHFFFF)
+Size  12: 6,12    GOOD (HHFFFF)
+Size  13: 7,13    GOOD (HHFFFF)
+Size  14: 7,14    GOOD (HHFFFF)
+Size  15: 8,15    GOOD (HHFFFF)
+Size  16: 8,16    GOOD (HHFFFF)
+Size  17: 9,17    GOOD (HHFFFF)
+Size  18: 9,18    GOOD (HHFFFF)
+Size  19: 10,19   GOOD (HHFFFF)
+Size  20: 10,20   GOOD (HHFFFF)
+Size  21: 11,21   GOOD (HHFFFF)
+Size  22: 11,22   GOOD (HHFFFF)
+Size  23: 12,23   GOOD (HHFFFF)
+Size  24: 12,24   GOOD (HHFFFF)
+Size  25: 13,25   GOOD (HHFFFF)
+Size  26: 13,26   GOOD (HHFFFF)
+Size  27: 14,27   GOOD (HHFFFF)
+Size  28: 14,28   GOOD (HHFFFF)
+Size  29: 15,29   GOOD (HHFFFF)
+Size  30: 15,30   GOOD (HHFFFF)
+Size  31: 16,31   GOOD (HHFFFF)
+Size  32: 16,32   GOOD (HHFFFF)
+Size  33: 17,33   GOOD (HHFFFF)
+Size  34: 17,34   GOOD (HHFFFF)
+Size  35: 18,35   GOOD (HHFFFF)
+Size  36: 18,36   GOOD (HHFFFF)
+Size  37: 19,37   GOOD (HHFFFF)
+Size  38: 19,38   GOOD (HHFFFF)
+Size  39: 20,39   GOOD (HHFFFF)
+Size  40: 20,40   GOOD (HHFFFF)
+Size  41: 21,41   GOOD (HHFFFF)
+Size  42: 21,42   GOOD (HHFFFF)
+Size  43: 22,43   GOOD (HHFFFF)
+Size  44: 22,44   GOOD (HHFFFF)
+Size  45: 23,45   GOOD (HHFFFF)
+Size  46: 23,46   GOOD (HHFFFF)
+Size  47: 24,47   GOOD (HHFFFF)
+Size  48: 24,48   GOOD (HHFFFF)
+Size  49: 25,49   GOOD (HHFFFF)
+Size  50: 25,50   GOOD (HHFFFF)
+Size  51: 26,51   GOOD (HHFFFF)
+Size  52: 26,52   GOOD (HHFFFF)
+Size  53: 27,53   GOOD (HHFFFF)
+Size  54: 27,54   GOOD (HHFFFF)
+Size  55: 28,55   GOOD (HHFFFF)
+Size  56: 28,56   GOOD (HHFFFF)
+Size  57: 29,57   GOOD (HHFFFF)
+Size  58: 29,58   GOOD (HHFFFF)
+Size  59: 30,59   GOOD (HHFFFF)
+Size  60: 30,60   GOOD (HHFFFF)
+Size  61: 31,61   GOOD (HHFFFF)
+Size  62: 31,62   GOOD (HHFFFF)
+Size  63: 32,63   GOOD (HHFFFF)
+Size  64: 32,64   GOOD (HHFFFF)
+Size  65: 33,65   GOOD (HHFFFF)
+Size  66: 33,66   GOOD (HHFFFF)
+Size  67: 34,67   GOOD (HHFFFF)
+Size  68: 34,68   GOOD (HHFFFF)
+Size  69: 35,69   GOOD (HHFFFF)
+Size  70: 35,70   GOOD (HHFFFF)
+Size  71: 36,71   GOOD (HHFFFF)
+Size  72: 36,72   GOOD (HHFFFF)
+Size  73: 37,73   GOOD (HHFFFF)
+Size  74: 37,74   GOOD (HHFFFF)
+Size  75: 38,75   GOOD (HHFFFF)
+Size  76: 38,76   GOOD (HHFFFF)
+Size  77: 39,77   GOOD (HHFFFF)
+Size  78: 39,78   GOOD (HHFFFF)
+Size  79: 40,79   GOOD (HHFFFF)
+Size  80: 40,80   GOOD (HHFFFF)
+Size  81: 41,81   GOOD (HHFFFF)
+Size  82: 41,82   GOOD (HHFFFF)
+Size  83: 42,83   GOOD (HHFFFF)
+Size  84: 42,84   GOOD (HHFFFF)
+Size  85: 43,85   GOOD (HHFFFF)
+Size  86: 43,86   GOOD (HHFFFF)
+Size  87: 44,87   GOOD (HHFFFF)
+Size  88: 44,88   GOOD (HHFFFF)
+Size  89: 45,89   GOOD (HHFFFF)
+Size  90: 45,90   GOOD (HHFFFF)
+Size  91: 46,91   GOOD (HHFFFF)
+Size  92: 46,92   GOOD (HHFFFF)
+Size  93: 47,93   GOOD (HHFFFF)
+Size  94: 47,94   GOOD (HHFFFF)
+Size  95: 48,95   GOOD (HHFFFF)
+Size  96: 48,96   GOOD (HHFFFF)
+Size  97: 49,97   GOOD (HHFFFF)
+Size  98: 49,98   GOOD (HHFFFF)
+Size  99: 50,99   GOOD (HHFFFF)
+Size 100: 50,100  GOOD (HHFFFF)
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP949.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP949.txt
new file mode 100644 (file)
index 0000000..2f0ea1e
--- /dev/null
@@ -0,0 +1,630 @@
+=====================================
+Code Page 949, Korean, GulimChe font
+=====================================
+
+Options: -face-gulimche -family 0x36
+Chars: A2 A3 2014 3044 30FC 4000
+
+Vista
+-----
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,5     OK   (HHHFFF)
+Size   5: 3,6     BAD  (HHHFHH)
+Size   6: 3,7     OK   (HHHFFF)
+Size   7: 4,8     BAD  (HHHFHH)
+Size   8: 4,9     OK   (HHHFFF)
+Size   9: 5,10    BAD  (HHHFHH)
+Size  10: 5,11    OK   (HHHFFF)
+Size  11: 6,13    BAD  (HHHFHH)
+Size  12: 6,14    OK   (HHHFFF)
+Size  13: 7,15    BAD  (HHHFHH)
+Size  14: 7,16    OK   (HHHFFF)
+Size  15: 8,17    BAD  (HHHFHH)
+Size  16: 8,18    OK   (HHHFFF)
+Size  17: 9,20    BAD  (HHHFHH)
+Size  18: 9,21    OK   (HHHFFF)
+Size  19: 10,22   BAD  (HHHFHH)
+Size  20: 10,23   OK   (HHHFFF)
+Size  21: 11,24   BAD  (HHHFHH)
+Size  22: 11,25   OK   (HHHFFF)
+Size  23: 12,26   BAD  (HHHFHH)
+Size  24: 12,28   OK   (HHHFFF)
+Size  25: 13,29   BAD  (HHHFHH)
+Size  26: 13,30   OK   (HHHFFF)
+Size  27: 14,31   BAD  (HHHFHH)
+Size  28: 14,32   OK   (HHHFFF)
+Size  29: 15,33   BAD  (HHHFHH)
+Size  30: 15,34   OK   (HHHFFF)
+Size  31: 16,36   BAD  (HHHFHH)
+Size  32: 16,37   OK   (HHHFFF)
+Size  33: 17,38   BAD  (HHHFHH)
+Size  34: 17,39   OK   (HHHFFF)
+Size  35: 18,40   BAD  (HHHFHH)
+Size  36: 18,41   OK   (HHHFFF)
+Size  37: 19,42   BAD  (HHHFHH)
+Size  38: 19,44   OK   (HHHFFF)
+Size  39: 20,45   BAD  (HHHFHH)
+Size  40: 20,46   OK   (HHHFFF)
+Size  41: 21,47   BAD  (HHHFHH)
+Size  42: 21,48   OK   (HHHFFF)
+Size  43: 22,49   BAD  (HHHFHH)
+Size  44: 22,51   OK   (HHHFFF)
+Size  45: 23,52   BAD  (HHHFHH)
+Size  46: 23,53   OK   (HHHFFF)
+Size  47: 24,54   BAD  (HHHFHH)
+Size  48: 24,55   OK   (HHHFFF)
+Size  49: 25,56   BAD  (HHHFHH)
+Size  50: 25,57   OK   (HHHFFF)
+Size  51: 26,59   BAD  (HHHFHH)
+Size  52: 26,60   OK   (HHHFFF)
+Size  53: 27,61   BAD  (HHHFHH)
+Size  54: 27,62   OK   (HHHFFF)
+Size  55: 28,63   BAD  (HHHFHH)
+Size  56: 28,64   OK   (HHHFFF)
+Size  57: 29,65   BAD  (HHHFHH)
+Size  58: 29,67   OK   (HHHFFF)
+Size  59: 30,68   BAD  (HHHFHH)
+Size  60: 30,69   OK   (HHHFFF)
+Size  61: 31,70   BAD  (HHHFHH)
+Size  62: 31,71   OK   (HHHFFF)
+Size  63: 32,72   BAD  (HHHFHH)
+Size  64: 32,74   OK   (HHHFFF)
+Size  65: 33,75   BAD  (HHHFHH)
+Size  66: 33,76   OK   (HHHFFF)
+Size  67: 34,77   BAD  (HHHFHH)
+Size  68: 34,78   OK   (HHHFFF)
+Size  69: 35,79   BAD  (HHHFHH)
+Size  70: 35,80   OK   (HHHFFF)
+Size  71: 36,82   BAD  (HHHFHH)
+Size  72: 36,83   OK   (HHHFFF)
+Size  73: 37,84   BAD  (HHHFHH)
+Size  74: 37,85   OK   (HHHFFF)
+Size  75: 38,86   BAD  (HHHFHH)
+Size  76: 38,87   OK   (HHHFFF)
+Size  77: 39,88   BAD  (HHHFHH)
+Size  78: 39,90   OK   (HHHFFF)
+Size  79: 40,91   BAD  (HHHFHH)
+Size  80: 40,92   OK   (HHHFFF)
+Size  81: 41,93   BAD  (HHHFHH)
+Size  82: 41,94   OK   (HHHFFF)
+Size  83: 42,95   BAD  (HHHFHH)
+Size  84: 42,96   OK   (HHHFFF)
+Size  85: 43,98   BAD  (HHHFHH)
+Size  86: 43,99   OK   (HHHFFF)
+Size  87: 44,100  BAD  (HHHFHH)
+Size  88: 44,101  OK   (HHHFFF)
+Size  89: 45,102  BAD  (HHHFHH)
+Size  90: 45,103  OK   (HHHFFF)
+Size  91: 46,105  BAD  (HHHFHH)
+Size  92: 46,106  OK   (HHHFFF)
+Size  93: 47,107  BAD  (HHHFHH)
+Size  94: 47,108  OK   (HHHFFF)
+Size  95: 48,109  BAD  (HHHFHH)
+Size  96: 48,110  OK   (HHHFFF)
+Size  97: 49,111  BAD  (HHHFHH)
+Size  98: 49,113  OK   (HHHFFF)
+Size  99: 50,114  BAD  (HHHFHH)
+Size 100: 50,115  OK   (HHHFFF)
+
+Windows 7
+---------
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,5     OK   (HHHFFF)
+Size   5: 3,6     BAD  (FFFFHH)
+Size   6: 3,7     OK   (HHHFFF)
+Size   7: 4,8     BAD  (FFFFHH)
+Size   8: 4,9     OK   (HHHFFF)
+Size   9: 5,10    BAD  (FFFFHH)
+Size  10: 5,11    OK   (HHHFFF)
+Size  11: 6,13    BAD  (FFFFHH)
+Size  12: 6,14    OK   (HHHFFF)
+Size  13: 7,15    BAD  (FFFFHH)
+Size  14: 7,16    OK   (HHHFFF)
+Size  15: 8,17    BAD  (FFFFHH)
+Size  16: 8,18    OK   (HHHFFF)
+Size  17: 9,20    BAD  (FFFFHH)
+Size  18: 9,21    OK   (HHHFFF)
+Size  19: 10,22   BAD  (FFFFHH)
+Size  20: 10,23   OK   (HHHFFF)
+Size  21: 11,24   BAD  (FFFFHH)
+Size  22: 11,25   OK   (HHHFFF)
+Size  23: 12,26   BAD  (FFFFHH)
+Size  24: 12,28   OK   (HHHFFF)
+Size  25: 13,29   BAD  (FFFFHH)
+Size  26: 13,30   OK   (HHHFFF)
+Size  27: 14,31   BAD  (FFFFHH)
+Size  28: 14,32   OK   (HHHFFF)
+Size  29: 15,33   BAD  (FFFFHH)
+Size  30: 15,34   OK   (HHHFFF)
+Size  31: 16,36   BAD  (FFFFHH)
+Size  32: 16,37   OK   (HHHFFF)
+Size  33: 17,38   BAD  (FFFFHH)
+Size  34: 17,39   OK   (HHHFFF)
+Size  35: 18,40   BAD  (FFFFHH)
+Size  36: 18,41   OK   (HHHFFF)
+Size  37: 19,42   BAD  (FFFFHH)
+Size  38: 19,44   OK   (HHHFFF)
+Size  39: 20,45   BAD  (FFFFHH)
+Size  40: 20,46   OK   (HHHFFF)
+Size  41: 21,47   BAD  (FFFFHH)
+Size  42: 21,48   OK   (HHHFFF)
+Size  43: 22,49   BAD  (FFFFHH)
+Size  44: 22,51   OK   (HHHFFF)
+Size  45: 23,52   BAD  (FFFFHH)
+Size  46: 23,53   OK   (HHHFFF)
+Size  47: 24,54   BAD  (FFFFHH)
+Size  48: 24,55   OK   (HHHFFF)
+Size  49: 25,56   BAD  (FFFFHH)
+Size  50: 25,57   OK   (HHHFFF)
+Size  51: 26,59   BAD  (FFFFHH)
+Size  52: 26,60   OK   (HHHFFF)
+Size  53: 27,61   BAD  (FFFFHH)
+Size  54: 27,62   OK   (HHHFFF)
+Size  55: 28,63   BAD  (FFFFHH)
+Size  56: 28,64   OK   (HHHFFF)
+Size  57: 29,65   BAD  (FFFFHH)
+Size  58: 29,67   OK   (HHHFFF)
+Size  59: 30,68   BAD  (FFFFHH)
+Size  60: 30,69   OK   (HHHFFF)
+Size  61: 31,70   BAD  (FFFFHH)
+Size  62: 31,71   OK   (HHHFFF)
+Size  63: 32,72   BAD  (FFFFHH)
+Size  64: 32,74   OK   (HHHFFF)
+Size  65: 33,75   BAD  (FFFFHH)
+Size  66: 33,76   OK   (HHHFFF)
+Size  67: 34,77   BAD  (FFFFHH)
+Size  68: 34,78   OK   (HHHFFF)
+Size  69: 35,79   BAD  (FFFFHH)
+Size  70: 35,80   OK   (HHHFFF)
+Size  71: 36,82   BAD  (FFFFHH)
+Size  72: 36,83   OK   (HHHFFF)
+Size  73: 37,84   BAD  (FFFFHH)
+Size  74: 37,85   OK   (HHHFFF)
+Size  75: 38,86   BAD  (FFFFHH)
+Size  76: 38,87   OK   (HHHFFF)
+Size  77: 39,88   BAD  (FFFFHH)
+Size  78: 39,90   OK   (HHHFFF)
+Size  79: 40,91   BAD  (FFFFHH)
+Size  80: 40,92   OK   (HHHFFF)
+Size  81: 41,93   BAD  (FFFFHH)
+Size  82: 41,94   OK   (HHHFFF)
+Size  83: 42,95   BAD  (FFFFHH)
+Size  84: 42,96   OK   (HHHFFF)
+Size  85: 43,98   BAD  (FFFFHH)
+Size  86: 43,99   OK   (HHHFFF)
+Size  87: 44,100  BAD  (FFFFHH)
+Size  88: 44,101  OK   (HHHFFF)
+Size  89: 45,102  BAD  (FFFFHH)
+Size  90: 45,103  OK   (HHHFFF)
+Size  91: 46,105  BAD  (FFFFHH)
+Size  92: 46,106  OK   (HHHFFF)
+Size  93: 47,107  BAD  (FFFFHH)
+Size  94: 47,108  OK   (HHHFFF)
+Size  95: 48,109  BAD  (FFFFHH)
+Size  96: 48,110  OK   (HHHFFF)
+Size  97: 49,111  BAD  (FFFFHH)
+Size  98: 49,113  OK   (HHHFFF)
+Size  99: 50,114  BAD  (FFFFHH)
+Size 100: 50,115  OK   (HHHFFF)
+
+Windows 8
+---------
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,5     OK   (HHHFFF)
+Size   5: 3,6     BAD  (FFFFHH)
+Size   6: 3,7     OK   (HHHFFF)
+Size   7: 4,8     BAD  (FFFFHH)
+Size   8: 4,9     OK   (HHHFFF)
+Size   9: 5,10    BAD  (FFFFHH)
+Size  10: 5,11    OK   (HHHFFF)
+Size  11: 6,13    BAD  (FFFFHH)
+Size  12: 6,14    OK   (HHHFFF)
+Size  13: 7,15    BAD  (FFFFHH)
+Size  14: 7,16    OK   (HHHFFF)
+Size  15: 8,17    BAD  (FFFFHH)
+Size  16: 8,18    OK   (HHHFFF)
+Size  17: 9,20    BAD  (FFFFHH)
+Size  18: 9,21    OK   (HHHFFF)
+Size  19: 10,22   BAD  (FFFFHH)
+Size  20: 10,23   OK   (HHHFFF)
+Size  21: 11,24   BAD  (FFFFHH)
+Size  22: 11,25   OK   (HHHFFF)
+Size  23: 12,26   BAD  (FFFFHH)
+Size  24: 12,28   OK   (HHHFFF)
+Size  25: 13,29   BAD  (FFFFHH)
+Size  26: 13,30   OK   (HHHFFF)
+Size  27: 14,31   BAD  (FFFFHH)
+Size  28: 14,32   OK   (HHHFFF)
+Size  29: 15,33   BAD  (FFFFHH)
+Size  30: 15,34   OK   (HHHFFF)
+Size  31: 16,36   BAD  (FFFFHH)
+Size  32: 16,37   OK   (HHHFFF)
+Size  33: 17,38   BAD  (FFFFHH)
+Size  34: 17,39   OK   (HHHFFF)
+Size  35: 18,40   BAD  (FFFFHH)
+Size  36: 18,41   OK   (HHHFFF)
+Size  37: 19,42   BAD  (FFFFHH)
+Size  38: 19,44   OK   (HHHFFF)
+Size  39: 20,45   BAD  (FFFFHH)
+Size  40: 20,46   OK   (HHHFFF)
+Size  41: 21,47   BAD  (FFFFHH)
+Size  42: 21,48   OK   (HHHFFF)
+Size  43: 22,49   BAD  (FFFFHH)
+Size  44: 22,51   OK   (HHHFFF)
+Size  45: 23,52   BAD  (FFFFHH)
+Size  46: 23,53   OK   (HHHFFF)
+Size  47: 24,54   BAD  (FFFFHH)
+Size  48: 24,55   OK   (HHHFFF)
+Size  49: 25,56   BAD  (FFFFHH)
+Size  50: 25,57   OK   (HHHFFF)
+Size  51: 26,59   BAD  (FFFFHH)
+Size  52: 26,60   OK   (HHHFFF)
+Size  53: 27,61   BAD  (FFFFHH)
+Size  54: 27,62   OK   (HHHFFF)
+Size  55: 28,63   BAD  (FFFFHH)
+Size  56: 28,64   OK   (HHHFFF)
+Size  57: 29,65   BAD  (FFFFHH)
+Size  58: 29,67   OK   (HHHFFF)
+Size  59: 30,68   BAD  (FFFFHH)
+Size  60: 30,69   OK   (HHHFFF)
+Size  61: 31,70   BAD  (FFFFHH)
+Size  62: 31,71   OK   (HHHFFF)
+Size  63: 32,72   BAD  (FFFFHH)
+Size  64: 32,74   OK   (HHHFFF)
+Size  65: 33,75   BAD  (FFFFHH)
+Size  66: 33,76   OK   (HHHFFF)
+Size  67: 34,77   BAD  (FFFFHH)
+Size  68: 34,78   OK   (HHHFFF)
+Size  69: 35,79   BAD  (FFFFHH)
+Size  70: 35,80   OK   (HHHFFF)
+Size  71: 36,82   BAD  (FFFFHH)
+Size  72: 36,83   OK   (HHHFFF)
+Size  73: 37,84   BAD  (FFFFHH)
+Size  74: 37,85   OK   (HHHFFF)
+Size  75: 38,86   BAD  (FFFFHH)
+Size  76: 38,87   OK   (HHHFFF)
+Size  77: 39,88   BAD  (FFFFHH)
+Size  78: 39,90   OK   (HHHFFF)
+Size  79: 40,91   BAD  (FFFFHH)
+Size  80: 40,92   OK   (HHHFFF)
+Size  81: 41,93   BAD  (FFFFHH)
+Size  82: 41,94   OK   (HHHFFF)
+Size  83: 42,95   BAD  (FFFFHH)
+Size  84: 42,96   OK   (HHHFFF)
+Size  85: 43,98   BAD  (FFFFHH)
+Size  86: 43,99   OK   (HHHFFF)
+Size  87: 44,100  BAD  (FFFFHH)
+Size  88: 44,101  OK   (HHHFFF)
+Size  89: 45,102  BAD  (FFFFHH)
+Size  90: 45,103  OK   (HHHFFF)
+Size  91: 46,105  BAD  (FFFFHH)
+Size  92: 46,106  OK   (HHHFFF)
+Size  93: 47,107  BAD  (FFFFHH)
+Size  94: 47,108  OK   (HHHFFF)
+Size  95: 48,109  BAD  (FFFFHH)
+Size  96: 48,110  OK   (HHHFFF)
+Size  97: 49,111  BAD  (FFFFHH)
+Size  98: 49,113  OK   (HHHFFF)
+Size  99: 50,114  BAD  (FFFFHH)
+Size 100: 50,115  OK   (HHHFFF)
+
+Windows 8.1
+-----------
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,5     OK   (HHHFFF)
+Size   5: 3,6     BAD  (FFFFHH)
+Size   6: 3,7     OK   (HHHFFF)
+Size   7: 4,8     BAD  (FFFFHH)
+Size   8: 4,9     OK   (HHHFFF)
+Size   9: 5,10    BAD  (FFFFHH)
+Size  10: 5,11    OK   (HHHFFF)
+Size  11: 6,13    BAD  (FFFFHH)
+Size  12: 6,14    OK   (HHHFFF)
+Size  13: 7,15    BAD  (FFFFHH)
+Size  14: 7,16    OK   (HHHFFF)
+Size  15: 8,17    BAD  (FFFFHH)
+Size  16: 8,18    OK   (HHHFFF)
+Size  17: 9,20    BAD  (FFFFHH)
+Size  18: 9,21    OK   (HHHFFF)
+Size  19: 10,22   BAD  (FFFFHH)
+Size  20: 10,23   OK   (HHHFFF)
+Size  21: 11,24   BAD  (FFFFHH)
+Size  22: 11,25   OK   (HHHFFF)
+Size  23: 12,26   BAD  (FFFFHH)
+Size  24: 12,28   OK   (HHHFFF)
+Size  25: 13,29   BAD  (FFFFHH)
+Size  26: 13,30   OK   (HHHFFF)
+Size  27: 14,31   BAD  (FFFFHH)
+Size  28: 14,32   OK   (HHHFFF)
+Size  29: 15,33   BAD  (FFFFHH)
+Size  30: 15,34   OK   (HHHFFF)
+Size  31: 16,36   BAD  (FFFFHH)
+Size  32: 16,37   OK   (HHHFFF)
+Size  33: 17,38   BAD  (FFFFHH)
+Size  34: 17,39   OK   (HHHFFF)
+Size  35: 18,40   BAD  (FFFFHH)
+Size  36: 18,41   OK   (HHHFFF)
+Size  37: 19,42   BAD  (FFFFHH)
+Size  38: 19,44   OK   (HHHFFF)
+Size  39: 20,45   BAD  (FFFFHH)
+Size  40: 20,46   OK   (HHHFFF)
+Size  41: 21,47   BAD  (FFFFHH)
+Size  42: 21,48   OK   (HHHFFF)
+Size  43: 22,49   BAD  (FFFFHH)
+Size  44: 22,51   OK   (HHHFFF)
+Size  45: 23,52   BAD  (FFFFHH)
+Size  46: 23,53   OK   (HHHFFF)
+Size  47: 24,54   BAD  (FFFFHH)
+Size  48: 24,55   OK   (HHHFFF)
+Size  49: 25,56   BAD  (FFFFHH)
+Size  50: 25,57   OK   (HHHFFF)
+Size  51: 26,59   BAD  (FFFFHH)
+Size  52: 26,60   OK   (HHHFFF)
+Size  53: 27,61   BAD  (FFFFHH)
+Size  54: 27,62   OK   (HHHFFF)
+Size  55: 28,63   BAD  (FFFFHH)
+Size  56: 28,64   OK   (HHHFFF)
+Size  57: 29,65   BAD  (FFFFHH)
+Size  58: 29,67   OK   (HHHFFF)
+Size  59: 30,68   BAD  (FFFFHH)
+Size  60: 30,69   OK   (HHHFFF)
+Size  61: 31,70   BAD  (FFFFHH)
+Size  62: 31,71   OK   (HHHFFF)
+Size  63: 32,72   BAD  (FFFFHH)
+Size  64: 32,74   OK   (HHHFFF)
+Size  65: 33,75   BAD  (FFFFHH)
+Size  66: 33,76   OK   (HHHFFF)
+Size  67: 34,77   BAD  (FFFFHH)
+Size  68: 34,78   OK   (HHHFFF)
+Size  69: 35,79   BAD  (FFFFHH)
+Size  70: 35,80   OK   (HHHFFF)
+Size  71: 36,82   BAD  (FFFFHH)
+Size  72: 36,83   OK   (HHHFFF)
+Size  73: 37,84   BAD  (FFFFHH)
+Size  74: 37,85   OK   (HHHFFF)
+Size  75: 38,86   BAD  (FFFFHH)
+Size  76: 38,87   OK   (HHHFFF)
+Size  77: 39,88   BAD  (FFFFHH)
+Size  78: 39,90   OK   (HHHFFF)
+Size  79: 40,91   BAD  (FFFFHH)
+Size  80: 40,92   OK   (HHHFFF)
+Size  81: 41,93   BAD  (FFFFHH)
+Size  82: 41,94   OK   (HHHFFF)
+Size  83: 42,95   BAD  (FFFFHH)
+Size  84: 42,96   OK   (HHHFFF)
+Size  85: 43,98   BAD  (FFFFHH)
+Size  86: 43,99   OK   (HHHFFF)
+Size  87: 44,100  BAD  (FFFFHH)
+Size  88: 44,101  OK   (HHHFFF)
+Size  89: 45,102  BAD  (FFFFHH)
+Size  90: 45,103  OK   (HHHFFF)
+Size  91: 46,105  BAD  (FFFFHH)
+Size  92: 46,106  OK   (HHHFFF)
+Size  93: 47,107  BAD  (FFFFHH)
+Size  94: 47,108  OK   (HHHFFF)
+Size  95: 48,109  BAD  (FFFFHH)
+Size  96: 48,110  OK   (HHHFFF)
+Size  97: 49,111  BAD  (FFFFHH)
+Size  98: 49,113  OK   (HHHFFF)
+Size  99: 50,114  BAD  (FFFFHH)
+Size 100: 50,115  OK   (HHHFFF)
+
+Windows 10 14342 Old Console
+----------------------------
+
+Size   1: 1,2     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     BAD  (FFFFHH)
+Size   4: 2,5     OK   (HHHFFF)
+Size   5: 3,6     BAD  (FFFFHH)
+Size   6: 3,7     OK   (HHHFFF)
+Size   7: 4,8     BAD  (FFFFHH)
+Size   8: 4,9     OK   (HHHFFF)
+Size   9: 5,10    BAD  (FFFFHH)
+Size  10: 5,11    OK   (HHHFFF)
+Size  11: 6,13    BAD  (FFFFHH)
+Size  12: 6,14    OK   (HHHFFF)
+Size  13: 7,15    BAD  (FFFFHH)
+Size  14: 7,16    OK   (HHHFFF)
+Size  15: 8,17    BAD  (FFFFHH)
+Size  16: 8,18    OK   (HHHFFF)
+Size  17: 9,20    BAD  (FFFFHH)
+Size  18: 9,21    OK   (HHHFFF)
+Size  19: 10,22   BAD  (FFFFHH)
+Size  20: 10,23   OK   (HHHFFF)
+Size  21: 11,24   BAD  (FFFFHH)
+Size  22: 11,25   OK   (HHHFFF)
+Size  23: 12,26   BAD  (FFFFHH)
+Size  24: 12,28   OK   (HHHFFF)
+Size  25: 13,29   BAD  (FFFFHH)
+Size  26: 13,30   OK   (HHHFFF)
+Size  27: 14,31   BAD  (FFFFHH)
+Size  28: 14,32   OK   (HHHFFF)
+Size  29: 15,33   BAD  (FFFFHH)
+Size  30: 15,34   OK   (HHHFFF)
+Size  31: 16,36   BAD  (FFFFHH)
+Size  32: 16,37   OK   (HHHFFF)
+Size  33: 17,38   BAD  (FFFFHH)
+Size  34: 17,39   OK   (HHHFFF)
+Size  35: 18,40   BAD  (FFFFHH)
+Size  36: 18,41   OK   (HHHFFF)
+Size  37: 19,42   BAD  (FFFFHH)
+Size  38: 19,44   OK   (HHHFFF)
+Size  39: 20,45   BAD  (FFFFHH)
+Size  40: 20,46   OK   (HHHFFF)
+Size  41: 21,47   BAD  (FFFFHH)
+Size  42: 21,48   OK   (HHHFFF)
+Size  43: 22,49   BAD  (FFFFHH)
+Size  44: 22,51   OK   (HHHFFF)
+Size  45: 23,52   BAD  (FFFFHH)
+Size  46: 23,53   OK   (HHHFFF)
+Size  47: 24,54   BAD  (FFFFHH)
+Size  48: 24,55   OK   (HHHFFF)
+Size  49: 25,56   BAD  (FFFFHH)
+Size  50: 25,57   OK   (HHHFFF)
+Size  51: 26,59   BAD  (FFFFHH)
+Size  52: 26,60   OK   (HHHFFF)
+Size  53: 27,61   BAD  (FFFFHH)
+Size  54: 27,62   OK   (HHHFFF)
+Size  55: 28,63   BAD  (FFFFHH)
+Size  56: 28,64   OK   (HHHFFF)
+Size  57: 29,65   BAD  (FFFFHH)
+Size  58: 29,67   OK   (HHHFFF)
+Size  59: 30,68   BAD  (FFFFHH)
+Size  60: 30,69   OK   (HHHFFF)
+Size  61: 31,70   BAD  (FFFFHH)
+Size  62: 31,71   OK   (HHHFFF)
+Size  63: 32,72   BAD  (FFFFHH)
+Size  64: 32,74   OK   (HHHFFF)
+Size  65: 33,75   BAD  (FFFFHH)
+Size  66: 33,76   OK   (HHHFFF)
+Size  67: 34,77   BAD  (FFFFHH)
+Size  68: 34,78   OK   (HHHFFF)
+Size  69: 35,79   BAD  (FFFFHH)
+Size  70: 35,80   OK   (HHHFFF)
+Size  71: 36,82   BAD  (FFFFHH)
+Size  72: 36,83   OK   (HHHFFF)
+Size  73: 37,84   BAD  (FFFFHH)
+Size  74: 37,85   OK   (HHHFFF)
+Size  75: 38,86   BAD  (FFFFHH)
+Size  76: 38,87   OK   (HHHFFF)
+Size  77: 39,88   BAD  (FFFFHH)
+Size  78: 39,90   OK   (HHHFFF)
+Size  79: 40,91   BAD  (FFFFHH)
+Size  80: 40,92   OK   (HHHFFF)
+Size  81: 41,93   BAD  (FFFFHH)
+Size  82: 41,94   OK   (HHHFFF)
+Size  83: 42,95   BAD  (FFFFHH)
+Size  84: 42,96   OK   (HHHFFF)
+Size  85: 43,98   BAD  (FFFFHH)
+Size  86: 43,99   OK   (HHHFFF)
+Size  87: 44,100  BAD  (FFFFHH)
+Size  88: 44,101  OK   (HHHFFF)
+Size  89: 45,102  BAD  (FFFFHH)
+Size  90: 45,103  OK   (HHHFFF)
+Size  91: 46,105  BAD  (FFFFHH)
+Size  92: 46,106  OK   (HHHFFF)
+Size  93: 47,107  BAD  (FFFFHH)
+Size  94: 47,108  OK   (HHHFFF)
+Size  95: 48,109  BAD  (FFFFHH)
+Size  96: 48,110  OK   (HHHFFF)
+Size  97: 49,111  BAD  (FFFFHH)
+Size  98: 49,113  OK   (HHHFFF)
+Size  99: 50,114  BAD  (FFFFHH)
+Size 100: 50,115  OK   (HHHFFF)
+
+Windows 10 14342 New Console
+----------------------------
+
+Size   1: 1,1     OK   (HHHFFF)
+Size   2: 1,2     OK   (HHHFFF)
+Size   3: 2,3     OK   (HHHFFF)
+Size   4: 2,4     OK   (HHHFFF)
+Size   5: 3,5     OK   (HHHFFF)
+Size   6: 3,6     OK   (HHHFFF)
+Size   7: 4,7     OK   (HHHFFF)
+Size   8: 4,8     OK   (HHHFFF)
+Size   9: 5,9     OK   (HHHFFF)
+Size  10: 5,10    OK   (HHHFFF)
+Size  11: 6,11    OK   (HHHFFF)
+Size  12: 6,12    OK   (HHHFFF)
+Size  13: 7,13    OK   (HHHFFF)
+Size  14: 7,14    OK   (HHHFFF)
+Size  15: 8,15    OK   (HHHFFF)
+Size  16: 8,16    OK   (HHHFFF)
+Size  17: 9,17    OK   (HHHFFF)
+Size  18: 9,18    OK   (HHHFFF)
+Size  19: 10,19   OK   (HHHFFF)
+Size  20: 10,20   OK   (HHHFFF)
+Size  21: 11,21   OK   (HHHFFF)
+Size  22: 11,22   OK   (HHHFFF)
+Size  23: 12,23   OK   (HHHFFF)
+Size  24: 12,24   OK   (HHHFFF)
+Size  25: 13,25   OK   (HHHFFF)
+Size  26: 13,26   OK   (HHHFFF)
+Size  27: 14,27   OK   (HHHFFF)
+Size  28: 14,28   OK   (HHHFFF)
+Size  29: 15,29   OK   (HHHFFF)
+Size  30: 15,30   OK   (HHHFFF)
+Size  31: 16,31   OK   (HHHFFF)
+Size  32: 16,32   OK   (HHHFFF)
+Size  33: 17,33   OK   (HHHFFF)
+Size  34: 17,34   OK   (HHHFFF)
+Size  35: 18,35   OK   (HHHFFF)
+Size  36: 18,36   OK   (HHHFFF)
+Size  37: 19,37   OK   (HHHFFF)
+Size  38: 19,38   OK   (HHHFFF)
+Size  39: 20,39   OK   (HHHFFF)
+Size  40: 20,40   OK   (HHHFFF)
+Size  41: 21,41   OK   (HHHFFF)
+Size  42: 21,42   OK   (HHHFFF)
+Size  43: 22,43   OK   (HHHFFF)
+Size  44: 22,44   OK   (HHHFFF)
+Size  45: 23,45   OK   (HHHFFF)
+Size  46: 23,46   OK   (HHHFFF)
+Size  47: 24,47   OK   (HHHFFF)
+Size  48: 24,48   OK   (HHHFFF)
+Size  49: 25,49   OK   (HHHFFF)
+Size  50: 25,50   OK   (HHHFFF)
+Size  51: 26,51   OK   (HHHFFF)
+Size  52: 26,52   OK   (HHHFFF)
+Size  53: 27,53   OK   (HHHFFF)
+Size  54: 27,54   OK   (HHHFFF)
+Size  55: 28,55   OK   (HHHFFF)
+Size  56: 28,56   OK   (HHHFFF)
+Size  57: 29,57   OK   (HHHFFF)
+Size  58: 29,58   OK   (HHHFFF)
+Size  59: 30,59   OK   (HHHFFF)
+Size  60: 30,60   OK   (HHHFFF)
+Size  61: 31,61   OK   (HHHFFF)
+Size  62: 31,62   OK   (HHHFFF)
+Size  63: 32,63   OK   (HHHFFF)
+Size  64: 32,64   OK   (HHHFFF)
+Size  65: 33,65   OK   (HHHFFF)
+Size  66: 33,66   OK   (HHHFFF)
+Size  67: 34,67   OK   (HHHFFF)
+Size  68: 34,68   OK   (HHHFFF)
+Size  69: 35,69   OK   (HHHFFF)
+Size  70: 35,70   OK   (HHHFFF)
+Size  71: 36,71   OK   (HHHFFF)
+Size  72: 36,72   OK   (HHHFFF)
+Size  73: 37,73   OK   (HHHFFF)
+Size  74: 37,74   OK   (HHHFFF)
+Size  75: 38,75   OK   (HHHFFF)
+Size  76: 38,76   OK   (HHHFFF)
+Size  77: 39,77   OK   (HHHFFF)
+Size  78: 39,78   OK   (HHHFFF)
+Size  79: 40,79   OK   (HHHFFF)
+Size  80: 40,80   OK   (HHHFFF)
+Size  81: 41,81   OK   (HHHFFF)
+Size  82: 41,82   OK   (HHHFFF)
+Size  83: 42,83   OK   (HHHFFF)
+Size  84: 42,84   OK   (HHHFFF)
+Size  85: 43,85   OK   (HHHFFF)
+Size  86: 43,86   OK   (HHHFFF)
+Size  87: 44,87   OK   (HHHFFF)
+Size  88: 44,88   OK   (HHHFFF)
+Size  89: 45,89   OK   (HHHFFF)
+Size  90: 45,90   OK   (HHHFFF)
+Size  91: 46,91   OK   (HHHFFF)
+Size  92: 46,92   OK   (HHHFFF)
+Size  93: 47,93   OK   (HHHFFF)
+Size  94: 47,94   OK   (HHHFFF)
+Size  95: 48,95   OK   (HHHFFF)
+Size  96: 48,96   OK   (HHHFFF)
+Size  97: 49,97   OK   (HHHFFF)
+Size  98: 49,98   OK   (HHHFFF)
+Size  99: 50,99   OK   (HHHFFF)
+Size 100: 50,100  OK   (HHHFFF)
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP950.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/CP950.txt
new file mode 100644 (file)
index 0000000..0dbade5
--- /dev/null
@@ -0,0 +1,630 @@
+===========================================================
+Code Page 950, Chinese Traditional (Taiwan), MingLight font
+===========================================================
+
+Options: -face-minglight -family 0x36
+Chars: A2 A3 2014 3044 30FC 4000
+
+Vista
+-----
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,4     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (HHHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (HHHFHH)
+Size   8: 4,10    GOOD (HHFFFF)
+Size   9: 5,11    BAD  (HHHFHH)
+Size  10: 5,12    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (HHHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,16    BAD  (HHHFHH)
+Size  14: 7,17    GOOD (HHFFFF)
+Size  15: 8,18    BAD  (HHHFHH)
+Size  16: 8,19    GOOD (HHFFFF)
+Size  17: 9,20    BAD  (HHHFHH)
+Size  18: 9,22    GOOD (HHFFFF)
+Size  19: 10,23   BAD  (HHHFHH)
+Size  20: 10,24   GOOD (HHFFFF)
+Size  21: 11,25   BAD  (HHHFHH)
+Size  22: 11,26   GOOD (HHFFFF)
+Size  23: 12,28   BAD  (HHHFHH)
+Size  24: 12,29   GOOD (HHFFFF)
+Size  25: 13,30   BAD  (HHHFHH)
+Size  26: 13,31   GOOD (HHFFFF)
+Size  27: 14,32   BAD  (HHHFHH)
+Size  28: 14,34   GOOD (HHFFFF)
+Size  29: 15,35   BAD  (HHHFHH)
+Size  30: 15,36   GOOD (HHFFFF)
+Size  31: 16,37   BAD  (HHHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,40   BAD  (HHHFHH)
+Size  34: 17,41   GOOD (HHFFFF)
+Size  35: 18,42   BAD  (HHHFHH)
+Size  36: 18,43   GOOD (HHFFFF)
+Size  37: 19,44   BAD  (HHHFHH)
+Size  38: 19,46   GOOD (HHFFFF)
+Size  39: 20,47   BAD  (HHHFHH)
+Size  40: 20,48   GOOD (HHFFFF)
+Size  41: 21,49   BAD  (HHHFHH)
+Size  42: 21,50   GOOD (HHFFFF)
+Size  43: 22,52   BAD  (HHHFHH)
+Size  44: 22,53   GOOD (HHFFFF)
+Size  45: 23,54   BAD  (HHHFHH)
+Size  46: 23,55   GOOD (HHFFFF)
+Size  47: 24,56   BAD  (HHHFHH)
+Size  48: 24,58   GOOD (HHFFFF)
+Size  49: 25,59   BAD  (HHHFHH)
+Size  50: 25,60   GOOD (HHFFFF)
+Size  51: 26,61   BAD  (HHHFHH)
+Size  52: 26,62   GOOD (HHFFFF)
+Size  53: 27,64   BAD  (HHHFHH)
+Size  54: 27,65   GOOD (HHFFFF)
+Size  55: 28,66   BAD  (HHHFHH)
+Size  56: 28,67   GOOD (HHFFFF)
+Size  57: 29,68   BAD  (HHHFHH)
+Size  58: 29,70   GOOD (HHFFFF)
+Size  59: 30,71   BAD  (HHHFHH)
+Size  60: 30,72   GOOD (HHFFFF)
+Size  61: 31,73   BAD  (HHHFHH)
+Size  62: 31,74   GOOD (HHFFFF)
+Size  63: 32,76   BAD  (HHHFHH)
+Size  64: 32,77   GOOD (HHFFFF)
+Size  65: 33,78   BAD  (HHHFHH)
+Size  66: 33,79   GOOD (HHFFFF)
+Size  67: 34,80   BAD  (HHHFHH)
+Size  68: 34,82   GOOD (HHFFFF)
+Size  69: 35,83   BAD  (HHHFHH)
+Size  70: 35,84   GOOD (HHFFFF)
+Size  71: 36,85   BAD  (HHHFHH)
+Size  72: 36,86   GOOD (HHFFFF)
+Size  73: 37,88   BAD  (HHHFHH)
+Size  74: 37,89   GOOD (HHFFFF)
+Size  75: 38,90   BAD  (HHHFHH)
+Size  76: 38,91   GOOD (HHFFFF)
+Size  77: 39,92   BAD  (HHHFHH)
+Size  78: 39,94   GOOD (HHFFFF)
+Size  79: 40,95   BAD  (HHHFHH)
+Size  80: 40,96   GOOD (HHFFFF)
+Size  81: 41,97   BAD  (HHHFHH)
+Size  82: 41,98   GOOD (HHFFFF)
+Size  83: 42,100  BAD  (HHHFHH)
+Size  84: 42,101  GOOD (HHFFFF)
+Size  85: 43,102  BAD  (HHHFHH)
+Size  86: 43,103  GOOD (HHFFFF)
+Size  87: 44,104  BAD  (HHHFHH)
+Size  88: 44,106  GOOD (HHFFFF)
+Size  89: 45,107  BAD  (HHHFHH)
+Size  90: 45,108  GOOD (HHFFFF)
+Size  91: 46,109  BAD  (HHHFHH)
+Size  92: 46,110  GOOD (HHFFFF)
+Size  93: 47,112  BAD  (HHHFHH)
+Size  94: 47,113  GOOD (HHFFFF)
+Size  95: 48,114  BAD  (HHHFHH)
+Size  96: 48,115  GOOD (HHFFFF)
+Size  97: 49,116  BAD  (HHHFHH)
+Size  98: 49,118  GOOD (HHFFFF)
+Size  99: 50,119  BAD  (HHHFHH)
+Size 100: 50,120  GOOD (HHFFFF)
+
+Windows 7
+---------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,4     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,10    GOOD (HHFFFF)
+Size   9: 5,11    BAD  (FFHFHH)
+Size  10: 5,12    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,16    BAD  (FFHFHH)
+Size  14: 7,17    GOOD (HHFFFF)
+Size  15: 8,18    BAD  (FFHFHH)
+Size  16: 8,19    GOOD (HHFFFF)
+Size  17: 9,20    BAD  (FFHFHH)
+Size  18: 9,22    GOOD (HHFFFF)
+Size  19: 10,23   BAD  (FFHFHH)
+Size  20: 10,24   GOOD (HHFFFF)
+Size  21: 11,25   BAD  (FFHFHH)
+Size  22: 11,26   GOOD (HHFFFF)
+Size  23: 12,28   BAD  (FFHFHH)
+Size  24: 12,29   GOOD (HHFFFF)
+Size  25: 13,30   BAD  (FFHFHH)
+Size  26: 13,31   GOOD (HHFFFF)
+Size  27: 14,32   BAD  (FFHFHH)
+Size  28: 14,34   GOOD (HHFFFF)
+Size  29: 15,35   BAD  (FFHFHH)
+Size  30: 15,36   GOOD (HHFFFF)
+Size  31: 16,37   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,40   BAD  (FFHFHH)
+Size  34: 17,41   GOOD (HHFFFF)
+Size  35: 18,42   BAD  (FFHFHH)
+Size  36: 18,43   GOOD (HHFFFF)
+Size  37: 19,44   BAD  (FFHFHH)
+Size  38: 19,46   GOOD (HHFFFF)
+Size  39: 20,47   BAD  (FFHFHH)
+Size  40: 20,48   GOOD (HHFFFF)
+Size  41: 21,49   BAD  (FFHFHH)
+Size  42: 21,50   GOOD (HHFFFF)
+Size  43: 22,52   BAD  (FFHFHH)
+Size  44: 22,53   GOOD (HHFFFF)
+Size  45: 23,54   BAD  (FFHFHH)
+Size  46: 23,55   GOOD (HHFFFF)
+Size  47: 24,56   BAD  (FFHFHH)
+Size  48: 24,58   GOOD (HHFFFF)
+Size  49: 25,59   BAD  (FFHFHH)
+Size  50: 25,60   GOOD (HHFFFF)
+Size  51: 26,61   BAD  (FFHFHH)
+Size  52: 26,62   GOOD (HHFFFF)
+Size  53: 27,64   BAD  (FFHFHH)
+Size  54: 27,65   GOOD (HHFFFF)
+Size  55: 28,66   BAD  (FFHFHH)
+Size  56: 28,67   GOOD (HHFFFF)
+Size  57: 29,68   BAD  (FFHFHH)
+Size  58: 29,70   GOOD (HHFFFF)
+Size  59: 30,71   BAD  (FFHFHH)
+Size  60: 30,72   GOOD (HHFFFF)
+Size  61: 31,73   BAD  (FFHFHH)
+Size  62: 31,74   GOOD (HHFFFF)
+Size  63: 32,76   BAD  (FFHFHH)
+Size  64: 32,77   GOOD (HHFFFF)
+Size  65: 33,78   BAD  (FFHFHH)
+Size  66: 33,79   GOOD (HHFFFF)
+Size  67: 34,80   BAD  (FFHFHH)
+Size  68: 34,82   GOOD (HHFFFF)
+Size  69: 35,83   BAD  (FFHFHH)
+Size  70: 35,84   GOOD (HHFFFF)
+Size  71: 36,85   BAD  (FFHFHH)
+Size  72: 36,86   GOOD (HHFFFF)
+Size  73: 37,88   BAD  (FFHFHH)
+Size  74: 37,89   GOOD (HHFFFF)
+Size  75: 38,90   BAD  (FFHFHH)
+Size  76: 38,91   GOOD (HHFFFF)
+Size  77: 39,92   BAD  (FFHFHH)
+Size  78: 39,94   GOOD (HHFFFF)
+Size  79: 40,95   BAD  (FFHFHH)
+Size  80: 40,96   GOOD (HHFFFF)
+Size  81: 41,97   BAD  (FFHFHH)
+Size  82: 41,98   GOOD (HHFFFF)
+Size  83: 42,100  BAD  (FFHFHH)
+Size  84: 42,101  GOOD (HHFFFF)
+Size  85: 43,102  BAD  (FFHFHH)
+Size  86: 43,103  GOOD (HHFFFF)
+Size  87: 44,104  BAD  (FFHFHH)
+Size  88: 44,106  GOOD (HHFFFF)
+Size  89: 45,107  BAD  (FFHFHH)
+Size  90: 45,108  GOOD (HHFFFF)
+Size  91: 46,109  BAD  (FFHFHH)
+Size  92: 46,110  GOOD (HHFFFF)
+Size  93: 47,112  BAD  (FFHFHH)
+Size  94: 47,113  GOOD (HHFFFF)
+Size  95: 48,114  BAD  (FFHFHH)
+Size  96: 48,115  GOOD (HHFFFF)
+Size  97: 49,116  BAD  (FFHFHH)
+Size  98: 49,118  GOOD (HHFFFF)
+Size  99: 50,119  BAD  (FFHFHH)
+Size 100: 50,120  GOOD (HHFFFF)
+
+Windows 8
+---------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,4     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,10    GOOD (HHFFFF)
+Size   9: 5,11    BAD  (FFHFHH)
+Size  10: 5,12    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,16    BAD  (FFHFHH)
+Size  14: 7,17    GOOD (HHFFFF)
+Size  15: 8,18    BAD  (FFHFHH)
+Size  16: 8,19    GOOD (HHFFFF)
+Size  17: 9,20    BAD  (FFHFHH)
+Size  18: 9,22    GOOD (HHFFFF)
+Size  19: 10,23   BAD  (FFHFHH)
+Size  20: 10,24   GOOD (HHFFFF)
+Size  21: 11,25   BAD  (FFHFHH)
+Size  22: 11,26   GOOD (HHFFFF)
+Size  23: 12,28   BAD  (FFHFHH)
+Size  24: 12,29   GOOD (HHFFFF)
+Size  25: 13,30   BAD  (FFHFHH)
+Size  26: 13,31   GOOD (HHFFFF)
+Size  27: 14,32   BAD  (FFHFHH)
+Size  28: 14,34   GOOD (HHFFFF)
+Size  29: 15,35   BAD  (FFHFHH)
+Size  30: 15,36   GOOD (HHFFFF)
+Size  31: 16,37   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,40   BAD  (FFHFHH)
+Size  34: 17,41   GOOD (HHFFFF)
+Size  35: 18,42   BAD  (FFHFHH)
+Size  36: 18,43   GOOD (HHFFFF)
+Size  37: 19,44   BAD  (FFHFHH)
+Size  38: 19,46   GOOD (HHFFFF)
+Size  39: 20,47   BAD  (FFHFHH)
+Size  40: 20,48   GOOD (HHFFFF)
+Size  41: 21,49   BAD  (FFHFHH)
+Size  42: 21,50   GOOD (HHFFFF)
+Size  43: 22,52   BAD  (FFHFHH)
+Size  44: 22,53   GOOD (HHFFFF)
+Size  45: 23,54   BAD  (FFHFHH)
+Size  46: 23,55   GOOD (HHFFFF)
+Size  47: 24,56   BAD  (FFHFHH)
+Size  48: 24,58   GOOD (HHFFFF)
+Size  49: 25,59   BAD  (FFHFHH)
+Size  50: 25,60   GOOD (HHFFFF)
+Size  51: 26,61   BAD  (FFHFHH)
+Size  52: 26,62   GOOD (HHFFFF)
+Size  53: 27,64   BAD  (FFHFHH)
+Size  54: 27,65   GOOD (HHFFFF)
+Size  55: 28,66   BAD  (FFHFHH)
+Size  56: 28,67   GOOD (HHFFFF)
+Size  57: 29,68   BAD  (FFHFHH)
+Size  58: 29,70   GOOD (HHFFFF)
+Size  59: 30,71   BAD  (FFHFHH)
+Size  60: 30,72   GOOD (HHFFFF)
+Size  61: 31,73   BAD  (FFHFHH)
+Size  62: 31,74   GOOD (HHFFFF)
+Size  63: 32,76   BAD  (FFHFHH)
+Size  64: 32,77   GOOD (HHFFFF)
+Size  65: 33,78   BAD  (FFHFHH)
+Size  66: 33,79   GOOD (HHFFFF)
+Size  67: 34,80   BAD  (FFHFHH)
+Size  68: 34,82   GOOD (HHFFFF)
+Size  69: 35,83   BAD  (FFHFHH)
+Size  70: 35,84   GOOD (HHFFFF)
+Size  71: 36,85   BAD  (FFHFHH)
+Size  72: 36,86   GOOD (HHFFFF)
+Size  73: 37,88   BAD  (FFHFHH)
+Size  74: 37,89   GOOD (HHFFFF)
+Size  75: 38,90   BAD  (FFHFHH)
+Size  76: 38,91   GOOD (HHFFFF)
+Size  77: 39,92   BAD  (FFHFHH)
+Size  78: 39,94   GOOD (HHFFFF)
+Size  79: 40,95   BAD  (FFHFHH)
+Size  80: 40,96   GOOD (HHFFFF)
+Size  81: 41,97   BAD  (FFHFHH)
+Size  82: 41,98   GOOD (HHFFFF)
+Size  83: 42,100  BAD  (FFHFHH)
+Size  84: 42,101  GOOD (HHFFFF)
+Size  85: 43,102  BAD  (FFHFHH)
+Size  86: 43,103  GOOD (HHFFFF)
+Size  87: 44,104  BAD  (FFHFHH)
+Size  88: 44,106  GOOD (HHFFFF)
+Size  89: 45,107  BAD  (FFHFHH)
+Size  90: 45,108  GOOD (HHFFFF)
+Size  91: 46,109  BAD  (FFHFHH)
+Size  92: 46,110  GOOD (HHFFFF)
+Size  93: 47,112  BAD  (FFHFHH)
+Size  94: 47,113  GOOD (HHFFFF)
+Size  95: 48,114  BAD  (FFHFHH)
+Size  96: 48,115  GOOD (HHFFFF)
+Size  97: 49,116  BAD  (FFHFHH)
+Size  98: 49,118  GOOD (HHFFFF)
+Size  99: 50,119  BAD  (FFHFHH)
+Size 100: 50,120  GOOD (HHFFFF)
+
+Windows 8.1
+-----------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,4     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,10    GOOD (HHFFFF)
+Size   9: 5,11    BAD  (FFHFHH)
+Size  10: 5,12    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,16    BAD  (FFHFHH)
+Size  14: 7,17    GOOD (HHFFFF)
+Size  15: 8,18    BAD  (FFHFHH)
+Size  16: 8,19    GOOD (HHFFFF)
+Size  17: 9,20    BAD  (FFHFHH)
+Size  18: 9,22    GOOD (HHFFFF)
+Size  19: 10,23   BAD  (FFHFHH)
+Size  20: 10,24   GOOD (HHFFFF)
+Size  21: 11,25   BAD  (FFHFHH)
+Size  22: 11,26   GOOD (HHFFFF)
+Size  23: 12,28   BAD  (FFHFHH)
+Size  24: 12,29   GOOD (HHFFFF)
+Size  25: 13,30   BAD  (FFHFHH)
+Size  26: 13,31   GOOD (HHFFFF)
+Size  27: 14,32   BAD  (FFHFHH)
+Size  28: 14,34   GOOD (HHFFFF)
+Size  29: 15,35   BAD  (FFHFHH)
+Size  30: 15,36   GOOD (HHFFFF)
+Size  31: 16,37   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,40   BAD  (FFHFHH)
+Size  34: 17,41   GOOD (HHFFFF)
+Size  35: 18,42   BAD  (FFHFHH)
+Size  36: 18,43   GOOD (HHFFFF)
+Size  37: 19,44   BAD  (FFHFHH)
+Size  38: 19,46   GOOD (HHFFFF)
+Size  39: 20,47   BAD  (FFHFHH)
+Size  40: 20,48   GOOD (HHFFFF)
+Size  41: 21,49   BAD  (FFHFHH)
+Size  42: 21,50   GOOD (HHFFFF)
+Size  43: 22,52   BAD  (FFHFHH)
+Size  44: 22,53   GOOD (HHFFFF)
+Size  45: 23,54   BAD  (FFHFHH)
+Size  46: 23,55   GOOD (HHFFFF)
+Size  47: 24,56   BAD  (FFHFHH)
+Size  48: 24,58   GOOD (HHFFFF)
+Size  49: 25,59   BAD  (FFHFHH)
+Size  50: 25,60   GOOD (HHFFFF)
+Size  51: 26,61   BAD  (FFHFHH)
+Size  52: 26,62   GOOD (HHFFFF)
+Size  53: 27,64   BAD  (FFHFHH)
+Size  54: 27,65   GOOD (HHFFFF)
+Size  55: 28,66   BAD  (FFHFHH)
+Size  56: 28,67   GOOD (HHFFFF)
+Size  57: 29,68   BAD  (FFHFHH)
+Size  58: 29,70   GOOD (HHFFFF)
+Size  59: 30,71   BAD  (FFHFHH)
+Size  60: 30,72   GOOD (HHFFFF)
+Size  61: 31,73   BAD  (FFHFHH)
+Size  62: 31,74   GOOD (HHFFFF)
+Size  63: 32,76   BAD  (FFHFHH)
+Size  64: 32,77   GOOD (HHFFFF)
+Size  65: 33,78   BAD  (FFHFHH)
+Size  66: 33,79   GOOD (HHFFFF)
+Size  67: 34,80   BAD  (FFHFHH)
+Size  68: 34,82   GOOD (HHFFFF)
+Size  69: 35,83   BAD  (FFHFHH)
+Size  70: 35,84   GOOD (HHFFFF)
+Size  71: 36,85   BAD  (FFHFHH)
+Size  72: 36,86   GOOD (HHFFFF)
+Size  73: 37,88   BAD  (FFHFHH)
+Size  74: 37,89   GOOD (HHFFFF)
+Size  75: 38,90   BAD  (FFHFHH)
+Size  76: 38,91   GOOD (HHFFFF)
+Size  77: 39,92   BAD  (FFHFHH)
+Size  78: 39,94   GOOD (HHFFFF)
+Size  79: 40,95   BAD  (FFHFHH)
+Size  80: 40,96   GOOD (HHFFFF)
+Size  81: 41,97   BAD  (FFHFHH)
+Size  82: 41,98   GOOD (HHFFFF)
+Size  83: 42,100  BAD  (FFHFHH)
+Size  84: 42,101  GOOD (HHFFFF)
+Size  85: 43,102  BAD  (FFHFHH)
+Size  86: 43,103  GOOD (HHFFFF)
+Size  87: 44,104  BAD  (FFHFHH)
+Size  88: 44,106  GOOD (HHFFFF)
+Size  89: 45,107  BAD  (FFHFHH)
+Size  90: 45,108  GOOD (HHFFFF)
+Size  91: 46,109  BAD  (FFHFHH)
+Size  92: 46,110  GOOD (HHFFFF)
+Size  93: 47,112  BAD  (FFHFHH)
+Size  94: 47,113  GOOD (HHFFFF)
+Size  95: 48,114  BAD  (FFHFHH)
+Size  96: 48,115  GOOD (HHFFFF)
+Size  97: 49,116  BAD  (FFHFHH)
+Size  98: 49,118  GOOD (HHFFFF)
+Size  99: 50,119  BAD  (FFHFHH)
+Size 100: 50,120  GOOD (HHFFFF)
+
+Windows 10 14342 Old Console
+----------------------------
+
+Size   1: 1,2     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,4     BAD  (FFHFHH)
+Size   4: 2,5     GOOD (HHFFFF)
+Size   5: 3,6     BAD  (FFHFHH)
+Size   6: 3,7     GOOD (HHFFFF)
+Size   7: 4,8     BAD  (FFHFHH)
+Size   8: 4,10    GOOD (HHFFFF)
+Size   9: 5,11    BAD  (FFHFHH)
+Size  10: 5,12    GOOD (HHFFFF)
+Size  11: 6,13    BAD  (FFHFHH)
+Size  12: 6,14    GOOD (HHFFFF)
+Size  13: 7,16    BAD  (FFHFHH)
+Size  14: 7,17    GOOD (HHFFFF)
+Size  15: 8,18    BAD  (FFHFHH)
+Size  16: 8,19    GOOD (HHFFFF)
+Size  17: 9,20    BAD  (FFHFHH)
+Size  18: 9,22    GOOD (HHFFFF)
+Size  19: 10,23   BAD  (FFHFHH)
+Size  20: 10,24   GOOD (HHFFFF)
+Size  21: 11,25   BAD  (FFHFHH)
+Size  22: 11,26   GOOD (HHFFFF)
+Size  23: 12,28   BAD  (FFHFHH)
+Size  24: 12,29   GOOD (HHFFFF)
+Size  25: 13,30   BAD  (FFHFHH)
+Size  26: 13,31   GOOD (HHFFFF)
+Size  27: 14,32   BAD  (FFHFHH)
+Size  28: 14,34   GOOD (HHFFFF)
+Size  29: 15,35   BAD  (FFHFHH)
+Size  30: 15,36   GOOD (HHFFFF)
+Size  31: 16,37   BAD  (FFHFHH)
+Size  32: 16,38   GOOD (HHFFFF)
+Size  33: 17,40   BAD  (FFHFHH)
+Size  34: 17,41   GOOD (HHFFFF)
+Size  35: 18,42   BAD  (FFHFHH)
+Size  36: 18,43   GOOD (HHFFFF)
+Size  37: 19,44   BAD  (FFHFHH)
+Size  38: 19,46   GOOD (HHFFFF)
+Size  39: 20,47   BAD  (FFHFHH)
+Size  40: 20,48   GOOD (HHFFFF)
+Size  41: 21,49   BAD  (FFHFHH)
+Size  42: 21,50   GOOD (HHFFFF)
+Size  43: 22,52   BAD  (FFHFHH)
+Size  44: 22,53   GOOD (HHFFFF)
+Size  45: 23,54   BAD  (FFHFHH)
+Size  46: 23,55   GOOD (HHFFFF)
+Size  47: 24,56   BAD  (FFHFHH)
+Size  48: 24,58   GOOD (HHFFFF)
+Size  49: 25,59   BAD  (FFHFHH)
+Size  50: 25,60   GOOD (HHFFFF)
+Size  51: 26,61   BAD  (FFHFHH)
+Size  52: 26,62   GOOD (HHFFFF)
+Size  53: 27,64   BAD  (FFHFHH)
+Size  54: 27,65   GOOD (HHFFFF)
+Size  55: 28,66   BAD  (FFHFHH)
+Size  56: 28,67   GOOD (HHFFFF)
+Size  57: 29,68   BAD  (FFHFHH)
+Size  58: 29,70   GOOD (HHFFFF)
+Size  59: 30,71   BAD  (FFHFHH)
+Size  60: 30,72   GOOD (HHFFFF)
+Size  61: 31,73   BAD  (FFHFHH)
+Size  62: 31,74   GOOD (HHFFFF)
+Size  63: 32,76   BAD  (FFHFHH)
+Size  64: 32,77   GOOD (HHFFFF)
+Size  65: 33,78   BAD  (FFHFHH)
+Size  66: 33,79   GOOD (HHFFFF)
+Size  67: 34,80   BAD  (FFHFHH)
+Size  68: 34,82   GOOD (HHFFFF)
+Size  69: 35,83   BAD  (FFHFHH)
+Size  70: 35,84   GOOD (HHFFFF)
+Size  71: 36,85   BAD  (FFHFHH)
+Size  72: 36,86   GOOD (HHFFFF)
+Size  73: 37,88   BAD  (FFHFHH)
+Size  74: 37,89   GOOD (HHFFFF)
+Size  75: 38,90   BAD  (FFHFHH)
+Size  76: 38,91   GOOD (HHFFFF)
+Size  77: 39,92   BAD  (FFHFHH)
+Size  78: 39,94   GOOD (HHFFFF)
+Size  79: 40,95   BAD  (FFHFHH)
+Size  80: 40,96   GOOD (HHFFFF)
+Size  81: 41,97   BAD  (FFHFHH)
+Size  82: 41,98   GOOD (HHFFFF)
+Size  83: 42,100  BAD  (FFHFHH)
+Size  84: 42,101  GOOD (HHFFFF)
+Size  85: 43,102  BAD  (FFHFHH)
+Size  86: 43,103  GOOD (HHFFFF)
+Size  87: 44,104  BAD  (FFHFHH)
+Size  88: 44,106  GOOD (HHFFFF)
+Size  89: 45,107  BAD  (FFHFHH)
+Size  90: 45,108  GOOD (HHFFFF)
+Size  91: 46,109  BAD  (FFHFHH)
+Size  92: 46,110  GOOD (HHFFFF)
+Size  93: 47,112  BAD  (FFHFHH)
+Size  94: 47,113  GOOD (HHFFFF)
+Size  95: 48,114  BAD  (FFHFHH)
+Size  96: 48,115  GOOD (HHFFFF)
+Size  97: 49,116  BAD  (FFHFHH)
+Size  98: 49,118  GOOD (HHFFFF)
+Size  99: 50,119  BAD  (FFHFHH)
+Size 100: 50,120  GOOD (HHFFFF)
+
+Windows 10 14342 New Console
+----------------------------
+
+Size   1: 1,1     GOOD (HHFFFF)
+Size   2: 1,2     GOOD (HHFFFF)
+Size   3: 2,3     GOOD (HHFFFF)
+Size   4: 2,4     GOOD (HHFFFF)
+Size   5: 3,5     GOOD (HHFFFF)
+Size   6: 3,6     GOOD (HHFFFF)
+Size   7: 4,7     GOOD (HHFFFF)
+Size   8: 4,8     GOOD (HHFFFF)
+Size   9: 5,9     GOOD (HHFFFF)
+Size  10: 5,10    GOOD (HHFFFF)
+Size  11: 6,11    GOOD (HHFFFF)
+Size  12: 6,12    GOOD (HHFFFF)
+Size  13: 7,13    GOOD (HHFFFF)
+Size  14: 7,14    GOOD (HHFFFF)
+Size  15: 8,15    GOOD (HHFFFF)
+Size  16: 8,16    GOOD (HHFFFF)
+Size  17: 9,17    GOOD (HHFFFF)
+Size  18: 9,18    GOOD (HHFFFF)
+Size  19: 10,19   GOOD (HHFFFF)
+Size  20: 10,20   GOOD (HHFFFF)
+Size  21: 11,21   GOOD (HHFFFF)
+Size  22: 11,22   GOOD (HHFFFF)
+Size  23: 12,23   GOOD (HHFFFF)
+Size  24: 12,24   GOOD (HHFFFF)
+Size  25: 13,25   GOOD (HHFFFF)
+Size  26: 13,26   GOOD (HHFFFF)
+Size  27: 14,27   GOOD (HHFFFF)
+Size  28: 14,28   GOOD (HHFFFF)
+Size  29: 15,29   GOOD (HHFFFF)
+Size  30: 15,30   GOOD (HHFFFF)
+Size  31: 16,31   GOOD (HHFFFF)
+Size  32: 16,32   GOOD (HHFFFF)
+Size  33: 17,33   GOOD (HHFFFF)
+Size  34: 17,34   GOOD (HHFFFF)
+Size  35: 18,35   GOOD (HHFFFF)
+Size  36: 18,36   GOOD (HHFFFF)
+Size  37: 19,37   GOOD (HHFFFF)
+Size  38: 19,38   GOOD (HHFFFF)
+Size  39: 20,39   GOOD (HHFFFF)
+Size  40: 20,40   GOOD (HHFFFF)
+Size  41: 21,41   GOOD (HHFFFF)
+Size  42: 21,42   GOOD (HHFFFF)
+Size  43: 22,43   GOOD (HHFFFF)
+Size  44: 22,44   GOOD (HHFFFF)
+Size  45: 23,45   GOOD (HHFFFF)
+Size  46: 23,46   GOOD (HHFFFF)
+Size  47: 24,47   GOOD (HHFFFF)
+Size  48: 24,48   GOOD (HHFFFF)
+Size  49: 25,49   GOOD (HHFFFF)
+Size  50: 25,50   GOOD (HHFFFF)
+Size  51: 26,51   GOOD (HHFFFF)
+Size  52: 26,52   GOOD (HHFFFF)
+Size  53: 27,53   GOOD (HHFFFF)
+Size  54: 27,54   GOOD (HHFFFF)
+Size  55: 28,55   GOOD (HHFFFF)
+Size  56: 28,56   GOOD (HHFFFF)
+Size  57: 29,57   GOOD (HHFFFF)
+Size  58: 29,58   GOOD (HHFFFF)
+Size  59: 30,59   GOOD (HHFFFF)
+Size  60: 30,60   GOOD (HHFFFF)
+Size  61: 31,61   GOOD (HHFFFF)
+Size  62: 31,62   GOOD (HHFFFF)
+Size  63: 32,63   GOOD (HHFFFF)
+Size  64: 32,64   GOOD (HHFFFF)
+Size  65: 33,65   GOOD (HHFFFF)
+Size  66: 33,66   GOOD (HHFFFF)
+Size  67: 34,67   GOOD (HHFFFF)
+Size  68: 34,68   GOOD (HHFFFF)
+Size  69: 35,69   GOOD (HHFFFF)
+Size  70: 35,70   GOOD (HHFFFF)
+Size  71: 36,71   GOOD (HHFFFF)
+Size  72: 36,72   GOOD (HHFFFF)
+Size  73: 37,73   GOOD (HHFFFF)
+Size  74: 37,74   GOOD (HHFFFF)
+Size  75: 38,75   GOOD (HHFFFF)
+Size  76: 38,76   GOOD (HHFFFF)
+Size  77: 39,77   GOOD (HHFFFF)
+Size  78: 39,78   GOOD (HHFFFF)
+Size  79: 40,79   GOOD (HHFFFF)
+Size  80: 40,80   GOOD (HHFFFF)
+Size  81: 41,81   GOOD (HHFFFF)
+Size  82: 41,82   GOOD (HHFFFF)
+Size  83: 42,83   GOOD (HHFFFF)
+Size  84: 42,84   GOOD (HHFFFF)
+Size  85: 43,85   GOOD (HHFFFF)
+Size  86: 43,86   GOOD (HHFFFF)
+Size  87: 44,87   GOOD (HHFFFF)
+Size  88: 44,88   GOOD (HHFFFF)
+Size  89: 45,89   GOOD (HHFFFF)
+Size  90: 45,90   GOOD (HHFFFF)
+Size  91: 46,91   GOOD (HHFFFF)
+Size  92: 46,92   GOOD (HHFFFF)
+Size  93: 47,93   GOOD (HHFFFF)
+Size  94: 47,94   GOOD (HHFFFF)
+Size  95: 48,95   GOOD (HHFFFF)
+Size  96: 48,96   GOOD (HHFFFF)
+Size  97: 49,97   GOOD (HHFFFF)
+Size  98: 49,98   GOOD (HHFFFF)
+Size  99: 50,99   GOOD (HHFFFF)
+Size 100: 50,100  GOOD (HHFFFF)
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/MinimumWindowWidths.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/MinimumWindowWidths.txt
new file mode 100644 (file)
index 0000000..d5261d8
--- /dev/null
@@ -0,0 +1,16 @@
+The narrowest allowed console window, in pixels, on a conventional (~96dpi)
+monitor:
+
+(mode con: cols=40 lines=40) && SetFont.exe -face "Lucida Console" -h 1 && (ping -n 4 127.0.0.1 > NUL) && cls && GetConsolePos.exe && SetFont.exe -face "Lucida Console" -h 12
+
+(mode con: cols=40 lines=40) && SetFont.exe -face "Lucida Console" -h 16 && (ping -n 4 127.0.0.1 > NUL) && cls && GetConsolePos.exe && SetFont.exe -face "Lucida Console" -h 12
+
+                sz1:px      sz1:col     sz16:px     sz16:col
+Vista:          124         104         137         10
+Windows 7:      132         112         147         11
+Windows 8:      140         120         147         11
+Windows 8.1:    140         120         147         11
+Windows 10 OLD: 136         116         147         11
+Windows 10 NEW: 136         103         136         10
+
+I used build 14342 to test Windows 10.
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Results.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Results.txt
new file mode 100644 (file)
index 0000000..15a825c
--- /dev/null
@@ -0,0 +1,4 @@
+As before, avoid odd sizes in favor of even sizes.
+
+It's curious that the Japanese font is handled so poorly, especially with
+Windows 8 and later.
diff --git a/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Windows10SetFontBugginess.txt b/node_modules/node-pty/deps/winpty/misc/Font-Report-June2016/Windows10SetFontBugginess.txt
new file mode 100644 (file)
index 0000000..fef397a
--- /dev/null
@@ -0,0 +1,144 @@
+Issues:
+
+ - Starting with the 14342 build, changing the font using
+   SetCurrentConsoleFontEx does not affect the window size.  e.g. The content
+   itself will resize/redraw, but the window neither shrinks nor expands.
+   Presumably this is an oversight?  It's almost a convenience; if a program
+   is going to resize the window anyway, then it's nice that the window size
+   contraints don't get in the way.  Ordinarily, changing the font doesn't just
+   change the window size in pixels--it can also change the size as measured in
+   rows and columns.
+
+ - (Aside: in the 14342 build, there is also a bug with wmic.exe.  Open a console
+   with more than 300 lines of screen buffer, then fill those lines with, e.g.,
+   dir /s.  Then run wmic.exe.  You won't be able to see the wmic.exe prompt.
+   If you query the screen buffer info somehow, you'll notice that the srWindow
+   is not contained within the dwSize.  This breaks winpty's scraping, because
+   it's invalid.)
+
+ - In build 14316, with the Japanese locale, with the 437 code page, attempting
+   to set the Consolas font instead sets the Terminal (raster) font.  It seems
+   to pick an appropriate vertical size.
+
+ - It seems necessary to specify "-family 0x36" for maximum reliability.
+   Setting the family to 0 almost always works, and specifying just -tt rarely
+   works.
+
+Win7
+    English locale / 437 code page:
+        SetFont.exe -face Consolas -h 16                    works
+        SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+        SetFont.exe -face Consolas -h 16 -family 0x36       works
+    Japanese locale / 932 code page:
+        SetFont.exe -face Consolas -h 16                    works
+        SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+        SetFont.exe -face Consolas -h 16 -family 0x36       works
+    Japanese locale / 437 code page:
+        SetFont.exe -face Consolas -h 16                    works
+        SetFont.exe -face Consolas -h 16 -tt                unreliable
+        SetFont.exe -face Consolas -h 16 -family 0x36       works
+
+Win10 Build 10586
+    New console
+        Japanese locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+
+Win10 Build 14316
+    Old console
+        English locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+        Japanese locale / 932 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+        Japanese locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selected very small Consolas font
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+    New console
+        English locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                works
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+        Japanese locale / 932 code page:
+            SetFont.exe -face Consolas -h 16                    selects gothic instead
+            SetFont.exe -face Consolas -h 16 -tt                selects gothic instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       selects gothic instead
+        Japanese locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -family 0x36(*)    selects Terminal font instead
+
+Win10 Build 14342
+    Old Console
+        English locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+        Japanese locale / 932 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+        Japanese locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+    New console
+        English locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    works
+            SetFont.exe -face Consolas -h 16 -tt                works
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+        Japanese locale / 932 code page:
+            SetFont.exe -face Consolas -h 16                    selects gothic instead
+            SetFont.exe -face Consolas -h 16 -tt                selects gothic instead
+            SetFont.exe -face Consolas -h 16 -family 0x36       selects gothic instead
+        Japanese locale / 437 code page:
+            SetFont.exe -face Consolas -h 16                    selects Terminal font instead
+            SetFont.exe -face Consolas -h 16 -tt                works
+            SetFont.exe -face Consolas -h 16 -family 0x36       works
+
+(*) I was trying to figure out whether the inconsistency was at when I stumbled
+onto this completely unexpected bug.  Here's more detail:
+
+    F:\>SetFont.exe -face Consolas -h 16 -family 0x36 -weight normal -w 8
+    Setting to: nFont=0 dwFontSize=(8,16) FontFamily=0x36 FontWeight=400 FaceName="Consolas"
+    SetCurrentConsoleFontEx returned 1
+
+    F:\>GetFont.exe
+    largestConsoleWindowSize=(96,50)
+    maxWnd=0: nFont=0 dwFontSize=(12,16) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
+    maxWnd=1: nFont=0 dwFontSize=(96,25) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
+    00-00: 12x16
+    GetNumberOfConsoleFonts returned 0
+    CP=437 OutputCP=437
+
+    F:\>SetFont.exe -face "Lucida Console" -h 16 -family 0x36 -weight normal
+    Setting to: nFont=0 dwFontSize=(0,16) FontFamily=0x36 FontWeight=400 FaceName="Lucida Console"
+    SetCurrentConsoleFontEx returned 1
+
+    F:\>GetFont.exe
+    largestConsoleWindowSize=(96,50)
+    maxWnd=0: nFont=0 dwFontSize=(12,16) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
+    maxWnd=1: nFont=0 dwFontSize=(96,25) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
+    00-00: 12x16
+    GetNumberOfConsoleFonts returned 0
+    CP=437 OutputCP=437
+
+    F:\>SetFont.exe -face "Lucida Console" -h 12 -family 0x36 -weight normal
+    Setting to: nFont=0 dwFontSize=(0,12) FontFamily=0x36 FontWeight=400 FaceName="Lucida Console"
+    SetCurrentConsoleFontEx returned 1
+
+    F:\>GetFont.exe
+    largestConsoleWindowSize=(230,66)
+    maxWnd=0: nFont=0 dwFontSize=(5,12) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
+    maxWnd=1: nFont=0 dwFontSize=(116,36) FontFamily=0x30 FontWeight=400 FaceName=Terminal (54 65 72 6D 69 6E 61 6C)
+    00-00:  5x12
+    GetNumberOfConsoleFonts returned 0
+    CP=437 OutputCP=437
+
+Even attempting to set to a Lucida Console / Consolas font from the Console
+properties dialog fails.
diff --git a/node_modules/node-pty/deps/winpty/misc/FontSurvey.cc b/node_modules/node-pty/deps/winpty/misc/FontSurvey.cc
new file mode 100644 (file)
index 0000000..254bcc8
--- /dev/null
@@ -0,0 +1,100 @@
+#include <windows.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <vector>
+
+#include "TestUtil.cc"
+
+#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0]))
+
+// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
+const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // Japanese
+const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // Simplified Chinese
+const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // Traditional Chinese
+const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // Korean
+
+std::vector<bool> condense(const std::vector<CHAR_INFO> &buf) {
+    std::vector<bool> ret;
+    size_t i = 0;
+    while (i < buf.size()) {
+        if (buf[i].Char.UnicodeChar == L' ' &&
+                ((buf[i].Attributes & 0x300) == 0)) {
+            // end of line
+            break;
+        } else if (i + 1 < buf.size() &&
+                ((buf[i].Attributes & 0x300) == 0x100) &&
+                ((buf[i + 1].Attributes & 0x300) == 0x200) &&
+                buf[i].Char.UnicodeChar != L' ' &&
+                buf[i].Char.UnicodeChar == buf[i + 1].Char.UnicodeChar) {
+            // double-width
+            ret.push_back(true);
+            i += 2;
+        } else if ((buf[i].Attributes & 0x300) == 0) {
+            // single-width
+            ret.push_back(false);
+            i++;
+        } else {
+            ASSERT(false && "unexpected output");
+        }
+    }
+    return ret;
+}
+
+int main(int argc, char *argv[]) {
+    if (argc != 2) {
+        printf("Usage: %s \"arguments for SetFont.exe\"\n", argv[0]);
+        return 1;
+    }
+
+    const char *setFontArgs = argv[1];
+
+    const wchar_t testLine[] = { 0xA2, 0xA3, 0x2014, 0x3044, 0x30FC, 0x4000, 0 };
+    const HANDLE conout = openConout();
+
+    char setFontCmd[1024];
+    for (int h = 1; h <= 100; ++h) {
+        sprintf(setFontCmd, ".\\SetFont.exe %s -h %d && cls", setFontArgs, h);
+        system(setFontCmd);
+
+        CONSOLE_FONT_INFOEX infoex = {};
+        infoex.cbSize = sizeof(infoex);
+        BOOL success = GetCurrentConsoleFontEx(conout, FALSE, &infoex);
+        ASSERT(success && "GetCurrentConsoleFontEx failed");
+
+        DWORD actual = 0;
+        success = WriteConsoleW(conout, testLine, wcslen(testLine), &actual, nullptr);
+        ASSERT(success && actual == wcslen(testLine));
+
+        std::vector<CHAR_INFO> readBuf(14);
+        const SMALL_RECT readRegion = {0, 0, static_cast<short>(readBuf.size() - 1), 0};
+        SMALL_RECT readRegion2 = readRegion;
+        success = ReadConsoleOutputW(
+            conout, readBuf.data(), 
+            {static_cast<short>(readBuf.size()), 1}, 
+            {0, 0},
+            &readRegion2);
+        ASSERT(success && !memcmp(&readRegion, &readRegion2, sizeof(readRegion)));
+
+        const auto widths = condense(readBuf);
+        std::string widthsStr;
+        for (bool width : widths) {
+            widthsStr.append(width ? "F" : "H");
+        }
+        char size[16];
+        sprintf(size, "%d,%d", infoex.dwFontSize.X, infoex.dwFontSize.Y);
+        const char *status = "";
+        if (widthsStr == "HHFFFF") {
+            status = "GOOD";
+        } else if (widthsStr == "HHHFFF") {
+            status = "OK";
+        } else {
+            status = "BAD";
+        }
+        trace("Size %3d: %-7s %-4s (%s)", h, size, status, widthsStr.c_str());
+    }
+    sprintf(setFontCmd, ".\\SetFont.exe %s -h 14", setFontArgs);
+    system(setFontCmd);
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/FormatChar.h b/node_modules/node-pty/deps/winpty/misc/FormatChar.h
new file mode 100644 (file)
index 0000000..aade488
--- /dev/null
@@ -0,0 +1,21 @@
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+
+static inline void formatChar(char *str, char ch)
+{
+    // Print some common control codes.
+    switch (ch) {
+    case '\r': strcpy(str, "CR "); break;
+    case '\n': strcpy(str, "LF "); break;
+    case ' ':  strcpy(str, "SP "); break;
+    case 27:   strcpy(str, "^[ "); break;
+    case 3:    strcpy(str, "^C "); break;
+    default:
+        if (isgraph(ch))
+            sprintf(str, "%c ", ch);
+        else
+            sprintf(str, "%02x ", ch);
+        break;
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/FreezePerfTest.cc b/node_modules/node-pty/deps/winpty/misc/FreezePerfTest.cc
new file mode 100644 (file)
index 0000000..2c0b008
--- /dev/null
@@ -0,0 +1,62 @@
+#include <windows.h>
+
+#include "TestUtil.cc"
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
+
+int main(int argc, char *argv[0]) {
+
+    if (argc != 2) {
+        printf("Usage: %s (mark|selectall|read)\n", argv[0]);
+        return 1;
+    }
+
+    enum class Test { Mark, SelectAll, Read } test;
+    if (!strcmp(argv[1], "mark")) {
+        test = Test::Mark;
+    } else if (!strcmp(argv[1], "selectall")) {
+        test = Test::SelectAll;
+    } else if (!strcmp(argv[1], "read")) {
+        test = Test::Read;
+    } else {
+        printf("Invalid test: %s\n", argv[1]);
+        return 1;
+    }
+
+    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+    TimeMeasurement tm;
+    HWND hwnd = GetConsoleWindow();
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(100, 3000);
+    system("cls");
+    setWindowPos(0, 2975, 100, 25);
+    setCursorPos(0, 2999);
+
+    ShowWindow(hwnd, SW_HIDE);
+
+    for (int i = 0; i < 1000; ++i) {
+        // CONSOLE_SCREEN_BUFFER_INFO info = {};
+        // GetConsoleScreenBufferInfo(conout, &info);
+
+        if (test == Test::Mark) {
+            SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
+            SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
+        } else if (test == Test::SelectAll) {
+            SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0);
+            SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
+        } else if (test == Test::Read) {
+            static CHAR_INFO buffer[100 * 3000];
+            const SMALL_RECT readRegion = {0, 0, 99, 2999};
+            SMALL_RECT tmp = readRegion;
+            BOOL ret = ReadConsoleOutput(conout, buffer, {100, 3000}, {0, 0}, &tmp);
+            ASSERT(ret && !memcmp(&tmp, &readRegion, sizeof(tmp)));
+        }
+    }
+
+    ShowWindow(hwnd, SW_SHOW);
+
+    printf("elapsed: %f\n", tm.elapsed());
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/GetCh.cc b/node_modules/node-pty/deps/winpty/misc/GetCh.cc
new file mode 100644 (file)
index 0000000..cd6ed19
--- /dev/null
@@ -0,0 +1,20 @@
+#include <conio.h>
+#include <ctype.h>
+#include <stdio.h>
+
+int main() {
+    printf("\nPress any keys -- Ctrl-D exits\n\n");
+
+    while (true) {
+        const int ch = getch();
+        printf("0x%x", ch);
+        if (isgraph(ch)) {
+            printf(" '%c'", ch);
+        }
+        printf("\n");
+        if (ch == 0x4) { // Ctrl-D
+            break;
+        }
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/GetConsolePos.cc b/node_modules/node-pty/deps/winpty/misc/GetConsolePos.cc
new file mode 100644 (file)
index 0000000..1f3cc53
--- /dev/null
@@ -0,0 +1,41 @@
+#include <windows.h>
+
+#include <stdio.h>
+
+#include "TestUtil.cc"
+
+int main() {
+    const HANDLE conout = openConout();
+
+    CONSOLE_SCREEN_BUFFER_INFO info = {};
+    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
+    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
+
+    trace("cursor=%d,%d", info.dwCursorPosition.X, info.dwCursorPosition.Y);
+    printf("cursor=%d,%d\n", info.dwCursorPosition.X, info.dwCursorPosition.Y);
+
+    trace("srWindow={L=%d,T=%d,R=%d,B=%d}", info.srWindow.Left, info.srWindow.Top, info.srWindow.Right, info.srWindow.Bottom);
+    printf("srWindow={L=%d,T=%d,R=%d,B=%d}\n", info.srWindow.Left, info.srWindow.Top, info.srWindow.Right, info.srWindow.Bottom);
+
+    trace("dwSize=%d,%d", info.dwSize.X, info.dwSize.Y);
+    printf("dwSize=%d,%d\n", info.dwSize.X, info.dwSize.Y);
+
+    const HWND hwnd = GetConsoleWindow();
+    if (hwnd != NULL) {
+        RECT r = {};
+        if (GetWindowRect(hwnd, &r)) {
+            const int w = r.right - r.left;
+            const int h = r.bottom - r.top;
+            trace("hwnd: pos=(%d,%d) size=(%d,%d)", r.left, r.top, w, h);
+            printf("hwnd: pos=(%d,%d) size=(%d,%d)\n", r.left, r.top, w, h);
+        } else {
+            trace("GetWindowRect failed");
+            printf("GetWindowRect failed\n");
+        }
+    } else {
+        trace("GetConsoleWindow returned NULL");
+        printf("GetConsoleWindow returned NULL\n");
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/GetFont.cc b/node_modules/node-pty/deps/winpty/misc/GetFont.cc
new file mode 100644 (file)
index 0000000..3862531
--- /dev/null
@@ -0,0 +1,261 @@
+#include <windows.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+#include "../src/shared/OsModule.h"
+#include "../src/shared/StringUtil.h"
+
+#include "TestUtil.cc"
+#include "../src/shared/StringUtil.cc"
+
+#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
+
+// Some of these types and functions are missing from the MinGW headers.
+// Others are undocumented.
+
+struct AGENT_CONSOLE_FONT_INFO {
+    DWORD nFont;
+    COORD dwFontSize;
+};
+
+struct AGENT_CONSOLE_FONT_INFOEX {
+    ULONG cbSize;
+    DWORD nFont;
+    COORD dwFontSize;
+    UINT FontFamily;
+    UINT FontWeight;
+    WCHAR FaceName[LF_FACESIZE];
+};
+
+// undocumented XP API
+typedef BOOL WINAPI SetConsoleFont_t(
+            HANDLE hOutput,
+            DWORD dwFontIndex);
+
+// undocumented XP API
+typedef DWORD WINAPI GetNumberOfConsoleFonts_t();
+
+// XP and up
+typedef BOOL WINAPI GetCurrentConsoleFont_t(
+            HANDLE hOutput,
+            BOOL bMaximumWindow,
+            AGENT_CONSOLE_FONT_INFO *lpConsoleCurrentFont);
+
+// XP and up
+typedef COORD WINAPI GetConsoleFontSize_t(
+            HANDLE hConsoleOutput,
+            DWORD nFont);
+
+// Vista and up
+typedef BOOL WINAPI GetCurrentConsoleFontEx_t(
+            HANDLE hConsoleOutput,
+            BOOL bMaximumWindow,
+            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
+
+// Vista and up
+typedef BOOL WINAPI SetCurrentConsoleFontEx_t(
+            HANDLE hConsoleOutput,
+            BOOL bMaximumWindow,
+            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
+
+#define GET_MODULE_PROC(mod, funcName) \
+    m_##funcName = reinterpret_cast<funcName##_t*>((mod).proc(#funcName)); \
+
+#define DEFINE_ACCESSOR(funcName) \
+    funcName##_t &funcName() const { \
+        ASSERT(valid()); \
+        return *m_##funcName; \
+    }
+
+class XPFontAPI {
+public:
+    XPFontAPI() : m_kernel32(L"kernel32.dll") {
+        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFont);
+        GET_MODULE_PROC(m_kernel32, GetConsoleFontSize);
+    }
+
+    bool valid() const {
+        return m_GetCurrentConsoleFont != NULL &&
+            m_GetConsoleFontSize != NULL;
+    }
+
+    DEFINE_ACCESSOR(GetCurrentConsoleFont)
+    DEFINE_ACCESSOR(GetConsoleFontSize)
+
+private:
+    OsModule m_kernel32;
+    GetCurrentConsoleFont_t *m_GetCurrentConsoleFont;
+    GetConsoleFontSize_t *m_GetConsoleFontSize;
+};
+
+class UndocumentedXPFontAPI : public XPFontAPI {
+public:
+    UndocumentedXPFontAPI() : m_kernel32(L"kernel32.dll") {
+        GET_MODULE_PROC(m_kernel32, SetConsoleFont);
+        GET_MODULE_PROC(m_kernel32, GetNumberOfConsoleFonts);
+    }
+
+    bool valid() const {
+        return this->XPFontAPI::valid() &&
+            m_SetConsoleFont != NULL &&
+            m_GetNumberOfConsoleFonts != NULL;
+    }
+
+    DEFINE_ACCESSOR(SetConsoleFont)
+    DEFINE_ACCESSOR(GetNumberOfConsoleFonts)
+
+private:
+    OsModule m_kernel32;
+    SetConsoleFont_t *m_SetConsoleFont;
+    GetNumberOfConsoleFonts_t *m_GetNumberOfConsoleFonts;
+};
+
+class VistaFontAPI : public XPFontAPI {
+public:
+    VistaFontAPI() : m_kernel32(L"kernel32.dll") {
+        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFontEx);
+        GET_MODULE_PROC(m_kernel32, SetCurrentConsoleFontEx);
+    }
+
+    bool valid() const {
+        return this->XPFontAPI::valid() &&
+            m_GetCurrentConsoleFontEx != NULL &&
+            m_SetCurrentConsoleFontEx != NULL;
+    }
+
+    DEFINE_ACCESSOR(GetCurrentConsoleFontEx)
+    DEFINE_ACCESSOR(SetCurrentConsoleFontEx)
+
+private:
+    OsModule m_kernel32;
+    GetCurrentConsoleFontEx_t *m_GetCurrentConsoleFontEx;
+    SetCurrentConsoleFontEx_t *m_SetCurrentConsoleFontEx;
+};
+
+static std::vector<std::pair<DWORD, COORD> > readFontTable(
+        XPFontAPI &api, HANDLE conout, DWORD maxCount) {
+    std::vector<std::pair<DWORD, COORD> > ret;
+    for (DWORD i = 0; i < maxCount; ++i) {
+        COORD size = api.GetConsoleFontSize()(conout, i);
+        if (size.X == 0 && size.Y == 0) {
+            break;
+        }
+        ret.push_back(std::make_pair(i, size));
+    }
+    return ret;
+}
+
+static void dumpFontTable(HANDLE conout) {
+    const int kMaxCount = 1000;
+    XPFontAPI api;
+    if (!api.valid()) {
+        printf("dumpFontTable: cannot dump font table -- missing APIs\n");
+        return;
+    }
+    std::vector<std::pair<DWORD, COORD> > table =
+        readFontTable(api, conout, kMaxCount);
+    std::string line;
+    char tmp[128];
+    size_t first = 0;
+    while (first < table.size()) {
+        size_t last = std::min(table.size() - 1, first + 10 - 1);
+        winpty_snprintf(tmp, "%02u-%02u:",
+            static_cast<unsigned>(first), static_cast<unsigned>(last));
+        line = tmp;
+        for (size_t i = first; i <= last; ++i) {
+            if (i % 10 == 5) {
+                line += "  - ";
+            }
+            winpty_snprintf(tmp, " %2dx%-2d",
+                table[i].second.X, table[i].second.Y);
+            line += tmp;
+        }
+        printf("%s\n", line.c_str());
+        first = last + 1;
+    }
+    if (table.size() == kMaxCount) {
+        printf("... stopped reading at %d fonts ...\n", kMaxCount);
+    }
+}
+
+static std::string stringToCodePoints(const std::wstring &str) {
+    std::string ret = "(";
+    for (size_t i = 0; i < str.size(); ++i) {
+        char tmp[32];
+        winpty_snprintf(tmp, "%X", str[i]);
+        if (ret.size() > 1) {
+            ret.push_back(' ');
+        }
+        ret += tmp;
+    }
+    ret.push_back(')');
+    return ret;
+}
+
+static void dumpFontInfoEx(
+        const AGENT_CONSOLE_FONT_INFOEX &infoex) {
+    std::wstring faceName(infoex.FaceName,
+        winpty_wcsnlen(infoex.FaceName, COUNT_OF(infoex.FaceName)));
+    cprintf(L"nFont=%u dwFontSize=(%d,%d) "
+        "FontFamily=0x%x FontWeight=%u FaceName=%ls %hs\n",
+        static_cast<unsigned>(infoex.nFont),
+        infoex.dwFontSize.X, infoex.dwFontSize.Y,
+        infoex.FontFamily, infoex.FontWeight, faceName.c_str(),
+        stringToCodePoints(faceName).c_str());
+}
+
+static void dumpVistaFont(VistaFontAPI &api, HANDLE conout, BOOL maxWindow) {
+    AGENT_CONSOLE_FONT_INFOEX infoex = {0};
+    infoex.cbSize = sizeof(infoex);
+    if (!api.GetCurrentConsoleFontEx()(conout, maxWindow, &infoex)) {
+        printf("GetCurrentConsoleFontEx call failed\n");
+        return;
+    }
+    dumpFontInfoEx(infoex);
+}
+
+static void dumpXPFont(XPFontAPI &api, HANDLE conout, BOOL maxWindow) {
+    AGENT_CONSOLE_FONT_INFO info = {0};
+    if (!api.GetCurrentConsoleFont()(conout, maxWindow, &info)) {
+        printf("GetCurrentConsoleFont call failed\n");
+        return;
+    }
+    printf("nFont=%u dwFontSize=(%d,%d)\n",
+        static_cast<unsigned>(info.nFont),
+        info.dwFontSize.X, info.dwFontSize.Y);
+}
+
+static void dumpFontAndTable(HANDLE conout) {
+    VistaFontAPI vista;
+    if (vista.valid()) {
+        printf("maxWnd=0: "); dumpVistaFont(vista, conout, FALSE);
+        printf("maxWnd=1: "); dumpVistaFont(vista, conout, TRUE);
+        dumpFontTable(conout);
+        return;
+    }
+    UndocumentedXPFontAPI xp;
+    if (xp.valid()) {
+        printf("maxWnd=0: "); dumpXPFont(xp, conout, FALSE);
+        printf("maxWnd=1: "); dumpXPFont(xp, conout, TRUE);
+        dumpFontTable(conout);
+        return;
+    }
+    printf("setSmallFont: neither Vista nor XP APIs detected -- giving up\n");
+    dumpFontTable(conout);
+}
+
+int main() {
+    const HANDLE conout = openConout();
+    const COORD largest = GetLargestConsoleWindowSize(conout);
+    printf("largestConsoleWindowSize=(%d,%d)\n", largest.X, largest.Y);
+    dumpFontAndTable(conout);
+    UndocumentedXPFontAPI xp;
+    if (xp.valid()) {
+        printf("GetNumberOfConsoleFonts returned %u\n", xp.GetNumberOfConsoleFonts()());
+    } else {
+        printf("The GetNumberOfConsoleFonts API was missing\n");
+    }
+    printf("CP=%u OutputCP=%u\n", GetConsoleCP(), GetConsoleOutputCP());
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/IdentifyConsoleWindow.ps1 b/node_modules/node-pty/deps/winpty/misc/IdentifyConsoleWindow.ps1
new file mode 100644 (file)
index 0000000..0c48859
--- /dev/null
@@ -0,0 +1,51 @@
+#
+# Usage: powershell <path>\IdentifyConsoleWindow.ps1
+#
+# This script determines whether the process has a console attached, whether
+# that console has a non-NULL window (e.g. HWND), and whether the window is on
+# the current window station.
+#
+
+$signature = @'
+[DllImport("kernel32.dll", SetLastError=true)]
+public static extern IntPtr GetConsoleWindow();
+
+[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
+public static extern bool SetConsoleTitle(String title);
+
+[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
+public static extern int GetWindowText(IntPtr hWnd,
+                                       System.Text.StringBuilder lpString,
+                                       int nMaxCount);
+'@
+
+$WinAPI = Add-Type -MemberDefinition $signature `
+    -Name WinAPI -Namespace IdentifyConsoleWindow -PassThru
+
+if (!$WinAPI::SetConsoleTitle("ConsoleWindowScript")) {
+    echo "error: could not change console title -- is a console attached?"
+    exit 1
+} else {
+    echo "note: successfully set console title to ""ConsoleWindowScript""."
+}
+
+$hwnd = $WinAPI::GetConsoleWindow()
+if ($hwnd -eq 0) {
+    echo "note: GetConsoleWindow returned NULL."
+} else {
+    echo "note: GetConsoleWindow returned 0x$($hwnd.ToString("X"))."
+    $sb = New-Object System.Text.StringBuilder -ArgumentList 4096
+    if ($WinAPI::GetWindowText($hwnd, $sb, $sb.Capacity)) {
+        $title = $sb.ToString()
+        echo "note: GetWindowText returned ""${title}""."
+        if ($title -eq "ConsoleWindowScript") {
+            echo "success!"
+        } else {
+            echo "error: expected to see ""ConsoleWindowScript""."
+            echo "  (Perhaps the console window is on a different window station?)"
+        }
+    } else {
+        echo "error: GetWindowText could not read the window title."
+        echo "  (Perhaps the console window is on a different window station?)"
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/IsNewConsole.cc b/node_modules/node-pty/deps/winpty/misc/IsNewConsole.cc
new file mode 100644 (file)
index 0000000..2b554c7
--- /dev/null
@@ -0,0 +1,87 @@
+// Determines whether this is a new console by testing whether MARK moves the
+// cursor.
+//
+// WARNING: This test program may behave erratically if run under winpty.
+//
+
+#include <windows.h>
+
+#include <stdio.h>
+#include <string.h>
+
+#include "TestUtil.cc"
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
+
+static COORD getWindowPos(HANDLE conout) {
+    CONSOLE_SCREEN_BUFFER_INFO info = {};
+    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
+    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
+    return { info.srWindow.Left, info.srWindow.Top };
+}
+
+static COORD getWindowSize(HANDLE conout) {
+    CONSOLE_SCREEN_BUFFER_INFO info = {};
+    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
+    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
+    return {
+        static_cast<short>(info.srWindow.Right - info.srWindow.Left + 1),
+        static_cast<short>(info.srWindow.Bottom - info.srWindow.Top + 1)
+    };
+}
+
+static COORD getCursorPos(HANDLE conout) {
+    CONSOLE_SCREEN_BUFFER_INFO info = {};
+    BOOL ret = GetConsoleScreenBufferInfo(conout, &info);
+    ASSERT(ret && "GetConsoleScreenBufferInfo failed");
+    return info.dwCursorPosition;
+}
+
+static void setCursorPos(HANDLE conout, COORD pos) {
+    BOOL ret = SetConsoleCursorPosition(conout, pos);
+    ASSERT(ret && "SetConsoleCursorPosition failed");
+}
+
+int main() {
+    const HANDLE conout = openConout();
+    const HWND hwnd = GetConsoleWindow();
+    ASSERT(hwnd != NULL && "GetConsoleWindow() returned NULL");
+
+    // With the legacy console, the Mark command moves the the cursor to the
+    // top-left cell of the visible console window.  Determine whether this
+    // is the new console by seeing if the cursor moves.
+
+    const auto windowSize = getWindowSize(conout);
+    if (windowSize.X <= 1) {
+        printf("Error: console window must be at least 2 columns wide\n");
+        trace("Error: console window must be at least 2 columns wide");
+        return 1;
+    }
+
+    bool cursorMoved = false;
+    const auto initialPos = getCursorPos(conout);
+
+    const auto windowPos = getWindowPos(conout);
+    setCursorPos(conout, { static_cast<short>(windowPos.X + 1), windowPos.Y });
+
+    {
+        const auto posA = getCursorPos(conout);
+        SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
+        const auto posB = getCursorPos(conout);
+        cursorMoved = memcmp(&posA, &posB, sizeof(posA)) != 0;
+        SendMessage(hwnd, WM_CHAR, 27, 0x00010001); // Send ESCAPE
+    }
+
+    setCursorPos(conout, initialPos);
+
+    if (cursorMoved) {
+        printf("Legacy console (i.e. MARK moved cursor)\n");
+        trace("Legacy console (i.e. MARK moved cursor)");
+    } else {
+        printf("Windows 10 new console (i.e MARK did not move cursor)\n");
+        trace("Windows 10 new console (i.e MARK did not move cursor)");
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/MouseInputNotes.txt b/node_modules/node-pty/deps/winpty/misc/MouseInputNotes.txt
new file mode 100644 (file)
index 0000000..18460c6
--- /dev/null
@@ -0,0 +1,90 @@
+Introduction
+============
+
+The only specification I could find describing mouse input escape sequences
+was the /usr/share/doc/xterm/ctlseqs.txt.gz file installed on my Ubuntu
+machine.
+
+Here are the relevant escape sequences:
+
+ * [ON] CSI '?' M 'h'                   Enable mouse input mode M
+ * [OFF] CSI '?' M 'l'                  Disable mouse input mode M
+ * [EVT] CSI 'M' F X Y                  Mouse event (default or mode 1005)
+ * [EVT6] CSI '<' F ';' X ';' Y 'M'     Mouse event with mode 1006
+ * [EVT6] CSI '<' F ';' X ';' Y 'm'     Mouse event with mode 1006 (up)
+ * [EVT15] CSI F ';' X ';' Y 'M'        Mouse event with mode 1015
+
+The first batch of modes affect what events are reported:
+
+ * 9: Presses only (not as well-supported as the other modes)
+ * 1000: Presses and releases
+ * 1002: Presses, releases, and moves-while-pressed
+ * 1003: Presses, releases, and all moves
+
+The next batch of modes affect the encoding of the mouse events:
+
+ * 1005: The X and Y coordinates are UTF-8 codepoints rather than bytes.
+ * 1006: Use the EVT6 sequences instead of EVT
+ * 1015: Use the EVT15 sequence instead of EVT (aka URVXT-mode)
+
+Support for modes in existing terminals
+=======================================
+
+                                 |  9   1000 1002 1003 | 1004 | overflow     | defhi | 1005 1006 1015
+---------------------------------+---------------------+------+--------------+-------+----------------
+Eclipse TM Terminal (Neon)       |  _    _    _    _   |  _   | n/a          | n/a   |  _    _    _
+gnome-terminal 3.6.2             |  X    X    X    X   |  _   | suppressed*b | 0x07  |  _    X    X
+iTerm2 2.1.4                     |  _    X    X    X   |  OI  | wrap*z       | n/a   |  X    X    X
+jediterm/IntelliJ                |  _    X    X    X   |  _   | ch='?'       | 0xff  |  X    X    X
+Konsole 2.13.2                   |  _    X    X    *a  |  _   | suppressed   | 0xff  |  X    X    X
+mintty 2.2.2                     |  X    X    X    X   |  OI  | ch='\0'      | 0xff  |  X    X    X
+putty 0.66                       |  _    X    X    _   |  _   | suppressed   | 0xff  |  _    X    X
+rxvt 2.7.10                      |  X    X    _    _   |  _   | wrap*z       | n/a   |  _    _    _
+screen(under xterm)              |  X    X    X    X   |  _   | suppressed   | 0xff  |  _    _    _
+urxvt 9.21                       |  X    X    X    X   |  _   | wrap*z       | n/a   |  X    _    X
+xfce4-terminal 0.6.3 (GTK2 VTE)  |  X    X    X    X   |  _   | wrap         | n/a   |  _    _    _
+xterm                            |  X    X    X    X   |  OI  | ch='\0'      | 0xff  |  X    X    X
+
+*a: Mode 1003 is handled the same way as 1002.
+*b: The coordinate wraps from 0xff to 0x00, then maxs out at 0x07.  I'm
+    guessing this behavior is a bug?  I'm using the Xubuntu 14.04
+    gnome-terminal.
+*z: These terminals have a bug where column 224 (and row 224, presumably)
+    yields a truncated escape sequence.  224 + 32 is 0, so it would normally
+    yield `CSI 'M' F '\0' Y`, but the '\0' is interpreted as a NUL-terminator.
+
+Problem 1: How do these flags work?
+===================================
+
+Terminals accept the OFF sequence with any of the input modes.  This makes
+little sense--there are two multi-value settings, not seven independent flags!
+
+All the terminals handle Granularity the same way.  ON-Granularity sets
+Granularity to the specified value, and OFF-Granularity sets Granularity to
+OFF.
+
+Terminals vary in how they handle the Encoding modes.  For example:
+
+ * xterm.  ON-Encoding sets Encoding.  OFF-Encoding with a non-active Encoding
+   has no effect.  OFF-Encoding otherwise resets Encoding to Default.
+
+ * mintty (tested 2.2.2), iTerm2 2.1.4, and jediterm.  ON-Encoding sets
+   Encoding.  OFF-Encoding resets Encoding to Default.
+
+ * Konsole (tested 2.13.2) seems to configure each encoding method
+   independently.  The effective Encoding is the first enabled encoding in this
+   list:
+    - Mode 1006
+    - Mode 1015
+    - Mode 1005
+    - Default
+
+ * gnome-terminal (tested 3.6.2) also configures each encoding method
+   independently.  The effective Encoding is the first enabled encoding in
+   this list:
+    - Mode 1006
+    - Mode 1015
+    - Default
+   Mode 1005 is not supported.
+
+ * xfce4 terminal 0.6.3 (GTK2 VTE) always outputs the default encoding method.
diff --git a/node_modules/node-pty/deps/winpty/misc/MoveConsoleWindow.cc b/node_modules/node-pty/deps/winpty/misc/MoveConsoleWindow.cc
new file mode 100644 (file)
index 0000000..7d9684f
--- /dev/null
@@ -0,0 +1,34 @@
+#include <windows.h>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    if (argc != 3 && argc != 5) {
+        printf("Usage: %s x y\n", argv[0]);
+        printf("Usage: %s x y width height\n", argv[0]);
+        return 1;
+    }
+
+    HWND hwnd = GetConsoleWindow();
+
+    const int x = atoi(argv[1]);
+    const int y = atoi(argv[2]);
+
+    int w = 0, h = 0;
+    if (argc == 3) {
+        RECT r = {};
+        BOOL ret = GetWindowRect(hwnd, &r);
+        ASSERT(ret && "GetWindowRect failed on console window");
+        w = r.right - r.left;
+        h = r.bottom - r.top;
+    } else {
+        w = atoi(argv[3]);
+        h = atoi(argv[4]);
+    }
+
+    BOOL ret = MoveWindow(hwnd, x, y, w, h, TRUE);
+    trace("MoveWindow: ret=%d", ret);
+    printf("MoveWindow: ret=%d\n", ret);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Notes.txt b/node_modules/node-pty/deps/winpty/misc/Notes.txt
new file mode 100644 (file)
index 0000000..410e184
--- /dev/null
@@ -0,0 +1,219 @@
+Test programs
+-------------
+
+Cygwin
+  emacs
+  vim
+  mc     (Midnight Commander)
+  lynx
+  links
+  less
+  more
+  wget
+
+Capturing the console output
+----------------------------
+
+Initial idea:
+
+In the agent, keep track of the remote terminal state for N lines of
+(window+history).  Also keep track of the terminal size.  Regularly poll for
+changes to the console screen buffer, then use some number of edits to bring
+the remote terminal into sync with the console.
+
+This idea seems to have trouble when a Unix terminal is resized.  When the
+server receives a resize notification, it can have a hard time figuring out
+what the terminal did.  Race conditions might also be a problem.
+
+The behavior of the terminal can be tricky:
+
+ - When the window is expanded by one line, does the terminal add a blank line
+   to the bottom or move a line from the history into the top?
+
+ - When the window is shrunk by one line, does the terminal delete the topmost
+   or the bottommost line?  Can it delete the line with the cursor?
+
+Some popular behaviors for expanding:
+ - [all] If there are no history lines, then add a line at the bottom.
+ - [konsole] Always add a line at the bottom.
+ - [putty,xterm,rxvt] Pull in a history line from the top.
+ - [g-t] I can't tell.  It seems to add a blank line, until the program writes
+   to stdout or until I click the scroll bar, then the output "snaps" back down,
+   pulling lines out of the history.  I thought I saw different behavior
+   between Ubuntu 10.10 and 11.10, so maybe GNOME 3 changed something.  Avoid
+   using "bash" to test this behavior because "bash" apparently always writes
+   the prompt after terminal resize.
+
+Some popular behaviors for shrinking:
+ - [konsole,putty,xterm,rxvt] If the line at the bottom is blank, then delete
+   it.  Otherwise, move the topmost line into history.
+ - [g-t] If the line at the bottom has not been touched, then delete it.
+   Otherwise, move the topmost line into history.
+
+(TODO: I need to test my theories about the terminal behavior better still.
+It's interesting to see how g-t handles clear differently than every other
+terminal.)
+
+There is an ANSI escape sequence (DSR) that sends the current cursor location
+to the terminal's input.  One idea I had was to use this code to figure out how
+the terminal had handled a resize.  I currently think this idea won't work due
+to race conditions.
+
+Newer idea:
+
+Keep track of the last N lines that have been sent to the remote terminal.
+Poll for changes to console output.  When the output changes, send just the
+changed content to the terminal.  In particular:
+ - Don't send a cursor position (CUP) code.  Instead, if the line that's 3
+   steps up from the latest line changes, send a relative cursor up (CUU)
+   code.  It's OK to send an absolute column number code (CHA).
+ - At least in general, don't try to send complete screenshots of the current
+   console window.
+
+The idea is that sending just the changes should have good behavior for streams
+of output, even when those streams modify the output (e.g. an archiver, or
+maybe a downloader/packager/wget).  I need to think about whether this works
+for full-screen programs (e.g. emacs, less, lynx, the above list of programs).
+
+I noticed that console programs don't typically modify the window or buffer
+coordinates.  edit.com is an exception.
+
+I tested the pager in native Python (more?), and I verified that ENTER and SPACE
+both paid no attention to the location of the console window within the screen
+buffer.  This makes sense -- why would they care?  The Cygwin less, on the other
+hand, does care.  If I scroll the window up, then Cygwin less will write to a
+position within the window.  I didn't really expect this behavior, but it
+doesn't seem to be a problem.
+
+Setting up a TestNetServer service
+----------------------------------
+
+First run the deploy.sh script to copy files into deploy.  Make sure
+TestNetServer.exe will run in a bare environment (no MinGW or Qt in the path).
+
+Install the Windows Server 2003 Resource Kit.  It will have two programs in it,
+instsrv and srvany.
+
+Run:
+
+  InstSrv TestNetServer <path-to-srvany>\srvany.exe
+
+This creates a service named "TestNetServer" that uses the Microsoft service
+wrapper.  To configure the new service to run TestNetServer, set a registry
+value:
+
+  [HKLM\SYSTEM\CurrentControlSet\Services\TestNetServer\Parameters]
+  Application=<full-path>\TestNetServer.exe
+
+Also see http://www.iopus.com/guides/srvany.htm.
+
+To remove the service, run:
+
+  InstSrv TestNetServer REMOVE
+
+TODO
+----
+
+Agent: When resizing the console, consider whether to add lines to the top
+or bottom.  I remember thinking the current behavior was wrong for some
+application, but I forgot which one.
+
+Make the font as small as possible.  The console window dimensions are limited by
+the screen size, so making the font small reduces an unnecessary limitation on the
+PseudoConsole size.  There's a documented Vista/Win7 API for this
+(SetCurrentConsoleFontEx), and apparently WinXP has an undocumented API
+(SetConsoleFont):
+    http://blogs.microsoft.co.il/blogs/pavely/archive/2009/07/23/changing-console-fonts.aspx
+
+Make the agent work with DOS programs like edit and qbasic.
+ - Detect that the terminal program has resized the window/buffer and enter a
+   simple just-scrape-and-dont-resize mode.  Track the client window size and
+   send the intersection of the console and the agent's client.
+ - I also need to generate keyboard scan codes.
+ - Solve the NTVDM.EXE console shutdown problem, probably by ignoring NTVDM.EXE
+   when it appears on the GetConsoleProcessList list.
+
+Rename the agent?  Is the term "proxy" more accurate?
+
+Optimize the polling.  e.g. Use a longer poll interval when the console is idle.
+Do a minimal poll that checks whether the sync marker or window has moved.
+
+Increase the console buffer size to ~9000 lines.  Beware making it so big that
+reading the sync column exhausts the 32KB conhost<->agent heap.
+
+Reduce the memory overhead of the agent.  The agent's m_bufferData array can
+be small (a few hundred lines?) relative to the console buffer size.
+
+Try to handle console background color better.
+    Unix terminal emulators have a user-configurable foreground and background
+color, and for best results, the agent really needs to avoid changing the colors,
+especially the background color.  It's undesirable/ugly to SSH into a machine
+and see the command prompt change the colors.  It's especially ugly that the
+terminal retains its original colors and only drawn cells get the new colors.
+(e.g. Resizing the window to the right uses the local terminal colors rather
+than the remote colors.)  It's especially ugly in gnome-terminal, which draws
+user-configurable black as black, but VT100 black as dark-gray.
+    If there were a way to query the terminal emulator's colors, then I could
+match the console's colors to the terminal and everything would just work.  As
+far as I know, that's not possible.
+    I thought of a kludge that might work.  Instead of translating console white
+and black to VT/100 white and black, I would translate them to "reset" and
+"invert".  I'd translate other colors normally.  This approach should produce
+ideal results for command-line work and tolerable results for full-screen
+programs without configuration.  Configuring the agent for black-on-white or
+white-on-black would produce ideal results in all situations.
+    This kludge only really applies to the SSH application.  For a Win32 Konsole
+application, it should be easy to get the colors right all the time.
+
+Try using the screen reader API:
+ - To eliminate polling.
+ - To detect when a line wraps.  When a line wraps, it'd be nice not to send a
+   CRLF to the terminal emulator so copy-and-paste works better.
+ - To detect hard tabs with Cygwin.
+
+Implement VT100/ANSI escape sequence recognition for input.  Decide where this
+functionality belongs.  PseudoConsole.dll?  Disambiguating ESC from an escape
+sequence might be tricky.  For the SSH server, I was thinking that when a small
+SSH payload ended with an ESC character, I could assume the character was really
+an ESC keypress, on the assumption that if it were an escape sequence, the
+payload would probably contain the whole sequence.  I'm not sure this works,
+especially if there's a lot of other traffic multiplexed on the SSH socket.
+
+Support Unicode.
+ - Some DOS programs draw using line/box characters.  Can these characters be
+   translated to the Unicode equivalents?
+
+Create automated tests.
+
+Experiment with the Terminator emulator, an emulator that doesn't wrap lines.
+How many columns does it report having?  What column does it report the cursor
+in as it's writing past the right end of the window?  Will Terminator be a
+problem if I implement line wrapping detection in the agent?
+
+BUG: After the unix-adapter/pconsole.exe program exits, the blinking cursor is
+replaced with a hidden cursor.
+
+Fix assert() in the agent.  If it fails, the failure message needs to be
+reported somewhere.  Pop up a dialog box?  Maybe switch the active desktop,
+then show a dialog box?
+
+TODO: There's already a pconsole project on GitHub.  Maybe rename this project
+to something else?  winpty?
+
+TODO: Can the DebugServer system be replaced with OutputDebugString?  How
+do we decide whose processes' output to collect?
+
+TODO: Three executables:
+  build/winpty-agent.exe
+  build/winpty.dll
+  build/console.exe
+
+BUG: Run the pconsole.exe inside another console.  As I type dir, I see this:
+      D:\rprichard\pconsole>
+      D:\rprichard\pconsole>d
+      D:\rprichard\pconsole>di
+      D:\rprichard\pconsole>dir
+    In the output of "dir", every other line is blank.
+    There was a bug in Terminal::sendLine that was causing this to happen
+    frequently.  Now that I fixed it, this bug should only manifest on lines
+    whose last column is not a space (i.e. a full line).
diff --git a/node_modules/node-pty/deps/winpty/misc/OSVersion.cc b/node_modules/node-pty/deps/winpty/misc/OSVersion.cc
new file mode 100644 (file)
index 0000000..456708f
--- /dev/null
@@ -0,0 +1,27 @@
+#include <windows.h>
+
+#include <assert.h>
+#include <locale.h>
+#include <stdio.h>
+
+#include <iostream>
+
+int main() {
+    setlocale(LC_ALL, "");
+
+    OSVERSIONINFOEXW info = {0};
+    info.dwOSVersionInfoSize = sizeof(info);
+    assert(GetVersionExW((OSVERSIONINFOW*)&info));
+
+    printf("dwMajorVersion      = %d\n", (int)info.dwMajorVersion);
+    printf("dwMinorVersion      = %d\n", (int)info.dwMinorVersion);
+    printf("dwBuildNumber       = %d\n", (int)info.dwBuildNumber);
+    printf("dwPlatformId        = %d\n", (int)info.dwPlatformId);
+    printf("szCSDVersion        = %ls\n", info.szCSDVersion);
+    printf("wServicePackMajor   = %d\n", info.wServicePackMajor);
+    printf("wServicePackMinor   = %d\n", info.wServicePackMinor);
+    printf("wSuiteMask          = 0x%x\n", (unsigned int)info.wSuiteMask);
+    printf("wProductType        = 0x%x\n", (unsigned int)info.wProductType);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ScreenBufferFreezeInactive.cc b/node_modules/node-pty/deps/winpty/misc/ScreenBufferFreezeInactive.cc
new file mode 100644 (file)
index 0000000..656d4f1
--- /dev/null
@@ -0,0 +1,101 @@
+//
+// Verify that console selection blocks writes to an inactive console screen
+// buffer.  Writes TEST PASSED or TEST FAILED to the popup console window.
+//
+
+#include <windows.h>
+#include <stdio.h>
+
+#include <string>
+
+#include "TestUtil.cc"
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
+
+bool g_useMark = false;
+
+CALLBACK DWORD pausingThread(LPVOID dummy)
+{
+    HWND hwnd = GetConsoleWindow();
+    trace("Sending selection to freeze");
+    SendMessage(hwnd, WM_SYSCOMMAND,
+        g_useMark ? SC_CONSOLE_MARK :
+                    SC_CONSOLE_SELECT_ALL,
+        0);
+    Sleep(1000);
+    trace("Sending escape WM_CHAR to unfreeze");
+    SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
+    Sleep(1000);
+}
+
+static HANDLE createBuffer() {
+    HANDLE buf = CreateConsoleScreenBuffer(
+        GENERIC_READ | GENERIC_WRITE,
+        FILE_SHARE_READ | FILE_SHARE_WRITE,
+        NULL,
+        CONSOLE_TEXTMODE_BUFFER,
+        NULL);
+    ASSERT(buf != INVALID_HANDLE_VALUE);
+    return buf;
+}
+
+static void runTest(bool useMark, bool createEarly) {
+    trace("=======================================");
+    trace("useMark=%d createEarly=%d", useMark, createEarly);
+    g_useMark = useMark;
+    HANDLE buf = INVALID_HANDLE_VALUE;
+
+    if (createEarly) {
+        buf = createBuffer();
+    }
+
+    CreateThread(NULL, 0,
+         pausingThread, NULL,
+         0, NULL);
+    Sleep(500);
+
+    if (!createEarly) {
+        trace("Creating buffer");
+        TimeMeasurement tm1;
+        buf = createBuffer();
+        const double elapsed1 = tm1.elapsed();
+        if (elapsed1 >= 0.250) {
+            printf("!!! TEST FAILED !!!\n");
+            Sleep(2000);
+            return;
+        }
+    }
+
+    trace("Writing to aux buffer");
+    TimeMeasurement tm2;
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleW(buf, L"HI", 2, &actual, NULL);
+    const double elapsed2 = tm2.elapsed();
+    trace("Writing to aux buffer: finished: ret=%d actual=%d (elapsed=%1.3f)", ret, actual, elapsed2);
+    if (elapsed2 < 0.250) {
+        printf("!!! TEST FAILED !!!\n");
+    } else {
+        printf("TEST PASSED\n");
+    }
+    Sleep(2000);
+}
+
+int main(int argc, char **argv) {
+    if (argc == 1) {
+        startChildProcess(L"child");
+        return 0;
+    }
+
+    std::string arg = argv[1];
+    if (arg == "child") {
+        for (int useMark = 0; useMark <= 1; useMark++) {
+            for (int createEarly = 0; createEarly <= 1; createEarly++) {
+                runTest(useMark, createEarly);
+            }
+        }
+        printf("done...\n");
+        Sleep(1000);
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ScreenBufferTest.cc b/node_modules/node-pty/deps/winpty/misc/ScreenBufferTest.cc
new file mode 100644 (file)
index 0000000..fa584b9
--- /dev/null
@@ -0,0 +1,671 @@
+//
+// Windows versions tested
+//
+// Vista Enterprise SP2 32-bit
+//  - ver reports [Version 6.0.6002]
+//  - kernel32.dll product/file versions are 6.0.6002.19381
+//
+// Windows 7 Ultimate SP1 32-bit
+//  - ver reports [Version 6.1.7601]
+//  - conhost.exe product/file versions are 6.1.7601.18847
+//  - kernel32.dll product/file versions are 6.1.7601.18847
+//
+// Windows Server 2008 R2 Datacenter SP1 64-bit
+//  - ver reports [Version 6.1.7601]
+//  - conhost.exe product/file versions are 6.1.7601.23153
+//  - kernel32.dll product/file versions are 6.1.7601.23153
+//
+// Windows 8 Enterprise 32-bit
+//  - ver reports [Version 6.2.9200]
+//  - conhost.exe product/file versions are 6.2.9200.16578
+//  - kernel32.dll product/file versions are 6.2.9200.16859
+//
+
+//
+// Specific version details on working Server 2008 R2:
+//
+//      dwMajorVersion      = 6
+//      dwMinorVersion      = 1
+//      dwBuildNumber       = 7601
+//      dwPlatformId        = 2
+//      szCSDVersion        = Service Pack 1
+//      wServicePackMajor   = 1
+//      wServicePackMinor   = 0
+//      wSuiteMask          = 0x190
+//      wProductType        = 0x3
+//
+// Specific version details on broken Win7:
+//
+//      dwMajorVersion      = 6
+//      dwMinorVersion      = 1
+//      dwBuildNumber       = 7601
+//      dwPlatformId        = 2
+//      szCSDVersion        = Service Pack 1
+//      wServicePackMajor   = 1
+//      wServicePackMinor   = 0
+//      wSuiteMask          = 0x100
+//      wProductType        = 0x1
+//
+
+#include <windows.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "TestUtil.cc"
+
+const char *g_prefix = "";
+
+static void dumpHandles() {
+    trace("%sSTDIN=0x%I64x STDOUT=0x%I64x STDERR=0x%I64x",
+        g_prefix,
+        (long long)GetStdHandle(STD_INPUT_HANDLE),
+        (long long)GetStdHandle(STD_OUTPUT_HANDLE),
+        (long long)GetStdHandle(STD_ERROR_HANDLE));
+}
+
+static const char *successOrFail(BOOL ret) {
+    return ret ? "ok" : "FAILED";
+}
+
+static void startChildInSameConsole(const wchar_t *args, BOOL
+                                    bInheritHandles=FALSE) {
+    wchar_t program[1024];
+    wchar_t cmdline[1024];
+    GetModuleFileNameW(NULL, program, 1024);
+    swprintf(cmdline, L"\"%ls\" %ls", program, args);
+
+    STARTUPINFOW sui;
+    PROCESS_INFORMATION pi;
+    memset(&sui, 0, sizeof(sui));
+    memset(&pi, 0, sizeof(pi));
+    sui.cb = sizeof(sui);
+
+    CreateProcessW(program, cmdline,
+                   NULL, NULL,
+                   /*bInheritHandles=*/bInheritHandles,
+                   /*dwCreationFlags=*/0,
+                   NULL, NULL,
+                   &sui, &pi);
+}
+
+static void closeHandle(HANDLE h) {
+    trace("%sClosing handle 0x%I64x...", g_prefix, (long long)h);
+    trace("%sClosing handle 0x%I64x... %s", g_prefix, (long long)h, successOrFail(CloseHandle(h)));
+}
+
+static HANDLE createBuffer() {
+
+    // If sa isn't provided, the handle defaults to not-inheritable.
+    SECURITY_ATTRIBUTES sa = {0};
+    sa.nLength = sizeof(sa);
+    sa.bInheritHandle = TRUE;
+
+    trace("%sCreating a new buffer...", g_prefix);
+    HANDLE conout = CreateConsoleScreenBuffer(
+                GENERIC_READ | GENERIC_WRITE,
+                FILE_SHARE_READ | FILE_SHARE_WRITE,
+                &sa,
+                CONSOLE_TEXTMODE_BUFFER, NULL);
+
+    trace("%sCreating a new buffer... 0x%I64x", g_prefix, (long long)conout);
+    return conout;
+}
+
+static HANDLE openConout() {
+
+    // If sa isn't provided, the handle defaults to not-inheritable.
+    SECURITY_ATTRIBUTES sa = {0};
+    sa.nLength = sizeof(sa);
+    sa.bInheritHandle = TRUE;
+
+    trace("%sOpening CONOUT...", g_prefix);
+    HANDLE conout = CreateFileW(L"CONOUT$",
+                GENERIC_READ | GENERIC_WRITE,
+                FILE_SHARE_READ | FILE_SHARE_WRITE,
+                &sa,
+                OPEN_EXISTING, 0, NULL);
+    trace("%sOpening CONOUT... 0x%I64x", g_prefix, (long long)conout);
+    return conout;
+}
+
+static void setConsoleActiveScreenBuffer(HANDLE conout) {
+    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called...",
+        g_prefix, (long long)conout);
+    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called... %s",
+        g_prefix, (long long)conout,
+        successOrFail(SetConsoleActiveScreenBuffer(conout)));
+}
+
+static void writeTest(HANDLE conout, const char *msg) {
+    char writeData[256];
+    sprintf(writeData, "%s%s\n", g_prefix, msg);
+
+    trace("%sWriting to 0x%I64x: '%s'...",
+        g_prefix, (long long)conout, msg);
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleA(conout, writeData, strlen(writeData), &actual, NULL);
+    trace("%sWriting to 0x%I64x: '%s'... %s",
+        g_prefix, (long long)conout, msg,
+        successOrFail(ret && actual == strlen(writeData)));
+}
+
+static void writeTest(const char *msg) {
+    writeTest(GetStdHandle(STD_OUTPUT_HANDLE), msg);
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TEST 1 -- create new buffer, activate it, and close the handle.  The console
+// automatically switches the screen buffer back to the original.
+//
+// This test passes everywhere.
+//
+
+static void test1(int argc, char *argv[]) {
+    if (!strcmp(argv[1], "1")) {
+        startChildProcess(L"1:child");
+        return;
+    }
+
+    HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
+    writeTest(origBuffer, "<-- origBuffer -->");
+
+    HANDLE newBuffer = createBuffer();
+    writeTest(newBuffer, "<-- newBuffer -->");
+    setConsoleActiveScreenBuffer(newBuffer);
+    Sleep(2000);
+
+    writeTest(origBuffer, "TEST PASSED!");
+
+    // Closing the handle w/o switching the active screen buffer automatically
+    // switches the console back to the original buffer.
+    closeHandle(newBuffer);
+
+    while (true) {
+        Sleep(1000);
+    }
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TEST 2 -- Test program that creates and activates newBuffer, starts a child
+// process, then closes its newBuffer handle.  newBuffer remains activated,
+// because the child keeps it active.  (Also see TEST D.)
+//
+
+static void test2(int argc, char *argv[]) {
+    if (!strcmp(argv[1], "2")) {
+        startChildProcess(L"2:parent");
+        return;
+    }
+
+    if (!strcmp(argv[1], "2:parent")) {
+        g_prefix = "parent: ";
+        dumpHandles();
+        HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
+        writeTest(origBuffer, "<-- origBuffer -->");
+
+        HANDLE newBuffer = createBuffer();
+        writeTest(newBuffer, "<-- newBuffer -->");
+        setConsoleActiveScreenBuffer(newBuffer);
+
+        Sleep(1000);
+        writeTest(newBuffer, "bInheritHandles=FALSE:");
+        startChildInSameConsole(L"2:child", FALSE);
+        Sleep(1000);
+        writeTest(newBuffer, "bInheritHandles=TRUE:");
+        startChildInSameConsole(L"2:child", TRUE);
+
+        Sleep(1000);
+        trace("parent:----");
+
+        // Close the new buffer.  The active screen buffer doesn't automatically
+        // switch back to origBuffer, because the child process has a handle open
+        // to the original buffer.
+        closeHandle(newBuffer);
+
+        Sleep(600 * 1000);
+        return;
+    }
+
+    if (!strcmp(argv[1], "2:child")) {
+        g_prefix = "child: ";
+        dumpHandles();
+        // The child's output isn't visible, because it's still writing to
+        // origBuffer.
+        trace("child:----");
+        writeTest("writing to STDOUT");
+
+        // Handle inheritability is curious.  The console handles this program
+        // creates are inheritable, but CreateProcess is called with both
+        // bInheritHandles=TRUE and bInheritHandles=FALSE.
+        //
+        // Vista and Windows 7: bInheritHandles has no effect.  The child and
+        // parent processes have the same STDIN/STDOUT/STDERR handles:
+        // 0x3, 0x7, and 0xB.  The parent has a 0xF handle for newBuffer.
+        // The child can only write to 0x7, 0xB, and 0xF.  Only the writes to
+        // 0xF are visible (i.e. they touch newBuffer).
+        //
+        // Windows 8 or Windows 10 (legacy or non-legacy): the lowest 2 bits of
+        // the HANDLE to WriteConsole seem to be ignored.  The new process'
+        // console handles always refer to the buffer that was active when they
+        // started, but the values of the handles depend upon bInheritHandles.
+        // With bInheritHandles=TRUE, the child has the same
+        // STDIN/STDOUT/STDERR/newBuffer handles as the parent, and the three
+        // output handles all work, though their output is all visible.  With
+        // bInheritHandles=FALSE, the child has different STDIN/STDOUT/STDERR
+        // handles, and only the new STDOUT/STDERR handles work.
+        //
+        for (unsigned int i = 0x1; i <= 0xB0; ++i) {
+            char msg[256];
+            sprintf(msg, "Write to handle 0x%x", i);
+            HANDLE h = reinterpret_cast<HANDLE>(i);
+            writeTest(h, msg);
+        }
+
+        Sleep(600 * 1000);
+        return;
+    }
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TEST A -- demonstrate an apparent Windows bug with screen buffers
+//
+// Steps:
+//  - The parent starts a child process.
+//  - The child process creates and activates newBuffer
+//  - The parent opens CONOUT$ and writes to it.
+//  - The parent closes CONOUT$.
+//     - At this point, broken Windows reactivates origBuffer.
+//  - The child writes to newBuffer again.
+//  - The child activates origBuffer again, then closes newBuffer.
+//
+// Test passes if the message "TEST PASSED!" is visible.
+// Test commonly fails if conhost.exe crashes.
+//
+// Results:
+//  - Windows 7 Ultimate SP1 32-bit: conhost.exe crashes
+//  - Windows Server 2008 R2 Datacenter SP1 64-bit: PASS
+//  - Windows 8 Enterprise 32-bit: PASS
+//  - Windows 10 64-bit (legacy and non-legacy): PASS
+//
+
+static void testA_parentWork() {
+    // Open an extra CONOUT$ handle so that the HANDLE values in parent and
+    // child don't collide.  I think it's OK if they collide, but since we're
+    // trying to track down a Windows bug, it's best to avoid unnecessary
+    // complication.
+    HANDLE dummy = openConout();
+
+    Sleep(3000);
+
+    // Step 2: Open CONOUT$ in the parent.  This opens the active buffer, which
+    // was just created in the child.  It's handle 0x13.  Write to it.
+
+    HANDLE newBuffer = openConout();
+    writeTest(newBuffer, "step2: writing to newBuffer");
+
+    Sleep(3000);
+
+    // Step 3: Close handle 0x13.  With Windows 7, the console switches back to
+    // origBuffer, and (unless I'm missing something) it shouldn't.
+
+    closeHandle(newBuffer);
+}
+
+static void testA_childWork() {
+    HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    //
+    // Step 1: Create the new screen buffer in the child process and make it
+    // active.  (Typically, it's handle 0x0F.)
+    //
+
+    HANDLE newBuffer = createBuffer();
+
+    setConsoleActiveScreenBuffer(newBuffer);
+    writeTest(newBuffer, "<-- newBuffer -->");
+
+    Sleep(9000);
+    trace("child:----");
+
+    // Step 4: write to the newBuffer again.
+    writeTest(newBuffer, "TEST PASSED!");
+
+    //
+    // Step 5: Switch back to the original screen buffer and close the new
+    // buffer.  The switch call succeeds, but the CloseHandle call freezes for
+    // several seconds, because conhost.exe crashes.
+    //
+    Sleep(3000);
+
+    setConsoleActiveScreenBuffer(origBuffer);
+    writeTest(origBuffer, "writing to origBuffer");
+
+    closeHandle(newBuffer);
+
+    // The console HWND is NULL.
+    trace("child: console HWND=0x%I64x", (long long)GetConsoleWindow());
+
+    // At this point, the console window has closed, but the parent/child
+    // processes are still running.  Calling AllocConsole would fail, but
+    // calling FreeConsole followed by AllocConsole would both succeed, and a
+    // new console would appear.
+}
+
+static void testA(int argc, char *argv[]) {
+
+    if (!strcmp(argv[1], "A")) {
+        startChildProcess(L"A:parent");
+        return;
+    }
+
+    if (!strcmp(argv[1], "A:parent")) {
+        g_prefix = "parent: ";
+        trace("parent:----");
+        dumpHandles();
+        writeTest("<-- origBuffer -->");
+        startChildInSameConsole(L"A:child");
+        testA_parentWork();
+        Sleep(120000);
+        return;
+    }
+
+    if (!strcmp(argv[1], "A:child")) {
+        g_prefix = "child: ";
+        dumpHandles();
+        testA_childWork();
+        Sleep(120000);
+        return;
+    }
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TEST B -- invert TEST A -- also crashes conhost on Windows 7
+//
+// Test passes if the message "TEST PASSED!" is visible.
+// Test commonly fails if conhost.exe crashes.
+//
+// Results:
+//  - Windows 7 Ultimate SP1 32-bit: conhost.exe crashes
+//  - Windows Server 2008 R2 Datacenter SP1 64-bit: PASS
+//  - Windows 8 Enterprise 32-bit: PASS
+//  - Windows 10 64-bit (legacy and non-legacy): PASS
+//
+
+static void testB(int argc, char *argv[]) {
+    if (!strcmp(argv[1], "B")) {
+        startChildProcess(L"B:parent");
+        return;
+    }
+
+    if (!strcmp(argv[1], "B:parent")) {
+        g_prefix = "parent: ";
+        startChildInSameConsole(L"B:child");
+        writeTest("<-- origBuffer -->");
+        HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
+
+        //
+        // Step 1: Create the new buffer and make it active.
+        //
+        trace("%s----", g_prefix);
+        HANDLE newBuffer = createBuffer();
+        setConsoleActiveScreenBuffer(newBuffer);
+        writeTest(newBuffer, "<-- newBuffer -->");
+
+        //
+        // Step 4: Attempt to write again to the new buffer.
+        //
+        Sleep(9000);
+        trace("%s----", g_prefix);
+        writeTest(newBuffer, "TEST PASSED!");
+
+        //
+        // Step 5: Switch back to the original buffer.
+        //
+        Sleep(3000);
+        trace("%s----", g_prefix);
+        setConsoleActiveScreenBuffer(origBuffer);
+        closeHandle(newBuffer);
+        writeTest(origBuffer, "writing to the initial buffer");
+
+        Sleep(60000);
+        return;
+    }
+
+    if (!strcmp(argv[1], "B:child")) {
+        g_prefix = "child: ";
+        Sleep(3000);
+        trace("%s----", g_prefix);
+
+        //
+        // Step 2: Open the newly active buffer and write to it.
+        //
+        HANDLE newBuffer = openConout();
+        writeTest(newBuffer, "writing to newBuffer");
+
+        //
+        // Step 3: Close the newly active buffer.
+        //
+        Sleep(3000);
+        closeHandle(newBuffer);
+
+        Sleep(60000);
+        return;
+    }
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TEST C -- Interleaving open/close of console handles also seems to break on
+// Windows 7.
+//
+// Test:
+//  - child creates and activates newBuf1
+//  - parent opens newBuf1
+//  - child creates and activates newBuf2
+//  - parent opens newBuf2, then closes newBuf1
+//  - child switches back to newBuf1
+//     * At this point, the console starts malfunctioning.
+//  - parent and child close newBuf2
+//  - child closes newBuf1
+//
+// Test passes if the message "TEST PASSED!" is visible.
+// Test commonly fails if conhost.exe crashes.
+//
+// Results:
+//  - Windows 7 Ultimate SP1 32-bit: conhost.exe crashes
+//  - Windows Server 2008 R2 Datacenter SP1 64-bit: PASS
+//  - Windows 8 Enterprise 32-bit: PASS
+//  - Windows 10 64-bit (legacy and non-legacy): PASS
+//
+
+static void testC(int argc, char *argv[]) {
+    if (!strcmp(argv[1], "C")) {
+        startChildProcess(L"C:parent");
+        return;
+    }
+
+    if (!strcmp(argv[1], "C:parent")) {
+        startChildInSameConsole(L"C:child");
+        writeTest("<-- origBuffer -->");
+        g_prefix = "parent: ";
+
+        // At time=4, open newBuffer1.
+        Sleep(4000);
+        trace("%s---- t=4", g_prefix);
+        const HANDLE newBuffer1 = openConout();
+
+        // At time=8, open newBuffer2, and close newBuffer1.
+        Sleep(4000);
+        trace("%s---- t=8", g_prefix);
+        const HANDLE newBuffer2 = openConout();
+        closeHandle(newBuffer1);
+
+        // At time=25, cleanup of newBuffer2.
+        Sleep(17000);
+        trace("%s---- t=25", g_prefix);
+        closeHandle(newBuffer2);
+
+        Sleep(240000);
+        return;
+    }
+
+    if (!strcmp(argv[1], "C:child")) {
+        g_prefix = "child: ";
+
+        // At time=2, create newBuffer1 and activate it.
+        Sleep(2000);
+        trace("%s---- t=2", g_prefix);
+        const HANDLE newBuffer1 = createBuffer();
+        setConsoleActiveScreenBuffer(newBuffer1);
+        writeTest(newBuffer1, "<-- newBuffer1 -->");
+
+        // At time=6, create newBuffer2 and activate it.
+        Sleep(4000);
+        trace("%s---- t=6", g_prefix);
+        const HANDLE newBuffer2 = createBuffer();
+        setConsoleActiveScreenBuffer(newBuffer2);
+        writeTest(newBuffer2, "<-- newBuffer2 -->");
+
+        // At time=10, attempt to switch back to newBuffer1.  The parent process
+        // has opened and closed its handle to newBuffer1, so does it still exist?
+        Sleep(4000);
+        trace("%s---- t=10", g_prefix);
+        setConsoleActiveScreenBuffer(newBuffer1);
+        writeTest(newBuffer1, "write to newBuffer1: TEST PASSED!");
+
+        // At time=25, cleanup of newBuffer2.
+        Sleep(15000);
+        trace("%s---- t=25", g_prefix);
+        closeHandle(newBuffer2);
+
+        // At time=35, cleanup of newBuffer1.  The console should switch to the
+        // initial buffer again.
+        Sleep(10000);
+        trace("%s---- t=35", g_prefix);
+        closeHandle(newBuffer1);
+
+        Sleep(240000);
+        return;
+    }
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TEST D -- parent creates a new buffer, child launches, writes,
+// closes it output handle, then parent writes again.  (Also see TEST 2.)
+//
+// On success, this will appear:
+//
+//    parent: <-- newBuffer -->
+//    child: writing to newBuffer
+//    parent: TEST PASSED!
+//
+// If this appears, it indicates that the child's closing its output handle did
+// not destroy newBuffer.
+//
+// Results:
+//  - Windows 7 Ultimate SP1 32-bit: PASS
+//  - Windows 8 Enterprise 32-bit: PASS
+//  - Windows 10 64-bit (legacy and non-legacy): PASS
+//
+
+static void testD(int argc, char *argv[]) {
+    if (!strcmp(argv[1], "D")) {
+        startChildProcess(L"D:parent");
+        return;
+    }
+
+    if (!strcmp(argv[1], "D:parent")) {
+        g_prefix = "parent: ";
+        HANDLE origBuffer = GetStdHandle(STD_OUTPUT_HANDLE);
+        writeTest(origBuffer, "<-- origBuffer -->");
+
+        HANDLE newBuffer = createBuffer();
+        writeTest(newBuffer, "<-- newBuffer -->");
+        setConsoleActiveScreenBuffer(newBuffer);
+
+        // At t=2, start a child process, explicitly forcing it to use
+        // newBuffer for its standard handles.  These calls are apparently
+        // redundant on Windows 8 and up.
+        Sleep(2000);
+        trace("parent:----");
+        trace("parent: starting child process");
+        SetStdHandle(STD_OUTPUT_HANDLE, newBuffer);
+        SetStdHandle(STD_ERROR_HANDLE, newBuffer);
+        startChildInSameConsole(L"D:child");
+        SetStdHandle(STD_OUTPUT_HANDLE, origBuffer);
+        SetStdHandle(STD_ERROR_HANDLE, origBuffer);
+
+        // At t=6, write again to newBuffer.
+        Sleep(4000);
+        trace("parent:----");
+        writeTest(newBuffer, "TEST PASSED!");
+
+        // At t=8, close the newBuffer.  In earlier versions of windows
+        // (including Server 2008 R2), the console then switches back to
+        // origBuffer.  As of Windows 8, it doesn't, because somehow the child
+        // process is keeping the console on newBuffer, even though the child
+        // process closed its STDIN/STDOUT/STDERR handles.  Killing the child
+        // process by hand after the test finishes *does* force the console
+        // back to origBuffer.
+        Sleep(2000);
+        closeHandle(newBuffer);
+
+        Sleep(120000);
+        return;
+    }
+
+    if (!strcmp(argv[1], "D:child")) {
+        g_prefix = "child: ";
+        // At t=2, the child starts.
+        trace("child:----");
+        dumpHandles();
+        writeTest("writing to newBuffer");
+
+        // At t=4, the child explicitly closes its handle.
+        Sleep(2000);
+        trace("child:----");
+        if (GetStdHandle(STD_ERROR_HANDLE) != GetStdHandle(STD_OUTPUT_HANDLE)) {
+            closeHandle(GetStdHandle(STD_ERROR_HANDLE));
+        }
+        closeHandle(GetStdHandle(STD_OUTPUT_HANDLE));
+        closeHandle(GetStdHandle(STD_INPUT_HANDLE));
+
+        Sleep(120000);
+        return;
+    }
+}
+
+
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        printf("USAGE: %s testnum\n", argv[0]);
+        return 0;
+    }
+
+    if (argv[1][0] == '1') {
+        test1(argc, argv);
+    } else if (argv[1][0] == '2') {
+        test2(argc, argv);
+    } else if (argv[1][0] == 'A') {
+        testA(argc, argv);
+    } else if (argv[1][0] == 'B') {
+        testB(argc, argv);
+    } else if (argv[1][0] == 'C') {
+        testC(argc, argv);
+    } else if (argv[1][0] == 'D') {
+        testD(argc, argv);
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ScreenBufferTest2.cc b/node_modules/node-pty/deps/winpty/misc/ScreenBufferTest2.cc
new file mode 100644 (file)
index 0000000..2b648c9
--- /dev/null
@@ -0,0 +1,151 @@
+#include <windows.h>
+
+#include "TestUtil.cc"
+
+const char *g_prefix = "";
+
+static void dumpHandles() {
+    trace("%sSTDIN=0x%I64x STDOUT=0x%I64x STDERR=0x%I64x",
+        g_prefix,
+        (long long)GetStdHandle(STD_INPUT_HANDLE),
+        (long long)GetStdHandle(STD_OUTPUT_HANDLE),
+        (long long)GetStdHandle(STD_ERROR_HANDLE));
+}
+
+static HANDLE createBuffer() {
+
+    // If sa isn't provided, the handle defaults to not-inheritable.
+    SECURITY_ATTRIBUTES sa = {0};
+    sa.nLength = sizeof(sa);
+    sa.bInheritHandle = TRUE;
+
+    trace("%sCreating a new buffer...", g_prefix);
+    HANDLE conout = CreateConsoleScreenBuffer(
+                GENERIC_READ | GENERIC_WRITE,
+                FILE_SHARE_READ | FILE_SHARE_WRITE,
+                &sa,
+                CONSOLE_TEXTMODE_BUFFER, NULL);
+
+    trace("%sCreating a new buffer... 0x%I64x", g_prefix, (long long)conout);
+    return conout;
+}
+
+static const char *successOrFail(BOOL ret) {
+    return ret ? "ok" : "FAILED";
+}
+
+static void setConsoleActiveScreenBuffer(HANDLE conout) {
+    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called...",
+        g_prefix, (long long)conout);
+    trace("%sSetConsoleActiveScreenBuffer(0x%I64x) called... %s",
+        g_prefix, (long long)conout,
+        successOrFail(SetConsoleActiveScreenBuffer(conout)));
+}
+
+static void writeTest(HANDLE conout, const char *msg) {
+    char writeData[256];
+    sprintf(writeData, "%s%s\n", g_prefix, msg);
+
+    trace("%sWriting to 0x%I64x: '%s'...",
+        g_prefix, (long long)conout, msg);
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleA(conout, writeData, strlen(writeData), &actual, NULL);
+    trace("%sWriting to 0x%I64x: '%s'... %s",
+        g_prefix, (long long)conout, msg,
+        successOrFail(ret && actual == strlen(writeData)));
+}
+
+static HANDLE startChildInSameConsole(const wchar_t *args, BOOL
+                                    bInheritHandles=FALSE) {
+    wchar_t program[1024];
+    wchar_t cmdline[1024];
+    GetModuleFileNameW(NULL, program, 1024);
+    swprintf(cmdline, L"\"%ls\" %ls", program, args);
+
+    STARTUPINFOW sui;
+    PROCESS_INFORMATION pi;
+    memset(&sui, 0, sizeof(sui));
+    memset(&pi, 0, sizeof(pi));
+    sui.cb = sizeof(sui);
+
+    CreateProcessW(program, cmdline,
+                   NULL, NULL,
+                   /*bInheritHandles=*/bInheritHandles,
+                   /*dwCreationFlags=*/0,
+                   NULL, NULL,
+                   &sui, &pi);
+
+    return pi.hProcess;
+}
+
+static HANDLE dup(HANDLE h, HANDLE targetProcess) {
+    HANDLE h2 = INVALID_HANDLE_VALUE;
+    BOOL ret = DuplicateHandle(
+        GetCurrentProcess(), h,
+        targetProcess, &h2,
+        0, TRUE, DUPLICATE_SAME_ACCESS);
+    trace("dup(0x%I64x) to process 0x%I64x... %s, 0x%I64x",
+        (long long)h,
+        (long long)targetProcess,
+        successOrFail(ret),
+        (long long)h2);
+    return h2;
+}
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"parent");
+        return 0;
+    }
+
+    if (!strcmp(argv[1], "parent")) {
+        g_prefix = "parent: ";
+        dumpHandles();
+        HANDLE hChild = startChildInSameConsole(L"child");
+
+        // Windows 10.
+        HANDLE orig1 = GetStdHandle(STD_OUTPUT_HANDLE);
+        HANDLE new1 = createBuffer();
+
+        Sleep(2000);
+        setConsoleActiveScreenBuffer(new1);
+
+        // Handle duplication results to child process in same console:
+        //  - Windows XP:                                       fails
+        //  - Windows 7 Ultimate SP1 32-bit:                    fails
+        //  - Windows Server 2008 R2 Datacenter SP1 64-bit:     fails
+        //  - Windows 8 Enterprise 32-bit:                      succeeds
+        //  - Windows 10:                                       succeeds
+        HANDLE orig2 = dup(orig1, GetCurrentProcess());
+        HANDLE new2 = dup(new1, GetCurrentProcess());
+
+        dup(orig1, hChild);
+        dup(new1, hChild);
+
+        // The writes to orig1/orig2 are invisible.  The writes to new1/new2
+        // are visible.
+        writeTest(orig1, "write to orig1");
+        writeTest(orig2, "write to orig2");
+        writeTest(new1, "write to new1");
+        writeTest(new2, "write to new2");
+
+        Sleep(120000);
+        return 0;
+    }
+
+    if (!strcmp(argv[1], "child")) {
+        g_prefix = "child: ";
+        dumpHandles();
+        Sleep(4000);
+        for (unsigned int i = 0x1; i <= 0xB0; ++i) {
+            char msg[256];
+            sprintf(msg, "Write to handle 0x%x", i);
+            HANDLE h = reinterpret_cast<HANDLE>(i);
+            writeTest(h, msg);
+        }
+        Sleep(120000);
+        return 0;
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/SelectAllTest.cc b/node_modules/node-pty/deps/winpty/misc/SelectAllTest.cc
new file mode 100644 (file)
index 0000000..a6c2773
--- /dev/null
@@ -0,0 +1,45 @@
+#define _WIN32_WINNT 0x0501
+#include <stdio.h>
+#include <windows.h>
+
+#include "../src/shared/DebugClient.cc"
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
+
+CALLBACK DWORD pausingThread(LPVOID dummy)
+{
+    HWND hwnd = GetConsoleWindow();
+    while (true) {
+        SendMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0);
+        Sleep(1000);
+        SendMessage(hwnd, WM_CHAR, 27, 0x00010001);
+        Sleep(1000);
+    }
+}
+
+int main()
+{
+    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
+    CONSOLE_SCREEN_BUFFER_INFO info;
+
+    GetConsoleScreenBufferInfo(out, &info);
+    COORD initial = info.dwCursorPosition;
+
+    CreateThread(NULL, 0,
+                 pausingThread, NULL,
+                 0, NULL);
+
+    for (int i = 0; i < 30; ++i) {
+        Sleep(100);
+        GetConsoleScreenBufferInfo(out, &info);
+        if (memcmp(&info.dwCursorPosition, &initial, sizeof(COORD)) != 0) {
+            trace("cursor moved to [%d,%d]",
+                   info.dwCursorPosition.X,
+                   info.dwCursorPosition.Y);
+        } else {
+            trace("cursor in expected position");
+        }
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/SetBufferSize.cc b/node_modules/node-pty/deps/winpty/misc/SetBufferSize.cc
new file mode 100644 (file)
index 0000000..b50a1f8
--- /dev/null
@@ -0,0 +1,32 @@
+#include <windows.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    if (argc != 3) {
+        printf("Usage: %s x y width height\n", argv[0]);
+        return 1;
+    }
+
+    const HANDLE conout = CreateFileW(L"CONOUT$",
+                                      GENERIC_READ | GENERIC_WRITE,
+                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                      NULL, OPEN_EXISTING, 0, NULL);
+    ASSERT(conout != INVALID_HANDLE_VALUE);
+
+    COORD size = {
+        (short)atoi(argv[1]),
+        (short)atoi(argv[2]),
+    };
+
+    BOOL ret = SetConsoleScreenBufferSize(conout, size);
+    const unsigned lastError = GetLastError();
+    const char *const retStr = ret ? "OK" : "failed";
+    trace("SetConsoleScreenBufferSize ret: %s (LastError=0x%x)", retStr, lastError);
+    printf("SetConsoleScreenBufferSize ret: %s (LastError=0x%x)\n", retStr, lastError);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/SetCursorPos.cc b/node_modules/node-pty/deps/winpty/misc/SetCursorPos.cc
new file mode 100644 (file)
index 0000000..d20fdbd
--- /dev/null
@@ -0,0 +1,10 @@
+#include <windows.h>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    int col = atoi(argv[1]);
+    int row = atoi(argv[2]);
+    setCursorPos(col, row);
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/SetFont.cc b/node_modules/node-pty/deps/winpty/misc/SetFont.cc
new file mode 100644 (file)
index 0000000..9bcd4b4
--- /dev/null
@@ -0,0 +1,145 @@
+#include <windows.h>
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+
+#include "TestUtil.cc"
+
+#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0]))
+
+// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
+const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // Japanese
+const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // Simplified Chinese
+const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // Traditional Chinese
+const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // Korean
+
+int main() {
+    setlocale(LC_ALL, "");
+    wchar_t *cmdline = GetCommandLineW();
+    int argc = 0;
+    wchar_t **argv = CommandLineToArgvW(cmdline, &argc);
+    const HANDLE conout = openConout();
+
+    if (argc == 1) {
+        cprintf(L"Usage:\n");
+        cprintf(L"  SetFont <index>\n");
+        cprintf(L"  SetFont options\n");
+        cprintf(L"\n");
+        cprintf(L"Options for SetCurrentConsoleFontEx:\n");
+        cprintf(L"  -idx INDEX\n");
+        cprintf(L"  -w WIDTH\n");
+        cprintf(L"  -h HEIGHT\n");
+        cprintf(L"  -family (0xNN|NN)\n");
+        cprintf(L"  -weight (normal|bold|NNN)\n");
+        cprintf(L"  -face FACENAME\n");
+        cprintf(L"  -face-{gothic|simsun|minglight|gulimche) [JP,CN-sim,CN-tra,KR]\n");
+        cprintf(L"  -tt\n");
+        cprintf(L"  -vec\n");
+        cprintf(L"  -vp\n");
+        cprintf(L"  -dev\n");
+        cprintf(L"  -roman\n");
+        cprintf(L"  -swiss\n");
+        cprintf(L"  -modern\n");
+        cprintf(L"  -script\n");
+        cprintf(L"  -decorative\n");
+        return 0;
+    }
+
+    if (isdigit(argv[1][0])) {
+        int index = _wtoi(argv[1]);
+        HMODULE kernel32 = LoadLibraryW(L"kernel32.dll");
+        FARPROC proc = GetProcAddress(kernel32, "SetConsoleFont");
+        if (proc == NULL) {
+            cprintf(L"Couldn't get address of SetConsoleFont\n");
+        } else {
+            BOOL ret = reinterpret_cast<BOOL WINAPI(*)(HANDLE, DWORD)>(proc)(
+                    conout, index);
+            cprintf(L"SetFont returned %d\n", ret);
+        }
+        return 0;
+    }
+
+    CONSOLE_FONT_INFOEX fontex = {0};
+    fontex.cbSize = sizeof(fontex);
+
+    for (int i = 1; i < argc; ++i) {
+        std::wstring arg = argv[i];
+        if (i + 1 < argc) {
+            std::wstring next = argv[i + 1];
+            if (arg == L"-idx") {
+                fontex.nFont = _wtoi(next.c_str());
+                ++i; continue;
+            } else if (arg == L"-w") {
+                fontex.dwFontSize.X = _wtoi(next.c_str());
+                ++i; continue;
+            } else if (arg == L"-h") {
+                fontex.dwFontSize.Y = _wtoi(next.c_str());
+                ++i; continue;
+            } else if (arg == L"-weight") {
+                if (next == L"normal") {
+                    fontex.FontWeight = 400;
+                } else if (next == L"bold") {
+                    fontex.FontWeight = 700;
+                } else {
+                    fontex.FontWeight = _wtoi(next.c_str());
+                }
+                ++i; continue;
+            } else if (arg == L"-face") {
+                wcsncpy(fontex.FaceName, next.c_str(), COUNT_OF(fontex.FaceName));
+                ++i; continue;
+            } else if (arg == L"-family") {
+                fontex.FontFamily = strtol(narrowString(next).c_str(), nullptr, 0);
+                ++i; continue;
+            }
+        }
+        if (arg == L"-tt") {
+            fontex.FontFamily |= TMPF_TRUETYPE;
+        } else if (arg == L"-vec") {
+            fontex.FontFamily |= TMPF_VECTOR;
+        } else if (arg == L"-vp") {
+            // Setting the TMPF_FIXED_PITCH bit actually indicates variable
+            // pitch.
+            fontex.FontFamily |= TMPF_FIXED_PITCH;
+        } else if (arg == L"-dev") {
+            fontex.FontFamily |= TMPF_DEVICE;
+        } else if (arg == L"-roman") {
+            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_ROMAN;
+        } else if (arg == L"-swiss") {
+            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_SWISS;
+        } else if (arg == L"-modern") {
+            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_MODERN;
+        } else if (arg == L"-script") {
+            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_SCRIPT;
+        } else if (arg == L"-decorative") {
+            fontex.FontFamily = (fontex.FontFamily & ~0xF0) | FF_DECORATIVE;
+        } else if (arg == L"-face-gothic") {
+            wcsncpy(fontex.FaceName, kMSGothic, COUNT_OF(fontex.FaceName));
+        } else if (arg == L"-face-simsun") {
+            wcsncpy(fontex.FaceName, kNSimSun, COUNT_OF(fontex.FaceName));
+        } else if (arg == L"-face-minglight") {
+            wcsncpy(fontex.FaceName, kMingLight, COUNT_OF(fontex.FaceName));
+        } else if (arg == L"-face-gulimche") {
+            wcsncpy(fontex.FaceName, kGulimChe, COUNT_OF(fontex.FaceName));
+        } else {
+            cprintf(L"Unrecognized argument: %ls\n", arg.c_str());
+            exit(1);
+        }
+    }
+
+    cprintf(L"Setting to: nFont=%u dwFontSize=(%d,%d) "
+        L"FontFamily=0x%x FontWeight=%u "
+        L"FaceName=\"%ls\"\n",
+        static_cast<unsigned>(fontex.nFont),
+        fontex.dwFontSize.X, fontex.dwFontSize.Y,
+        fontex.FontFamily, fontex.FontWeight,
+        fontex.FaceName);
+
+    BOOL ret = SetCurrentConsoleFontEx(
+        conout,
+        FALSE,
+        &fontex);
+    cprintf(L"SetCurrentConsoleFontEx returned %d\n", ret);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/SetWindowRect.cc b/node_modules/node-pty/deps/winpty/misc/SetWindowRect.cc
new file mode 100644 (file)
index 0000000..6291dd6
--- /dev/null
@@ -0,0 +1,36 @@
+#include <windows.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    if (argc != 5) {
+        printf("Usage: %s x y width height\n", argv[0]);
+        return 1;
+    }
+
+    const HANDLE conout = CreateFileW(L"CONOUT$",
+                                      GENERIC_READ | GENERIC_WRITE,
+                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                      NULL, OPEN_EXISTING, 0, NULL);
+    ASSERT(conout != INVALID_HANDLE_VALUE);
+
+    SMALL_RECT sr = {
+        (short)atoi(argv[1]),
+        (short)atoi(argv[2]),
+        (short)(atoi(argv[1]) + atoi(argv[3]) - 1),
+        (short)(atoi(argv[2]) + atoi(argv[4]) - 1),
+    };
+
+    trace("Calling SetConsoleWindowInfo with {L=%d,T=%d,R=%d,B=%d}",
+        sr.Left, sr.Top, sr.Right, sr.Bottom);
+    BOOL ret = SetConsoleWindowInfo(conout, TRUE, &sr);
+    const unsigned lastError = GetLastError();
+    const char *const retStr = ret ? "OK" : "failed";
+    trace("SetConsoleWindowInfo ret: %s (LastError=0x%x)", retStr, lastError);
+    printf("SetConsoleWindowInfo ret: %s (LastError=0x%x)\n", retStr, lastError);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ShowArgv.cc b/node_modules/node-pty/deps/winpty/misc/ShowArgv.cc
new file mode 100644 (file)
index 0000000..29a0f09
--- /dev/null
@@ -0,0 +1,12 @@
+// This test program is useful for studying commandline<->argv conversion.
+
+#include <stdio.h>
+#include <windows.h>
+
+int main(int argc, char **argv)
+{
+    printf("cmdline = [%s]\n", GetCommandLine());
+    for (int i = 0; i < argc; ++i)
+        printf("[%s]\n", argv[i]);
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/ShowConsoleInput.cc b/node_modules/node-pty/deps/winpty/misc/ShowConsoleInput.cc
new file mode 100644 (file)
index 0000000..75fbfb8
--- /dev/null
@@ -0,0 +1,40 @@
+#include <windows.h>
+#include <stdio.h>
+#include <ctype.h>
+
+int main(int argc, char *argv[])
+{
+    static int escCount = 0;
+
+    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
+    while (true) {
+        DWORD count;
+        INPUT_RECORD ir;
+        if (!ReadConsoleInput(hStdin, &ir, 1, &count)) {
+            printf("ReadConsoleInput failed\n");
+            return 1;
+        }
+
+        if (true) {
+            DWORD mode;
+            GetConsoleMode(hStdin, &mode);
+            SetConsoleMode(hStdin, mode & ~ENABLE_PROCESSED_INPUT);
+        }
+
+        if (ir.EventType == KEY_EVENT) {
+            const KEY_EVENT_RECORD &ker = ir.Event.KeyEvent;
+            printf("%s", ker.bKeyDown ? "dn" : "up");
+            printf(" ch=");
+            if (isprint(ker.uChar.AsciiChar))
+                printf("'%c'", ker.uChar.AsciiChar);
+            printf("%d", ker.uChar.AsciiChar);
+            printf(" vk=%#x", ker.wVirtualKeyCode);
+            printf(" scan=%#x", ker.wVirtualScanCode);
+            printf(" state=%#x", (int)ker.dwControlKeyState);
+            printf(" repeat=%d", ker.wRepeatCount);
+            printf("\n");
+            if (ker.uChar.AsciiChar == 27 && ++escCount == 6)
+                break;
+        }
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Spew.py b/node_modules/node-pty/deps/winpty/misc/Spew.py
new file mode 100644 (file)
index 0000000..9d1796a
--- /dev/null
@@ -0,0 +1,5 @@
+#!/usr/bin/env python
+i = 0;
+while True:
+    i += 1
+    print(i)
diff --git a/node_modules/node-pty/deps/winpty/misc/TestUtil.cc b/node_modules/node-pty/deps/winpty/misc/TestUtil.cc
new file mode 100644 (file)
index 0000000..c832a12
--- /dev/null
@@ -0,0 +1,172 @@
+// This file is included into test programs using #include
+
+#include <windows.h>
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <wchar.h>
+#include <vector>
+#include <string>
+
+#include "../src/shared/DebugClient.h"
+#include "../src/shared/TimeMeasurement.h"
+
+#include "../src/shared/DebugClient.cc"
+#include "../src/shared/WinptyAssert.cc"
+#include "../src/shared/WinptyException.cc"
+
+// Launch this test program again, in a new console that we will destroy.
+static void startChildProcess(const wchar_t *args) {
+    wchar_t program[1024];
+    wchar_t cmdline[1024];
+    GetModuleFileNameW(NULL, program, 1024);
+    swprintf(cmdline, L"\"%ls\" %ls", program, args);
+
+    STARTUPINFOW sui;
+    PROCESS_INFORMATION pi;
+    memset(&sui, 0, sizeof(sui));
+    memset(&pi, 0, sizeof(pi));
+    sui.cb = sizeof(sui);
+
+    CreateProcessW(program, cmdline,
+                   NULL, NULL,
+                   /*bInheritHandles=*/FALSE,
+                   /*dwCreationFlags=*/CREATE_NEW_CONSOLE,
+                   NULL, NULL,
+                   &sui, &pi);
+}
+
+static void setBufferSize(HANDLE conout, int x, int y) {
+    COORD size = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
+    BOOL success = SetConsoleScreenBufferSize(conout, size);
+    trace("setBufferSize: (%d,%d), result=%d", x, y, success);
+}
+
+static void setWindowPos(HANDLE conout, int x, int y, int w, int h) {
+    SMALL_RECT r = {
+        static_cast<SHORT>(x), static_cast<SHORT>(y),
+        static_cast<SHORT>(x + w - 1),
+        static_cast<SHORT>(y + h - 1)
+    };
+    BOOL success = SetConsoleWindowInfo(conout, /*bAbsolute=*/TRUE, &r);
+    trace("setWindowPos: (%d,%d,%d,%d), result=%d", x, y, w, h, success);
+}
+
+static void setCursorPos(HANDLE conout, int x, int y) {
+    COORD coord = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
+    SetConsoleCursorPosition(conout, coord);
+}
+
+static void setBufferSize(int x, int y) {
+    setBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), x, y);
+}
+
+static void setWindowPos(int x, int y, int w, int h) {
+    setWindowPos(GetStdHandle(STD_OUTPUT_HANDLE), x, y, w, h);
+}
+
+static void setCursorPos(int x, int y) {
+    setCursorPos(GetStdHandle(STD_OUTPUT_HANDLE), x, y);
+}
+
+static void countDown(int sec) {
+    for (int i = sec; i > 0; --i) {
+        printf("%d.. ", i);
+        fflush(stdout);
+        Sleep(1000);
+    }
+    printf("\n");
+}
+
+static void writeBox(int x, int y, int w, int h, char ch, int attributes=7) {
+    CHAR_INFO info = { 0 };
+    info.Char.AsciiChar = ch;
+    info.Attributes = attributes;
+    std::vector<CHAR_INFO> buf(w * h, info);
+    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+    COORD bufSize = { static_cast<SHORT>(w), static_cast<SHORT>(h) };
+    COORD bufCoord = { 0, 0 };
+    SMALL_RECT writeRegion = {
+        static_cast<SHORT>(x),
+        static_cast<SHORT>(y),
+        static_cast<SHORT>(x + w - 1),
+        static_cast<SHORT>(y + h - 1)
+    };
+    WriteConsoleOutputA(conout, buf.data(), bufSize, bufCoord, &writeRegion);
+}
+
+static void setChar(int x, int y, char ch, int attributes=7) {
+    writeBox(x, y, 1, 1, ch, attributes);
+}
+
+static void fillChar(int x, int y, int repeat, char ch) {
+    COORD coord = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
+    DWORD actual = 0;
+    FillConsoleOutputCharacterA(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        ch, repeat, coord, &actual);
+}
+
+static void repeatChar(int count, char ch) {
+    for (int i = 0; i < count; ++i) {
+        putchar(ch);
+    }
+    fflush(stdout);
+}
+
+// I don't know why, but wprintf fails to print this face name,
+// "MS ゴシック" (aka MS Gothic).  It helps to use wprintf instead of printf, and
+// it helps to call `setlocale(LC_ALL, "")`, but the Japanese symbols are
+// ultimately converted to `?` symbols, even though MS Gothic is able to
+// display its own name, and the current code page is 932 (Shift-JIS).
+static void cvfprintf(HANDLE conout, const wchar_t *fmt, va_list ap) {
+    wchar_t buffer[256];
+    vswprintf(buffer, 256 - 1, fmt, ap);
+    buffer[255] = L'\0';
+    DWORD actual = 0;
+    if (!WriteConsoleW(conout, buffer, wcslen(buffer), &actual, NULL)) {
+        wprintf(L"WriteConsoleW call failed!\n");
+    }
+}
+
+static void cfprintf(HANDLE conout, const wchar_t *fmt, ...) {
+    va_list ap;
+    va_start(ap, fmt);
+    cvfprintf(conout, fmt, ap);
+    va_end(ap);
+}
+
+static void cprintf(const wchar_t *fmt, ...) {
+    va_list ap;
+    va_start(ap, fmt);
+    cvfprintf(GetStdHandle(STD_OUTPUT_HANDLE), fmt, ap);
+    va_end(ap);
+}
+
+static std::string narrowString(const std::wstring &input)
+{
+    int mblen = WideCharToMultiByte(
+        CP_UTF8, 0,
+        input.data(), input.size(),
+        NULL, 0, NULL, NULL);
+    if (mblen <= 0) {
+        return std::string();
+    }
+    std::vector<char> tmp(mblen);
+    int mblen2 = WideCharToMultiByte(
+        CP_UTF8, 0,
+        input.data(), input.size(),
+        tmp.data(), tmp.size(),
+        NULL, NULL);
+    assert(mblen2 == mblen);
+    return std::string(tmp.data(), tmp.size());
+}
+
+HANDLE openConout() {
+    const HANDLE conout = CreateFileW(L"CONOUT$",
+                                      GENERIC_READ | GENERIC_WRITE,
+                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                      NULL, OPEN_EXISTING, 0, NULL);
+    ASSERT(conout != INVALID_HANDLE_VALUE);
+    return conout;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/UnicodeDoubleWidthTest.cc b/node_modules/node-pty/deps/winpty/misc/UnicodeDoubleWidthTest.cc
new file mode 100644 (file)
index 0000000..7210d41
--- /dev/null
@@ -0,0 +1,102 @@
+// Demonstrates how U+30FC is sometimes handled as a single-width character
+// when it should be handled as a double-width character.
+//
+// It only runs on computers where 932 is a valid code page.  Set the system
+// local to "Japanese (Japan)" to ensure this.
+//
+// The problem seems to happen when U+30FC is printed in a console using the
+// Lucida Console font, and only when that font is at certain sizes.
+//
+
+#include <windows.h>
+#include <assert.h>
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "TestUtil.cc"
+
+#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
+
+static void setFont(const wchar_t *faceName, int pxSize) {
+    CONSOLE_FONT_INFOEX infoex = {0};
+    infoex.cbSize = sizeof(infoex);
+    infoex.dwFontSize.Y = pxSize;
+    wcsncpy(infoex.FaceName, faceName, COUNT_OF(infoex.FaceName));
+    BOOL ret = SetCurrentConsoleFontEx(
+        GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &infoex);
+    assert(ret);
+}
+
+static bool performTest(const wchar_t testChar) {
+    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    SetConsoleTextAttribute(conout, 7);
+
+    system("cls");
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleW(conout, &testChar, 1, &actual, NULL);
+    assert(ret && actual == 1);
+
+    CHAR_INFO verify[2];
+    COORD bufSize = {2, 1};
+    COORD bufCoord = {0, 0};
+    const SMALL_RECT readRegion = {0, 0, 1, 0};
+    SMALL_RECT actualRegion = readRegion;
+    ret = ReadConsoleOutputW(conout, verify, bufSize, bufCoord, &actualRegion);
+    assert(ret && !memcmp(&readRegion, &actualRegion, sizeof(readRegion)));
+    assert(verify[0].Char.UnicodeChar == testChar);
+
+    if (verify[1].Char.UnicodeChar == testChar) {
+        // Typical double-width behavior with a TrueType font.  Pass.
+        assert(verify[0].Attributes == 0x107);
+        assert(verify[1].Attributes == 0x207);
+        return true;
+    } else if (verify[1].Char.UnicodeChar == 0) {
+        // Typical double-width behavior with a Raster Font.  Pass.
+        assert(verify[0].Attributes == 7);
+        assert(verify[1].Attributes == 0);
+        return true;
+    } else if (verify[1].Char.UnicodeChar == L' ') {
+        // Single-width behavior.  Fail.
+        assert(verify[0].Attributes == 7);
+        assert(verify[1].Attributes == 7);
+        return false;
+    } else {
+        // Unexpected output.
+        assert(false);
+    }
+}
+
+int main(int argc, char *argv[]) {
+    setlocale(LC_ALL, "");
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    assert(SetConsoleCP(932));
+    assert(SetConsoleOutputCP(932));
+
+    const wchar_t testChar = 0x30FC;
+    const wchar_t *const faceNames[] = {
+        L"Lucida Console",
+        L"Consolas",
+        L"MS ゴシック",
+    };
+
+    trace("Test started");
+
+    for (auto faceName : faceNames) {
+        for (int px = 1; px <= 50; ++px) {
+            setFont(faceName, px);
+            if (!performTest(testChar)) {
+                trace("FAILURE: %s %dpx", narrowString(faceName).c_str(), px);
+            }
+        }
+    }
+
+    trace("Test complete");
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/UnicodeWideTest1.cc b/node_modules/node-pty/deps/winpty/misc/UnicodeWideTest1.cc
new file mode 100644 (file)
index 0000000..a8d798e
--- /dev/null
@@ -0,0 +1,246 @@
+#include <windows.h>
+
+#include <assert.h>
+#include <vector>
+
+#include "TestUtil.cc"
+
+#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
+
+
+CHAR_INFO ci(wchar_t ch, WORD attributes) {
+    CHAR_INFO ret;
+    ret.Char.UnicodeChar = ch;
+    ret.Attributes = attributes;
+    return ret;
+}
+
+CHAR_INFO ci(wchar_t ch) {
+    return ci(ch, 7);
+}
+
+CHAR_INFO ci() {
+    return ci(L' ');
+}
+
+bool operator==(SMALL_RECT x, SMALL_RECT y) {
+    return !memcmp(&x, &y, sizeof(x));
+}
+
+SMALL_RECT sr(COORD pt, COORD size) {
+    return {
+        pt.X, pt.Y,
+        static_cast<SHORT>(pt.X + size.X - 1),
+        static_cast<SHORT>(pt.Y + size.Y - 1)
+    };
+}
+
+static void set(
+        const COORD pt,
+        const COORD size,
+        const std::vector<CHAR_INFO> &data) {
+    assert(data.size() == size.X * size.Y);
+    SMALL_RECT writeRegion = sr(pt, size);
+    BOOL ret = WriteConsoleOutputW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        data.data(), size, {0, 0}, &writeRegion);
+    assert(ret && writeRegion == sr(pt, size));
+}
+
+static void set(
+        const COORD pt,
+        const std::vector<CHAR_INFO> &data) {
+    set(pt, {static_cast<SHORT>(data.size()), 1}, data);
+}
+
+static void writeAttrsAt(
+        const COORD pt,
+        const std::vector<WORD> &data) {
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleOutputAttribute(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        data.data(), data.size(), pt, &actual);
+    assert(ret && actual == data.size());
+}
+
+static void writeCharsAt(
+        const COORD pt,
+        const std::vector<wchar_t> &data) {
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleOutputCharacterW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        data.data(), data.size(), pt, &actual);
+    assert(ret && actual == data.size());
+}
+
+static void writeChars(
+        const std::vector<wchar_t> &data) {
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        data.data(), data.size(), &actual, NULL);
+    assert(ret && actual == data.size());
+}
+
+std::vector<CHAR_INFO> get(
+        const COORD pt,
+        const COORD size) {
+    std::vector<CHAR_INFO> data(size.X * size.Y);
+    SMALL_RECT readRegion = sr(pt, size);
+    BOOL ret = ReadConsoleOutputW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        data.data(), size, {0, 0}, &readRegion);
+    assert(ret && readRegion == sr(pt, size));
+    return data;
+}
+
+std::vector<wchar_t> readCharsAt(
+        const COORD pt,
+        int size) {
+    std::vector<wchar_t> data(size);
+    DWORD actual = 0;
+    BOOL ret = ReadConsoleOutputCharacterW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        data.data(), data.size(), pt, &actual);
+    assert(ret);
+    data.resize(actual); // With double-width chars, we can read fewer than `size`.
+    return data;
+}
+
+static void dump(const COORD pt, const COORD size) {
+    for (CHAR_INFO ci : get(pt, size)) {
+        printf("%04X %04X\n", ci.Char.UnicodeChar, ci.Attributes);
+    }
+}
+
+static void dumpCharsAt(const COORD pt, int size) {
+    for (wchar_t ch : readCharsAt(pt, size)) {
+        printf("%04X\n", ch);
+    }
+}
+
+static COORD getCursorPos() {
+    CONSOLE_SCREEN_BUFFER_INFO info = { sizeof(info) };
+    assert(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info));
+    return info.dwCursorPosition;
+}
+
+static void test1() {
+    // We write "䀀䀀", then write "䀁" in the middle of the two.  The second
+    // write turns the first and last cells into spaces.  The LEADING/TRAILING
+    // flags retain consistency.
+    printf("test1 - overlap full-width char with full-width char\n");
+    writeCharsAt({1,0}, {0x4000, 0x4000});
+    dump({0,0}, {6,1});
+    printf("\n");
+    writeCharsAt({2,0}, {0x4001});
+    dump({0,0}, {6,1});
+    printf("\n");
+}
+
+static void test2() {
+    // Like `test1`, but use a lower-level API to do the write.  Consistency is
+    // preserved here too -- the first and last cells are replaced with spaces.
+    printf("test2 - overlap full-width char with full-width char (lowlevel)\n");
+    writeCharsAt({1,0}, {0x4000, 0x4000});
+    dump({0,0}, {6,1});
+    printf("\n");
+    set({2,0}, {ci(0x4001,0x107), ci(0x4001,0x207)});
+    dump({0,0}, {6,1});
+    printf("\n");
+}
+
+static void test3() {
+    // However, the lower-level API can break the LEADING/TRAILING invariant
+    // explicitly:
+    printf("test3 - explicitly violate LEADING/TRAILING using lowlevel API\n");
+    set({1,0}, {
+        ci(0x4000, 0x207),
+        ci(0x4001, 0x107),
+        ci(0x3044, 7),
+        ci(L'X', 0x107),
+        ci(L'X', 0x207),
+    });
+    dump({0,0}, {7,1});
+}
+
+static void test4() {
+    // It is possible for the two cells of a double-width character to have two
+    // colors.
+    printf("test4 - use lowlevel to assign two colors to one full-width char\n");
+    set({0,0}, {
+        ci(0x4000, 0x142),
+        ci(0x4000, 0x224),
+    });
+    dump({0,0}, {2,1});
+}
+
+static void test5() {
+    // WriteConsoleOutputAttribute doesn't seem to affect the LEADING/TRAILING
+    // flags.
+    printf("test5 - WriteConsoleOutputAttribute cannot affect LEADING/TRAILING\n");
+
+    // Trying to clear the flags doesn't work...
+    writeCharsAt({0,0}, {0x4000});
+    dump({0,0}, {2,1});
+    writeAttrsAt({0,0}, {0x42, 0x24});
+    printf("\n");
+    dump({0,0}, {2,1});
+
+    // ... and trying to add them also doesn't work.
+    writeCharsAt({0,1}, {'A', ' '});
+    writeAttrsAt({0,1}, {0x107, 0x207});
+    printf("\n");
+    dump({0,1}, {2,1});
+}
+
+static void test6() {
+    // The cursor position may be on either cell of a double-width character.
+    // Visually, the cursor appears under both cells, regardless of which
+    // specific one has the cursor.
+    printf("test6 - cursor can be either left or right cell of full-width char\n");
+
+    writeCharsAt({2,1}, {0x4000});
+
+    setCursorPos(2, 1);
+    auto pos1 = getCursorPos();
+    Sleep(1000);
+
+    setCursorPos(3, 1);
+    auto pos2 = getCursorPos();
+    Sleep(1000);
+
+    setCursorPos(0, 15);
+    printf("%d,%d\n", pos1.X, pos1.Y);
+    printf("%d,%d\n", pos2.X, pos2.Y);
+}
+
+static void runTest(void (&test)()) {
+    system("cls");
+    setCursorPos(0, 14);
+    test();
+    system("pause");
+}
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(80, 40);
+    setWindowPos(0, 0, 80, 40);
+
+    auto cp = GetConsoleOutputCP();
+    assert(cp == 932 || cp == 936 || cp == 949 || cp == 950);
+
+    runTest(test1);
+    runTest(test2);
+    runTest(test3);
+    runTest(test4);
+    runTest(test5);
+    runTest(test6);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/UnicodeWideTest2.cc b/node_modules/node-pty/deps/winpty/misc/UnicodeWideTest2.cc
new file mode 100644 (file)
index 0000000..05f80f7
--- /dev/null
@@ -0,0 +1,130 @@
+//
+// Test half-width vs full-width characters.
+//
+
+#include <windows.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "TestUtil.cc"
+
+static void writeChars(const wchar_t *text) {
+    wcslen(text);
+    const int len = wcslen(text);
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        text, len, &actual, NULL);
+    trace("writeChars: ret=%d, actual=%lld", ret, (long long)actual);
+}
+
+static void dumpChars(int x, int y, int w, int h) {
+    BOOL ret;
+    const COORD bufSize = {w, h};
+    const COORD bufCoord = {0, 0};
+    const SMALL_RECT topLeft = {x, y, x + w - 1, y + h - 1};
+    CHAR_INFO mbcsData[w * h];
+    CHAR_INFO unicodeData[w * h];
+    SMALL_RECT readRegion;
+    readRegion = topLeft;
+    ret = ReadConsoleOutputW(GetStdHandle(STD_OUTPUT_HANDLE), unicodeData,
+                             bufSize, bufCoord, &readRegion);
+    assert(ret);
+    readRegion = topLeft;
+    ret = ReadConsoleOutputA(GetStdHandle(STD_OUTPUT_HANDLE), mbcsData,
+                             bufSize, bufCoord, &readRegion);
+    assert(ret);
+
+    printf("\n");
+    for (int i = 0; i < w * h; ++i) {
+        printf("(%02d,%02d) CHAR: %04x %4x -- %02x %4x\n",
+            x + i % w, y + i / w,
+            (unsigned short)unicodeData[i].Char.UnicodeChar,
+            (unsigned short)unicodeData[i].Attributes,
+            (unsigned char)mbcsData[i].Char.AsciiChar,
+            (unsigned short)mbcsData[i].Attributes);
+    }
+}
+
+int main(int argc, char *argv[]) {
+    system("cls");
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(80, 38);
+    setWindowPos(0, 0, 80, 38);
+
+    // Write text.
+    const wchar_t text1[] = {
+        0x3044, // U+3044 (HIRAGANA LETTER I)
+        0x2014, // U+2014 (EM DASH)
+        0x3044, // U+3044 (HIRAGANA LETTER I)
+        0xFF2D, // U+FF2D (FULLWIDTH LATIN CAPITAL LETTER M)
+        0x30FC, // U+30FC (KATAKANA-HIRAGANA PROLONGED SOUND MARK)
+        0x0031, // U+3031 (DIGIT ONE)
+        0x2014, // U+2014 (EM DASH)
+        0x0032, // U+0032 (DIGIT TWO)
+        0x005C, // U+005C (REVERSE SOLIDUS)
+        0x3044, // U+3044 (HIRAGANA LETTER I)
+        0
+    };
+    setCursorPos(0, 0);
+    writeChars(text1);
+
+    setCursorPos(78, 1);
+    writeChars(L"<>");
+
+    const wchar_t text2[] = {
+        0x0032, // U+3032 (DIGIT TWO)
+        0x3044, // U+3044 (HIRAGANA LETTER I)
+        0,
+    };
+    setCursorPos(78, 1);
+    writeChars(text2);
+
+    system("pause");
+
+    dumpChars(0, 0, 17, 1);
+    dumpChars(2, 0, 2, 1);
+    dumpChars(2, 0, 1, 1);
+    dumpChars(3, 0, 1, 1);
+    dumpChars(78, 1, 2, 1);
+    dumpChars(0, 2, 2, 1);
+
+    system("pause");
+    system("cls");
+
+    const wchar_t text3[] = {
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 1
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 2
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 3
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 4
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 5
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 6
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 7
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 8
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 9
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 10
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 11
+        0x30FC, 0x30FC, 0x30FC, 0xFF2D, // 12
+        L'\r', '\n',
+        L'\r', '\n',
+        0
+    };
+    writeChars(text3);
+    system("pause");
+    {
+        const COORD bufSize = {80, 2};
+        const COORD bufCoord = {0, 0};
+        SMALL_RECT readRegion = {0, 0, 79, 1};
+        CHAR_INFO unicodeData[160];
+        BOOL ret = ReadConsoleOutputW(GetStdHandle(STD_OUTPUT_HANDLE), unicodeData,
+                                 bufSize, bufCoord, &readRegion);
+        assert(ret);
+        for (int i = 0; i < 96; ++i) {
+            printf("%04x ", unicodeData[i].Char.UnicodeChar);
+        }
+        printf("\n");
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/UnixEcho.cc b/node_modules/node-pty/deps/winpty/misc/UnixEcho.cc
new file mode 100644 (file)
index 0000000..372e045
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Unix test code that puts the terminal into raw mode, then echos typed
+ * characters to stdout.  Derived from sample code in the Stevens book, posted
+ * online at http://www.lafn.org/~dave/linux/terminalIO.html.
+ */
+
+#include <termios.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include "FormatChar.h"
+
+static struct termios   save_termios;
+static int              term_saved;
+
+/* RAW! mode */
+int tty_raw(int fd)
+{
+    struct termios  buf;
+
+    if (tcgetattr(fd, &save_termios) < 0) /* get the original state */
+        return -1;
+
+    buf = save_termios;
+
+    /* echo off, canonical mode off, extended input
+       processing off, signal chars off */
+    buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+
+    /* no SIGINT on BREAK, CR-to-NL off, input parity
+       check off, don't strip the 8th bit on input,
+       ouput flow control off */
+    buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
+
+    /* clear size bits, parity checking off */
+    buf.c_cflag &= ~(CSIZE | PARENB);
+
+    /* set 8 bits/char */
+    buf.c_cflag |= CS8;
+
+    /* output processing off */
+    buf.c_oflag &= ~(OPOST);
+
+    buf.c_cc[VMIN] = 1;  /* 1 byte at a time */
+    buf.c_cc[VTIME] = 0; /* no timer on input */
+
+    if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
+        return -1;
+
+    term_saved = 1;
+
+    return 0;
+}
+
+
+/* set it to normal! */
+int tty_reset(int fd)
+{
+    if (term_saved)
+        if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)
+            return -1;
+
+    return 0;
+}
+
+
+int main()
+{
+    tty_raw(0);
+
+    int count = 0;
+    while (true) {
+        char ch;
+        char buf[16];
+        int actual = read(0, &ch, 1);
+        if (actual != 1) {
+            perror("read error");
+            break;
+        }
+        formatChar(buf, ch);
+        fputs(buf, stdout);
+        fflush(stdout);
+        if (ch == 3) // Ctrl-C
+            break;
+    }
+
+    tty_reset(0);
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Utf16Echo.cc b/node_modules/node-pty/deps/winpty/misc/Utf16Echo.cc
new file mode 100644 (file)
index 0000000..ef5f302
--- /dev/null
@@ -0,0 +1,46 @@
+#include <windows.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include <vector>
+#include <string>
+
+int main(int argc, char *argv[]) {
+    system("cls");
+
+    if (argc == 1) {
+        printf("Usage: %s hhhh\n", argv[0]);
+        return 0;
+    }
+
+    std::wstring dataToWrite;
+    for (int i = 1; i < argc; ++i) {
+        wchar_t ch = strtol(argv[i], NULL, 16);
+        dataToWrite.push_back(ch);
+    }
+
+    DWORD actual = 0;
+    BOOL ret = WriteConsoleW(
+        GetStdHandle(STD_OUTPUT_HANDLE),
+        dataToWrite.data(), dataToWrite.size(), &actual, NULL);
+    assert(ret && actual == dataToWrite.size());
+
+    // Read it back.
+    std::vector<CHAR_INFO> readBuffer(dataToWrite.size() * 2);
+    COORD bufSize = {static_cast<short>(readBuffer.size()), 1};
+    COORD bufCoord = {0, 0};
+    SMALL_RECT topLeft = {0, 0, static_cast<short>(readBuffer.size() - 1), 0};
+    ret = ReadConsoleOutputW(
+            GetStdHandle(STD_OUTPUT_HANDLE), readBuffer.data(),
+            bufSize, bufCoord, &topLeft);
+    assert(ret);
+
+    printf("\n");
+    for (int i = 0; i < readBuffer.size(); ++i) {
+        printf("CHAR: %04x %04x\n",
+            readBuffer[i].Char.UnicodeChar,
+            readBuffer[i].Attributes);
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/VeryLargeRead.cc b/node_modules/node-pty/deps/winpty/misc/VeryLargeRead.cc
new file mode 100644 (file)
index 0000000..58f0897
--- /dev/null
@@ -0,0 +1,122 @@
+//
+// 2015-09-25
+// I measured these limits on the size of a single ReadConsoleOutputW call.
+// The limit seems to more-or-less disppear with Windows 8, which is the first
+// OS to stop using ALPCs for console I/O.  My guess is that the new I/O
+// method does not use the 64KiB shared memory buffer that the ALPC method
+// uses.
+//
+// I'm guessing the remaining difference between Windows 8/8.1 and Windows 10
+// might be related to the 32-vs-64-bitness.
+//
+// Client OSs
+//
+// Windows XP 32-bit VM ==> up to 13304 characters
+//  - 13304x1 works, but 13305x1 fails instantly
+// Windows 7 32-bit VM ==> between 16-17 thousand characters
+//  - 16000x1 works, 17000x1 fails instantly
+//  - 163x100 *crashes* conhost.exe but leaves VeryLargeRead.exe running
+// Windows 8 32-bit VM ==> between 240-250 million characters
+//  - 10000x24000 works, but 10000x25000 does not
+// Windows 8.1 32-bit VM ==> between 240-250 million characters
+//  - 10000x24000 works, but 10000x25000 does not
+// Windows 10 64-bit VM ==> no limit (tested to 576 million characters)
+//  - 24000x24000 works
+//  - `ver` reports [Version 10.0.10240], conhost.exe and ConhostV1.dll are
+//    10.0.10240.16384 for file and product version.  ConhostV2.dll is
+//    10.0.10240.16391 for file and product version.
+//
+// Server OSs
+//
+// Windows Server 2008 64-bit VM ==> 14300-14400 characters
+//  - 14300x1 works, 14400x1 fails instantly
+//  - This OS does not have conhost.exe.
+//  - `ver` reports [Version 6.0.6002]
+// Windows Server 2008 R2 64-bit VM ==> 15600-15700 characters
+//  - 15600x1 works, 15700x1 fails instantly
+//  - This OS has conhost.exe, and procexp.exe reveals console ALPC ports in
+//    use in conhost.exe.
+//  - `ver` reports [Version 6.1.7601], conhost.exe is 6.1.7601.23153 for file
+//    and product version.
+// Windows Server 2012 64-bit VM ==> at least 100 million characters
+//  - 10000x10000 works (VM had only 1GiB of RAM, so I skipped larger tests)
+//  - This OS has Windows 8's task manager and procexp.exe reveals the same
+//    lack of ALPC ports and the same \Device\ConDrv\* files as Windows 8.
+//  - `ver` reports [Version 6.2.9200], conhost.exe is 6.2.9200.16579 for file
+//    and product version.
+//
+// To summarize:
+//
+// client-OS    server-OS               notes
+// ---------------------------------------------------------------------------
+// XP           Server 2008             CSRSS, small reads
+// 7            Server 2008 R2          ALPC-to-conhost, small reads
+// 8, 8.1       Server 2012             new I/O interface, large reads allowed
+// 10           <no server OS yet>      enhanced console w/rewrapping
+//
+// (Presumably, Win2K, Vista, and Win2K3 behave the same as XP.  conhost.exe
+// was announced as a Win7 feature.)
+//
+
+#include <windows.h>
+#include <assert.h>
+#include <vector>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    long long width = 9000;
+    long long height = 9000;
+
+    assert(argc >= 1);
+    if (argc == 4) {
+        width = atoi(argv[2]);
+        height = atoi(argv[3]);
+    } else {
+        if (argc == 3) {
+            width = atoi(argv[1]);
+            height = atoi(argv[2]);
+        }
+        wchar_t args[1024];
+        swprintf(args, 1024, L"CHILD %lld %lld", width, height);
+        startChildProcess(args);
+        return 0;
+    }
+
+    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(width, height);
+    setWindowPos(0, 0, std::min(80LL, width), std::min(50LL, height));
+
+    setCursorPos(0, 0);
+    printf("A");
+    fflush(stdout);
+    setCursorPos(width - 2, height - 1);
+    printf("B");
+    fflush(stdout);
+
+    trace("sizeof(CHAR_INFO) = %d", (int)sizeof(CHAR_INFO));
+
+    trace("Allocating buffer...");
+    CHAR_INFO *buffer = new CHAR_INFO[width * height];
+    assert(buffer != NULL);
+    memset(&buffer[0], 0, sizeof(CHAR_INFO));
+    memset(&buffer[width * height - 2], 0, sizeof(CHAR_INFO));
+
+    COORD bufSize = { width, height };
+    COORD bufCoord = { 0, 0 };
+    SMALL_RECT readRegion = { 0, 0, width - 1, height - 1 };
+    trace("ReadConsoleOutputW: calling...");
+    BOOL success = ReadConsoleOutputW(conout, buffer, bufSize, bufCoord, &readRegion);
+    trace("ReadConsoleOutputW: success=%d", success);
+
+    assert(buffer[0].Char.UnicodeChar == L'A');
+    assert(buffer[width * height - 2].Char.UnicodeChar == L'B');
+    trace("Top-left and bottom-right characters read successfully!");
+
+    Sleep(30000);
+
+    delete [] buffer;
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/VkEscapeTest.cc b/node_modules/node-pty/deps/winpty/misc/VkEscapeTest.cc
new file mode 100644 (file)
index 0000000..97bf59f
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Sending VK_PAUSE to the console window almost works as a mechanism for
+ * pausing it, but it doesn't because the console could turn off the
+ * ENABLE_LINE_INPUT console mode flag.
+ */
+
+#define _WIN32_WINNT 0x0501
+#include <stdio.h>
+#include <stdlib.h>
+#include <windows.h>
+
+CALLBACK DWORD pausingThread(LPVOID dummy)
+{
+    if (1) {
+        Sleep(1000);
+        HWND hwnd = GetConsoleWindow();
+        SendMessage(hwnd, WM_KEYDOWN, VK_PAUSE, 1);
+        Sleep(1000);
+        SendMessage(hwnd, WM_KEYDOWN, VK_ESCAPE, 1);
+    }
+
+    if (0) {
+        INPUT_RECORD ir;
+        memset(&ir, 0, sizeof(ir));
+        ir.EventType = KEY_EVENT;
+        ir.Event.KeyEvent.bKeyDown = TRUE;
+        ir.Event.KeyEvent.wVirtualKeyCode = VK_PAUSE;
+        ir.Event.KeyEvent.wRepeatCount = 1;
+    }
+
+    return 0;
+}
+
+int main()
+{
+    HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
+    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
+    COORD c = { 0, 0 };
+
+    DWORD mode;
+    GetConsoleMode(hin, &mode);
+    SetConsoleMode(hin, mode &
+                   ~(ENABLE_LINE_INPUT));
+
+    CreateThread(NULL, 0,
+                 pausingThread, NULL,
+                 0, NULL);
+
+    int i = 0;
+    while (true) {
+        Sleep(100);
+        printf("%d\n", ++i);
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win10ResizeWhileFrozen.cc b/node_modules/node-pty/deps/winpty/misc/Win10ResizeWhileFrozen.cc
new file mode 100644 (file)
index 0000000..82feaf3
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Demonstrates a conhost hang that occurs when widening the console buffer
+ * while selection is in progress.  The problem affects the new Windows 10
+ * console, not the "legacy" console mode that Windows 10 also includes.
+ *
+ * First tested with:
+ *  - Windows 10.0.10240
+ *  - conhost.exe version 10.0.10240.16384
+ *  - ConhostV1.dll version 10.0.10240.16384
+ *  - ConhostV2.dll version 10.0.10240.16391
+ */
+
+#include <windows.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <wchar.h>
+
+#include "TestUtil.cc"
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(80, 25);
+    setWindowPos(0, 0, 80, 25);
+
+    countDown(5);
+
+    SendMessage(GetConsoleWindow(), WM_SYSCOMMAND, SC_CONSOLE_SELECT_ALL, 0);
+    Sleep(2000);
+
+    // This API call does not return.  In the console window, the "Select All"
+    // operation appears to end.  The console window becomes non-responsive,
+    // and the conhost.exe process must be killed from the Task Manager.
+    // (Killing this test program or closing the console window is not
+    // sufficient.)
+    //
+    // The same hang occurs whether line resizing is off or on.  It happens
+    // with both "Mark" and "Select All".  Calling setBufferSize with the
+    // existing buffer size does not hang, but calling it with only a changed
+    // buffer height *does* hang.  Calling setWindowPos does not hang.
+    setBufferSize(120, 25);
+
+    printf("Done...\n");
+    Sleep(2000);
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win10WrapTest1.cc b/node_modules/node-pty/deps/winpty/misc/Win10WrapTest1.cc
new file mode 100644 (file)
index 0000000..645fa95
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Demonstrates some wrapping behaviors of the new Windows 10 console.
+ */
+
+#include <windows.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(40, 20);
+    setWindowPos(0, 0, 40, 20);
+
+    system("cls");
+
+    repeatChar(39, 'A'); repeatChar(1, ' ');
+    repeatChar(39, 'B'); repeatChar(1, ' ');
+    printf("\n");
+
+    repeatChar(39, 'C'); repeatChar(1, ' ');
+    repeatChar(39, 'D'); repeatChar(1, ' ');
+    printf("\n");
+
+    repeatChar(40, 'E');
+    repeatChar(40, 'F');
+    printf("\n");
+
+    repeatChar(39, 'G'); repeatChar(1, ' ');
+    repeatChar(39, 'H'); repeatChar(1, ' ');
+    printf("\n");
+
+    Sleep(2000);
+
+    setChar(39, 0, '*', 0x24);
+    setChar(39, 1, '*', 0x24);
+
+    setChar(39, 3, ' ', 0x24);
+    setChar(39, 4, ' ', 0x24);
+
+    setChar(38, 6, ' ', 0x24);
+    setChar(38, 7, ' ', 0x24);
+
+    Sleep(2000);
+    setWindowPos(0, 0, 35, 20);
+    setBufferSize(35, 20);
+    trace("DONE");
+
+    printf("Sleeping forever...\n");
+    while(true) { Sleep(1000); }
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win10WrapTest2.cc b/node_modules/node-pty/deps/winpty/misc/Win10WrapTest2.cc
new file mode 100644 (file)
index 0000000..50615fc
--- /dev/null
@@ -0,0 +1,30 @@
+#include <windows.h>
+
+#include "TestUtil.cc"
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        startChildProcess(L"CHILD");
+        return 0;
+    }
+
+    const int WIDTH = 25;
+
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(WIDTH, 40);
+    setWindowPos(0, 0, WIDTH, 20);
+
+    system("cls");
+
+    for (int i = 0; i < 100; ++i) {
+        printf("FOO(%d)\n", i);
+    }
+
+    repeatChar(5, '\n');
+    repeatChar(WIDTH * 5, '.');
+    repeatChar(10, '\n');
+    setWindowPos(0, 20, WIDTH, 20);
+    writeBox(0, 5, 1, 10, '|');
+
+    Sleep(120000);
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win32Echo1.cc b/node_modules/node-pty/deps/winpty/misc/Win32Echo1.cc
new file mode 100644 (file)
index 0000000..06fc79f
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * A Win32 program that reads raw console input with ReadFile and echos
+ * it to stdout.
+ */
+
+#include <stdio.h>
+#include <conio.h>
+#include <windows.h>
+
+int main()
+{
+    int count = 0;
+    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
+    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
+    SetConsoleMode(hStdIn, 0);
+
+    while (true) {
+        DWORD actual;
+        char ch;
+        ReadFile(hStdIn, &ch, 1, &actual, NULL);
+        printf("%02x ", ch);
+        if (++count == 50)
+            break;
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win32Echo2.cc b/node_modules/node-pty/deps/winpty/misc/Win32Echo2.cc
new file mode 100644 (file)
index 0000000..b2ea2ad
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * A Win32 program that reads raw console input with getch and echos
+ * it to stdout.
+ */
+
+#include <stdio.h>
+#include <conio.h>
+
+int main()
+{
+    int count = 0;
+    while (true) {
+        int ch = getch();
+        printf("%02x ", ch);
+        if (++count == 50)
+            break;
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win32Test1.cc b/node_modules/node-pty/deps/winpty/misc/Win32Test1.cc
new file mode 100644 (file)
index 0000000..a40d318
--- /dev/null
@@ -0,0 +1,46 @@
+#define _WIN32_WINNT 0x0501
+#include "../src/shared/DebugClient.cc"
+#include <windows.h>
+#include <stdio.h>
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+
+CALLBACK DWORD writerThread(void*)
+{
+    while (true) {
+        Sleep(1000);
+        trace("writing");
+        printf("X\n");
+        trace("written");
+    }
+}
+
+int main()
+{
+    CreateThread(NULL, 0, writerThread, NULL, 0, NULL);
+    trace("marking console");
+    HWND hwnd = GetConsoleWindow();
+    PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
+
+    Sleep(2000);
+
+    trace("reading output");
+    CHAR_INFO buf[1];
+    COORD bufSize = { 1, 1 };
+    COORD zeroCoord = { 0, 0 };
+    SMALL_RECT readRect = { 0, 0, 0, 0 };
+    ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
+                      buf,
+                      bufSize,
+                      zeroCoord,
+                      &readRect);
+    trace("done reading output");
+
+    Sleep(2000);
+
+    PostMessage(hwnd, WM_CHAR, 27, 0x00010001);
+
+    Sleep(1100);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win32Test2.cc b/node_modules/node-pty/deps/winpty/misc/Win32Test2.cc
new file mode 100644 (file)
index 0000000..2777bad
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * This test demonstrates that putting a console into selection mode does not
+ * block the low-level console APIs, even though it blocks WriteFile.
+ */
+
+#define _WIN32_WINNT 0x0501
+#include "../src/shared/DebugClient.cc"
+#include <windows.h>
+#include <stdio.h>
+
+const int SC_CONSOLE_MARK = 0xFFF2;
+
+CALLBACK DWORD writerThread(void*)
+{
+    CHAR_INFO xChar, fillChar;
+    memset(&xChar, 0, sizeof(xChar));
+    xChar.Char.AsciiChar = 'X';
+    xChar.Attributes = 7;
+    memset(&fillChar, 0, sizeof(fillChar));
+    fillChar.Char.AsciiChar = ' ';
+    fillChar.Attributes = 7;
+    COORD oneCoord = { 1, 1 };
+    COORD zeroCoord = { 0, 0 };
+
+    while (true) {
+        SMALL_RECT writeRegion = { 5, 5, 5, 5 };
+        WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
+                           &xChar, oneCoord,
+                           zeroCoord,
+                           &writeRegion);
+        Sleep(500);
+        SMALL_RECT scrollRect = { 1, 1, 20, 20 };
+        COORD destCoord = { 0, 0 };
+        ScrollConsoleScreenBuffer(GetStdHandle(STD_OUTPUT_HANDLE),
+                                  &scrollRect,
+                                  NULL,
+                                  destCoord,
+                                  &fillChar);
+    }
+}
+
+int main()
+{
+    CreateThread(NULL, 0, writerThread, NULL, 0, NULL);
+    trace("marking console");
+    HWND hwnd = GetConsoleWindow();
+    PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);
+
+    Sleep(2000);
+
+    trace("reading output");
+    CHAR_INFO buf[1];
+    COORD bufSize = { 1, 1 };
+    COORD zeroCoord = { 0, 0 };
+    SMALL_RECT readRect = { 0, 0, 0, 0 };
+    ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
+                      buf,
+                      bufSize,
+                      zeroCoord,
+                      &readRect);
+    trace("done reading output");
+
+    Sleep(2000);
+
+    PostMessage(hwnd, WM_CHAR, 27, 0x00010001);
+
+    Sleep(1100);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win32Test3.cc b/node_modules/node-pty/deps/winpty/misc/Win32Test3.cc
new file mode 100644 (file)
index 0000000..1fb92af
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * Creates a window station and starts a process under it.  The new process
+ * also gets a new console.
+ */
+
+#include <windows.h>
+#include <string.h>
+#include <stdio.h>
+
+int main()
+{
+    BOOL success;
+
+    SECURITY_ATTRIBUTES sa;
+    memset(&sa, 0, sizeof(sa));
+    sa.bInheritHandle = TRUE;
+
+    HWINSTA originalStation = GetProcessWindowStation();
+    printf("originalStation == 0x%x\n", originalStation);
+    HWINSTA station = CreateWindowStation(NULL,
+                                          0,
+                                          WINSTA_ALL_ACCESS,
+                                          &sa);
+    printf("station == 0x%x\n", station);
+    if (!SetProcessWindowStation(station))
+        printf("SetWindowStation failed!\n");
+    HDESK desktop = CreateDesktop("Default", NULL, NULL,
+                                  /*dwFlags=*/0, GENERIC_ALL,
+                                  &sa);
+    printf("desktop = 0x%x\n", desktop);
+
+    char stationName[256];
+    stationName[0] = '\0';
+    success = GetUserObjectInformation(station, UOI_NAME, 
+                                       stationName, sizeof(stationName),
+                                       NULL);
+    printf("stationName = [%s]\n", stationName);
+
+    char startupDesktop[256];
+    sprintf(startupDesktop, "%s\\Default", stationName);
+
+    STARTUPINFO sui;
+    PROCESS_INFORMATION pi;
+    memset(&sui, 0, sizeof(sui));
+    memset(&pi, 0, sizeof(pi));
+    sui.cb = sizeof(STARTUPINFO);
+    sui.lpDesktop = startupDesktop;
+
+    // Start a cmd subprocess, and have it start its own cmd subprocess.
+    // Both subprocesses will connect to the same non-interactive window
+    // station.
+
+    const char program[] = "c:\\windows\\system32\\cmd.exe";
+    char cmdline[256];
+    sprintf(cmdline, "%s /c cmd", program);
+    success = CreateProcess(program,
+                            cmdline,
+                            NULL,
+                            NULL,
+                            /*bInheritHandles=*/FALSE,
+                            /*dwCreationFlags=*/CREATE_NEW_CONSOLE,
+                            NULL, NULL,
+                            &sui,
+                            &pi);
+
+    printf("pid == %d\n", pi.dwProcessId);
+
+    // This sleep is necessary.  We must give the child enough time to
+    // connect to the specified window station.
+    Sleep(5000);
+
+    SetProcessWindowStation(originalStation);
+    CloseWindowStation(station);
+    CloseDesktop(desktop);
+    Sleep(5000);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/Win32Write1.cc b/node_modules/node-pty/deps/winpty/misc/Win32Write1.cc
new file mode 100644 (file)
index 0000000..6e5bf96
--- /dev/null
@@ -0,0 +1,44 @@
+/* 
+ * A Win32 program that scrolls and writes to the console using the ioctl-like
+ * interface.
+ */
+
+#include <stdio.h>
+#include <windows.h>
+
+int main()
+{
+    HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    for (int i = 0; i < 80; ++i) {
+
+        CONSOLE_SCREEN_BUFFER_INFO info;
+        GetConsoleScreenBufferInfo(conout, &info);
+
+        SMALL_RECT src = { 0, 1, info.dwSize.X - 1, info.dwSize.Y - 1 };
+        COORD destOrigin = { 0, 0 };
+        CHAR_INFO fillCharInfo = { 0 };
+        fillCharInfo.Char.AsciiChar = ' ';
+        fillCharInfo.Attributes = 7;
+        ScrollConsoleScreenBuffer(conout,
+                                  &src,
+                                  NULL,
+                                  destOrigin,
+                                  &fillCharInfo);
+
+        CHAR_INFO buffer = { 0 };
+        buffer.Char.AsciiChar = 'X';
+        buffer.Attributes = 7;
+        COORD bufferSize = { 1, 1 };
+        COORD bufferCoord = { 0, 0 };
+        SMALL_RECT writeRegion = { 0, 0, 0, 0 };
+        writeRegion.Left = writeRegion.Right = i;
+        writeRegion.Top = writeRegion.Bottom = 5;
+        WriteConsoleOutput(conout, 
+                           &buffer, bufferSize, bufferCoord,
+                           &writeRegion);
+
+        Sleep(250);
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/WindowsBugCrashReader.cc b/node_modules/node-pty/deps/winpty/misc/WindowsBugCrashReader.cc
new file mode 100644 (file)
index 0000000..e6d9558
--- /dev/null
@@ -0,0 +1,27 @@
+// I noticed this on the ConEmu web site:
+//
+// https://social.msdn.microsoft.com/Forums/en-US/40c8e395-cca9-45c8-b9b8-2fbe6782ac2b/readconsoleoutput-cause-access-violation-writing-location-exception
+// https://conemu.github.io/en/MicrosoftBugs.html
+//
+// In Windows 7, 8, and 8.1, a ReadConsoleOutputW with an out-of-bounds read
+// region crashes the application.  I have reproduced the problem on Windows 8
+// and 8.1, but not on Windows 7.
+//
+
+#include <windows.h>
+
+#include "TestUtil.cc"
+
+int main() {
+    setWindowPos(0, 0, 1, 1);
+    setBufferSize(80, 25);
+    setWindowPos(0, 0, 80, 25);
+
+    const HANDLE conout = openConout();
+    static CHAR_INFO lineBuf[80];
+    SMALL_RECT readRegion = { 0, 999, 79, 999 };
+    const BOOL ret = ReadConsoleOutputW(conout, lineBuf, {80, 1}, {0, 0}, &readRegion);
+    ASSERT(!ret && "ReadConsoleOutputW should have failed");
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/WriteConsole.cc b/node_modules/node-pty/deps/winpty/misc/WriteConsole.cc
new file mode 100644 (file)
index 0000000..a03670c
--- /dev/null
@@ -0,0 +1,106 @@
+#include <windows.h>
+
+#include <assert.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include <string>
+#include <vector>
+
+static std::wstring mbsToWcs(const std::string &s) {
+    const size_t len = mbstowcs(nullptr, s.c_str(), 0);
+    if (len == static_cast<size_t>(-1)) {
+        assert(false && "mbsToWcs: invalid string");
+    }
+    std::wstring ret;
+    ret.resize(len);
+    const size_t len2 = mbstowcs(&ret[0], s.c_str(), len);
+    assert(len == len2);
+    return ret;
+}
+
+uint32_t parseHex(wchar_t ch, bool &invalid) {
+    if (ch >= L'0' && ch <= L'9') {
+        return ch - L'0';
+    } else if (ch >= L'a' && ch <= L'f') {
+        return ch - L'a' + 10;
+    } else if (ch >= L'A' && ch <= L'F') {
+        return ch - L'A' + 10;
+    } else {
+        invalid = true;
+        return 0;
+    }
+}
+
+int main(int argc, char *argv[]) {
+    std::vector<std::wstring> args;
+    for (int i = 1; i < argc; ++i) {
+        args.push_back(mbsToWcs(argv[i]));
+    }
+
+    std::wstring out;
+    for (const auto &arg : args) {
+        if (!out.empty()) {
+            out.push_back(L' ');
+        }
+        for (size_t i = 0; i < arg.size(); ++i) {
+            wchar_t ch = arg[i];
+            wchar_t nch = i + 1 < arg.size() ? arg[i + 1] : L'\0';
+            if (ch == L'\\') {
+                switch (nch) {
+                    case L'a':  ch = L'\a'; ++i; break;
+                    case L'b':  ch = L'\b'; ++i; break;
+                    case L'e':  ch = L'\x1b'; ++i; break;
+                    case L'f':  ch = L'\f'; ++i; break;
+                    case L'n':  ch = L'\n'; ++i; break;
+                    case L'r':  ch = L'\r'; ++i; break;
+                    case L't':  ch = L'\t'; ++i; break;
+                    case L'v':  ch = L'\v'; ++i; break;
+                    case L'\\': ch = L'\\'; ++i; break;
+                    case L'\'': ch = L'\''; ++i; break;
+                    case L'\"': ch = L'\"'; ++i; break;
+                    case L'\?': ch = L'\?'; ++i; break;
+                    case L'x':
+                        if (i + 3 < arg.size()) {
+                            bool invalid = false;
+                            uint32_t d1 = parseHex(arg[i + 2], invalid);
+                            uint32_t d2 = parseHex(arg[i + 3], invalid);
+                            if (!invalid) {
+                                i += 3;
+                                ch = (d1 << 4) | d2;
+                            }
+                        }
+                        break;
+                    case L'u':
+                        if (i + 5 < arg.size()) {
+                            bool invalid = false;
+                            uint32_t d1 = parseHex(arg[i + 2], invalid);
+                            uint32_t d2 = parseHex(arg[i + 3], invalid);
+                            uint32_t d3 = parseHex(arg[i + 4], invalid);
+                            uint32_t d4 = parseHex(arg[i + 5], invalid);
+                            if (!invalid) {
+                                i += 5;
+                                ch = (d1 << 24) | (d2 << 16) | (d3 << 8) | d4;
+                            }
+                        }
+                        break;
+                    default: break;
+                }
+            }
+            out.push_back(ch);
+        }
+    }
+
+    DWORD actual = 0;
+    if (!WriteConsoleW(
+            GetStdHandle(STD_OUTPUT_HANDLE),
+            out.c_str(),
+            out.size(),
+            &actual,
+            nullptr)) {
+        fprintf(stderr, "WriteConsole failed (is stdout a console?)\n");
+        exit(1);
+    }
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/misc/build32.sh b/node_modules/node-pty/deps/winpty/misc/build32.sh
new file mode 100644 (file)
index 0000000..162993c
--- /dev/null
@@ -0,0 +1,9 @@
+#!/bin/bash
+set -e
+name=$1
+name=${name%.}
+name=${name%.cc}
+name=${name%.exe}
+echo Compiling $name.cc to $name.exe
+i686-w64-mingw32-g++.exe -static -std=c++11 $name.cc -o $name.exe
+i686-w64-mingw32-strip $name.exe
diff --git a/node_modules/node-pty/deps/winpty/misc/build64.sh b/node_modules/node-pty/deps/winpty/misc/build64.sh
new file mode 100644 (file)
index 0000000..6757967
--- /dev/null
@@ -0,0 +1,9 @@
+#!/bin/bash
+set -e
+name=$1
+name=${name%.}
+name=${name%.cc}
+name=${name%.exe}
+echo Compiling $name.cc to $name.exe
+x86_64-w64-mingw32-g++.exe -static -std=c++11 $name.cc -o $name.exe
+x86_64-w64-mingw32-strip $name.exe
diff --git a/node_modules/node-pty/deps/winpty/misc/color-test.sh b/node_modules/node-pty/deps/winpty/misc/color-test.sh
new file mode 100644 (file)
index 0000000..065c809
--- /dev/null
@@ -0,0 +1,212 @@
+#!/bin/bash
+
+FORE=$1
+BACK=$2
+FILL=$3
+
+if [ "$FORE" = "" ]; then
+    FORE=DefaultFore
+fi
+if [ "$BACK" = "" ]; then
+    BACK=DefaultBack
+fi
+
+# To detect color changes, we want a character that fills the whole cell
+# if possible.  U+2588 is perfect, except that it becomes invisible in the
+# original xterm, when bolded.  For that terminal, use something else, like
+# "#" or "@".
+if [ "$FILL" = "" ]; then
+    FILL="█"
+fi
+
+# SGR (Select Graphic Rendition)
+s() {
+    printf '\033[0m'
+    while [ "$1" != "" ]; do
+        printf '\033['"$1"'m'
+        shift
+    done
+}
+
+# Print
+p() {
+    echo -n "$@"
+}
+
+# Print with newline
+pn() {
+    echo "$@"
+}
+
+# For practical reasons, sandwich black and white in-between the other colors.
+FORE_COLORS="31 30 37 32 33 34 35 36"
+BACK_COLORS="41 40 47 42 43 44 45 46"
+
+
+
+### Test order of Invert(7) -- it does not matter what order it appears in.
+
+# The Red color setting here (31) is shadowed by the green setting (32).  The
+# Reverse flag does not cause (32) to alter the background color immediately;
+# instead, the Reverse flag is applied once to determine the final effective
+# Fore/Back colors.
+s 7 31 32; p " -- Should be: $BACK-on-green -- "; s; pn
+s 31 7 32; p " -- Should be: $BACK-on-green -- "; s; pn
+s 31 32 7; p " -- Should be: $BACK-on-green -- "; s; pn
+
+# As above, but for the background color.
+s 7 41 42; p " -- Should be: green-on-$FORE -- "; s; pn
+s 41 7 42; p " -- Should be: green-on-$FORE -- "; s; pn
+s 41 42 7; p " -- Should be: green-on-$FORE -- "; s; pn
+
+# One last, related test
+s 7; p "Invert text"; s 7 1; p " with some words bold"; s; pn;
+s 0; p "Normal text"; s 0 1; p " with some words bold"; s; pn;
+
+pn
+
+
+
+### Test effect of Bold(1) on color, with and without Invert(7).
+
+# The Bold flag does not affect the background color when Reverse is missing.
+# There should always be 8 colored boxes.
+p "  "
+for x in $BACK_COLORS; do
+    s $x; p "-"; s $x 1; p "-"
+done
+s; pn "    Bold should not affect background"
+
+# On some terminals, Bold affects color, and on some it doesn't.  If there
+# are only 8 colored boxes, then the next two tests will also show 8 colored
+# boxes.  If there are 16 boxes, then exactly one of the next two tests will
+# also have 16 boxes.
+p "  "
+for x in $FORE_COLORS; do
+    s $x; p "$FILL"; s $x 1; p "$FILL"
+done
+s; pn "    Does bold affect foreground color?"
+
+# On some terminals, Bold+Invert highlights the final Background color.
+p "  "
+for x in $FORE_COLORS; do
+    s $x 7; p "-"; s $x 7 1; p "-"
+done
+s; pn "    Test if Bold+Invert affects background color"
+
+# On some terminals, Bold+Invert highlights the final Foreground color.
+p "  "
+for x in $BACK_COLORS; do
+    s $x 7; p "$FILL"; s $x 7 1; p "$FILL"
+done
+s; pn "    Test if Bold+Invert affects foreground color"
+
+pn
+
+
+
+### Test for support of ForeHi and BackHi properties.
+
+# ForeHi
+p "  "
+for x in $FORE_COLORS; do
+    hi=$(( $x + 60 ))
+    s $x; p "$FILL"; s $hi; p "$FILL"
+done
+s; pn "    Test for support of ForeHi colors"
+p "  "
+for x in $FORE_COLORS; do
+    hi=$(( $x + 60 ))
+    s $x; p "$FILL"; s $x $hi; p "$FILL"
+done
+s; pn "    Test for support of ForeHi colors (w/compat)"
+
+# BackHi
+p "  "
+for x in $BACK_COLORS; do
+    hi=$(( $x + 60 ))
+    s $x; p "-"; s $hi; p "-"
+done
+s; pn "    Test for support of BackHi colors"
+p "  "
+for x in $BACK_COLORS; do
+    hi=$(( $x + 60 ))
+    s $x; p "-"; s $x $hi; p "-"
+done
+s; pn "    Test for support of BackHi colors (w/compat)"
+
+pn
+
+
+
+### Identify the default fore and back colors.
+
+pn "Match default fore and back colors against 16-color palette"
+pn "  ==fore==  ==back=="
+for fore in $FORE_COLORS; do
+    forehi=$(( $fore + 60 ))
+    back=$(( $fore + 10 ))
+    backhi=$(( $back + 60 ))
+    p "  "
+    s $fore;   p "$FILL"; s; p "$FILL"; s $fore;   p "$FILL"; s; p "  "
+    s $forehi; p "$FILL"; s; p "$FILL"; s $forehi; p "$FILL"; s; p "  "
+    s $back;   p "-"; s; p "-"; s $back;   p "-"; s; p "  "
+    s $backhi; p "-"; s; p "-"; s $backhi; p "-"; s; p "  "
+    pn "  $fore $forehi $back $backhi"
+done
+
+pn
+
+
+
+### Test coloring of rest-of-line.
+
+#
+# When a new line is scrolled in, every cell in the line receives the
+# current background color, which can be the default/transparent color.
+#
+
+p "Newline with red background: usually no red -->"; s 41; pn
+s; pn "This text is plain, but rest is red if scrolled -->"
+s; p " "; s 41; printf '\033[1K'; s; printf '\033[1C'; pn "<-- red Erase-in-Line to beginning"
+s; p "red Erase-in-Line to end -->"; s 41; printf '\033[0K'; s; pn
+pn
+
+
+
+### Moving the cursor around does not change colors of anything.
+
+pn "Test modifying uncolored lines with a colored SGR:"
+pn "aaaa"
+pn
+pn "____e"
+s 31 42; printf '\033[4C\033[3A'; pn "bb"
+pn "cccc"
+pn "dddd"
+s; pn
+
+pn "Test modifying colored+inverted+bold line with plain text:"
+s 42 31 7 1; printf 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\r';
+s; pn "This text is plain and followed by green-on-red -->"
+pn
+
+
+
+### Full-width character overwriting
+
+pn 'Overwrite part of a full-width char with a half-width char'
+p 'initial U+4000 ideographs -->'; s 31 42; p '䀀䀀'; s; pn
+p 'write X to index #1 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[24G'; p X; s; pn
+p 'write X to index #2 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[25G'; p X; s; pn
+p 'write X to index #3 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[26G'; p X; s; pn
+p 'write X to index #4 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[27G'; p X; s; pn
+pn
+
+pn 'Verify that Erase-in-Line can "fix" last char in line'
+p 'original                  -->'; s 31 42; p '䀀䀀'; s; pn
+p 'overwrite                 -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[30G'; p 'XXX'; s; pn
+p 'overwrite + Erase-in-Line -->'; s 31 42; p '䀀䀀'; s 35 44; printf '\033[30G'; p 'XXX'; s; printf '\033[0K'; pn
+p 'original                  -->'; s 31 42; p 'X䀀䀀'; s; pn
+p 'overwrite                 -->'; s 31 42; p 'X䀀䀀'; s 35 44; printf '\033[30G'; p 'ーー'; s; pn
+p 'overwrite + Erase-in-Line -->'; s 31 42; p 'X䀀䀀'; s 35 44; printf '\033[30G'; p 'ーー'; s; printf '\033[0K'; pn
+pn
diff --git a/node_modules/node-pty/deps/winpty/misc/font-notes.txt b/node_modules/node-pty/deps/winpty/misc/font-notes.txt
new file mode 100644 (file)
index 0000000..d4e36d8
--- /dev/null
@@ -0,0 +1,300 @@
+==================================================================
+Notes regarding fonts, code pages, and East Asian character widths
+==================================================================
+
+
+Registry settings
+=================
+
+ * There are console registry settings in `HKCU\Console`.  That key has many
+   default settings (e.g. the default font settings) and also per-app subkeys
+   for app-specific overrides.
+
+ * It is possible to override the code page with an app-specific setting.
+
+ * There are registry settings in
+   `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console`.  In particular,
+   the `TrueTypeFont` subkey has a list of suitable font names associated with
+   various CJK code pages, as well as default font names.
+
+ * There are two values in `HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage`
+   that specify the current code pages -- `OEMCP` and `ACP`.  Setting the
+   system locale via the Control Panel's "Region" or "Language" dialogs seems
+   to change these code page values.
+
+
+Console fonts
+=============
+
+ * The `FontFamily` field of `CONSOLE_FONT_INFOEX` has two parts:
+    - The high four bits can be exactly one of the `FF_xxxx` font families:
+          FF_DONTCARE(0x00)
+          FF_ROMAN(0x10)
+          FF_SWISS(0x20)
+          FF_MODERN(0x30)
+          FF_SCRIPT(0x40)
+          FF_DECORATIVE(0x50)
+    - The low four bits are a bitmask:
+          TMPF_FIXED_PITCH(1) -- actually means variable pitch
+          TMPF_VECTOR(2)
+          TMPF_TRUETYPE(4)
+          TMPF_DEVICE(8)
+
+ * Each console has its own independent console font table.  The current font
+   is identified with an index into this table.  The size of the table is
+   returned by the undocumented `GetNumberOfConsoleFonts` API.  It is apparently
+   possible to get the table size without this API, by instead calling
+   `GetConsoleFontSize` on each nonnegative index starting with 0 until the API
+   fails by returning (0, 0).
+
+ * The font table grows dynamically.  Each time the console is configured with
+   a previously-unused (FaceName, Size) combination, two entries are added to
+   the font table -- one with normal weight and one with bold weight.  Fonts
+   added this way are always TrueType fonts.
+
+ * Initially, the font table appears to contain only raster fonts.  For
+   example, on an English Windows 8 installation, here is the initial font
+   table:
+       font 0: 4x6
+       font 1: 6x8
+       font 2: 8x8
+       font 3: 16x8
+       font 4: 5x12
+       font 5: 7x12
+       font 6: 8x12 -- the current font
+       font 7: 16x12
+       font 8: 12x16
+       font 9: 10x18
+   `GetNumberOfConsoleFonts` returns 10, and this table matches the raster font
+   sizes according to the console properties dialog.
+
+ * With a Japanese or Chinese locale, the initial font table appears to contain
+   the sizes applicable to both the East Asian raster font, as well as the
+   sizes for the CP437/CP1252 raster font.
+
+ * The index passed to `SetCurrentConsoleFontEx` apparently has no effect.
+   The undocumented `SetConsoleFont` API, however, accepts *only* a font index,
+   and on Windows 8 English, it switches between all 10 fonts, even font index
+   #0.
+
+ * If the index passed to `SetConsoleFont` identifies a Raster Font
+   incompatible with the current code page, then another Raster Font is
+   activated.
+
+ * Passing "Terminal" to `SetCurrentConsoleFontEx` seems to have no effect.
+   Perhaps relatedly, `SetCurrentConsoleFontEx` does not fail if it is given a
+   bogus `FaceName`.  Some font is still chosen and activated.  Passing a face
+   name and height seems to work reliably, modulo the CP936 issue described
+   below.
+
+
+Console fonts and code pages
+============================
+
+ * On an English Windows installation, the default code page is 437, and it
+   cannot be set to 932 (Shift-JIS).  (The API call fails.)  Changing the
+   system locale to "Japanese (Japan)" using the Region/Language dialog
+   changes the default CP to 932 and permits changing the console CP between
+   437 and 932.
+
+ * A console has both an input code page and an output code page
+   (`{Get,Set}ConsoleCP` and `{Get,Set}ConsoleOutputCP`).  I'm not going to
+   distinguish between the two for this document; presumably only the output
+   CP matters.  The code page can change while the console is open, e.g.
+   by running `mode con: cp select={932,437,1252}` or by calling
+   `SetConsoleOutputCP`.
+
+ * The current code page restricts which TrueType fonts and which Raster Font
+   sizes are available in the console properties dialog.  This can change
+   while the console is open.
+
+ * Changing the code page almost(?) always changes the current console font.
+   So far, I don't know how the new font is chosen.
+
+ * With a CP of 932, the only TrueType font available in the console properties
+   dialog is "MS Gothic", displayed as "MS ゴシック".  It is still possible to
+   use the English-default TrueType console fonts, Lucida Console and Consolas,
+   via `SetCurrentConsoleFontEx`.
+
+ * When using a Raster Font and CP437 or CP1252, writing a UTF-16 codepoint not
+   representable in the code page instead writes a question mark ('?') to the
+   console.  This conversion does not apply with a TrueType font, nor with the
+   Raster Font for CP932 or CP936.
+
+
+ReadConsoleOutput and double-width characters
+==============================================
+
+ * With a Raster Font active, when `ReadConsoleOutputW` reads two cells of a
+   double-width character, it fills only a single `CHAR_INFO` structure.  The
+   unused trailing `CHAR_INFO` structures are zero-filled.  With a TrueType
+   font active, `ReadConsoleOutputW` instead fills two `CHAR_INFO` structures,
+   the first marked with `COMMON_LVB_LEADING_BYTE` and the second marked with
+   `COMMON_LVB_TRAILING_BYTE`.  The flag is a misnomer--there aren't two
+   *bytes*, but two cells, and they have equal `CHAR_INFO.Char.UnicodeChar`
+   values.
+
+ * `ReadConsoleOutputA`, on the other hand, reads two `CHAR_INFO` cells, and
+   if the UTF-16 value can be represented as two bytes in the ANSI/OEM CP, then
+   the two bytes are placed in the two `CHAR_INFO.Char.AsciiChar` values, and
+   the `COMMON_LVB_{LEADING,TRAILING}_BYTE` values are also used.  If the
+   codepoint isn't representable, I don't remember what happens -- I think the
+   `AsciiChar` values take on an invalid marker.
+
+ * Reading only one cell of a double-width character reads a space (U+0020)
+   instead.  Raster-vs-TrueType and wide-vs-ANSI do not matter.
+    - XXX: what about attributes?  Can a double-width character have mismatched
+      color attributes?
+    - XXX: what happens when writing to just one cell of a double-width
+      character?
+
+
+Default Windows fonts for East Asian languages
+==============================================
+CP932 / Japanese: "MS ゴシック" (MS Gothic)
+CP936 / Chinese Simplified: "新宋体" (SimSun)
+
+
+Unreliable character width (half-width vs full-width)
+=====================================================
+
+The half-width vs full-width status of a codepoint depends on at least these variables:
+ * OS version (Win10 legacy and new modes are different versions)
+ * system locale (English vs Japanese vs Chinese Simplified vs Chinese Traditional, etc)
+ * code page (437 vs 932 vs 936, etc)
+ * raster vs TrueType (Terminal vs MS Gothic vs SimSun, etc)
+ * font size
+ * rendered-vs-model (rendered width can be larger or smaller than model width)
+
+Example 1: U+2014 (EM DASH): East_Asian_Width: Ambiguous
+--------------------------------------------------------
+                                            rendered        modeled
+CP932: Win7/8 Raster Fonts                  half            half
+CP932: Win7/8 Gothic 14/15px                half            full
+CP932: Win7/8 Consolas 14/15px              half            full
+CP932: Win7/8 Lucida Console 14px           half            full
+CP932: Win7/8 Lucida Console 15px           half            half
+CP932: Win10New Raster Fonts                half            half
+CP932: Win10New Gothic 14/15px              half            half
+CP932: Win10New Consolas 14/15px            half            half
+CP932: Win10New Lucida Console 14/15px      half            half
+
+CP936: Win7/8 Raster Fonts                  full            full
+CP936: Win7/8 SimSun 14px                   full            full
+CP936: Win7/8 SimSun 15px                   full            half
+CP936: Win7/8 Consolas 14/15px              half            full
+CP936: Win10New Raster Fonts                full            full
+CP936: Win10New SimSum 14/15px              full            full
+CP936: Win10New Consolas 14/15px            half            half
+
+Example 2: U+3044 (HIRAGANA LETTER I): East_Asian_Width: Wide
+-------------------------------------------------------------
+                                            rendered        modeled
+CP932: Win7/8/10N Raster Fonts              full            full
+CP932: Win7/8/10N Gothic 14/15px            full            full
+CP932: Win7/8/10N Consolas 14/15px          half(*2)        full
+CP932: Win7/8/10N Lucida Console 14/15px    half(*3)        full
+
+CP936: Win7/8/10N Raster Fonts              full            full
+CP936: Win7/8/10N SimSun 14/15px            full            full
+CP936: Win7/8/10N Consolas 14/15px          full            full
+
+Example 3: U+30FC (KATAKANA-HIRAGANA PROLONGED SOUND MARK): East_Asian_Width: Wide
+----------------------------------------------------------------------------------
+                                            rendered        modeled
+CP932: Win7 Raster Fonts                    full            full
+CP932: Win7 Gothic 14/15px                  full            full
+CP932: Win7 Consolas 14/15px                half(*2)        full
+CP932: Win7 Lucida Console 14px             half(*3)        full
+CP932: Win7 Lucida Console 15px             half(*3)        half
+CP932: Win8 Raster Fonts                    full            full
+CP932: Win8 Gothic 14px                     full            half
+CP932: Win8 Gothic 15px                     full            full
+CP932: Win8 Consolas 14/15px                half(*2)        full
+CP932: Win8 Lucida Console 14px             half(*3)        full
+CP932: Win8 Lucida Console 15px             half(*3)        half
+CP932: Win10New Raster Fonts                full            full
+CP932: Win10New Gothic 14/15px              full            full
+CP932: Win10New Consolas 14/15px            half(*2)        half
+CP932: Win10New Lucida Console 14/15px      half(*2)        half
+
+CP936: Win7/8 Raster Fonts                  full            full
+CP936: Win7/8 SimSun 14px                   full            full
+CP936: Win7/8 SimSun 15px                   full            half
+CP936: Win7/8 Consolas 14px                 full            full
+CP936: Win7/8 Consolas 15px                 full            half
+CP936: Win10New Raster Fonts                full            full
+CP936: Win10New SimSum 14/15px              full            full
+CP936: Win10New Consolas 14/15px            full            full
+
+Example 4: U+4000 (CJK UNIFIED IDEOGRAPH-4000): East_Asian_Width: Wide
+----------------------------------------------------------------------
+                                            rendered        modeled
+CP932: Win7 Raster Fonts                    half(*1)        half
+CP932: Win7 Gothic 14/15px                  full            full
+CP932: Win7 Consolas 14/15px                half(*2)        full
+CP932: Win7 Lucida Console 14px             half(*3)        full
+CP932: Win7 Lucida Console 15px             half(*3)        half
+CP932: Win8 Raster Fonts                    half(*1)        half
+CP932: Win8 Gothic 14px                     full            half
+CP932: Win8 Gothic 15px                     full            full
+CP932: Win8 Consolas 14/15px                half(*2)        full
+CP932: Win8 Lucida Console 14px             half(*3)        full
+CP932: Win8 Lucida Console 15px             half(*3)        half
+CP932: Win10New Raster Fonts                half(*1)        half
+CP932: Win10New Gothic 14/15px              full            full
+CP932: Win10New Consolas 14/15px            half(*2)        half
+CP932: Win10New Lucida Console 14/15px      half(*2)        half
+
+CP936: Win7/8 Raster Fonts                  full            full
+CP936: Win7/8 SimSun 14px                   full            full
+CP936: Win7/8 SimSun 15px                   full            half
+CP936: Win7/8 Consolas 14px                 full            full
+CP936: Win7/8 Consolas 15px                 full            half
+CP936: Win10New Raster Fonts                full            full
+CP936: Win10New SimSum 14/15px              full            full
+CP936: Win10New Consolas 14/15px            full            full
+
+(*1) Rendered as a half-width filled white box
+(*2) Rendered as a half-width box with a question mark inside
+(*3) Rendered as a half-width empty box
+(!!) One of the only places in Win10New where rendered and modeled width disagree
+
+
+Windows quirk: unreliable font heights with CP936 / Chinese Simplified
+======================================================================
+
+When I set the font to 新宋体 17px, using either the properties dialog or
+`SetCurrentConsoleFontEx`, the height reported by `GetCurrentConsoleFontEx` is
+not 17, but is instead 19.  The same problem does not affect Raster Fonts,
+nor have I seen the problem in the English or Japanese locales.  I observed
+this with Windows 7 and Windows 10 new mode.
+
+If I set the font using the facename, width, *and* height, then the
+`SetCurrentConsoleFontEx` and `GetCurrentConsoleFontEx` values agree.  If I
+set the font using *only* the facename and height, then the two values
+disagree.
+
+
+Windows bug: GetCurrentConsoleFontEx is initially invalid
+=========================================================
+
+ - Assume there is no configured console font name in the registry.  In this
+   case, the console defaults to a raster font.
+ - Open a new console and call the `GetCurrentConsoleFontEx` API.
+ - The `FaceName` field of the returned `CONSOLE_FONT_INFOEX` data
+   structure is incorrect.  On Windows 7, 8, and 10, I observed that the
+   field was blank.  On Windows 8, occasionally, it instead contained:
+      U+AE72 U+75BE U+0001
+   The other fields of the structure all appeared correct:
+      nFont=6 dwFontSize=(8,12) FontFamily=0x30 FontWeight=400
+ - The `FaceName` field becomes initialized easily:
+    - Open the console properties dialog and click OK.  (Cancel is not
+      sufficient.)
+    - Call the undocumented `SetConsoleFont` with the current font table
+      index, which is 6 in the example above.
+ - It seems that the console uncritically accepts whatever string is
+   stored in the registry, including a blank string, and passes it on the
+   the `GetCurrentConsoleFontEx` caller.  It is possible to get the console
+   to *write* a blank setting into the registry -- simply open the console
+   (default or app-specific) properties and click OK.
diff --git a/node_modules/node-pty/deps/winpty/misc/winbug-15048.cc b/node_modules/node-pty/deps/winpty/misc/winbug-15048.cc
new file mode 100644 (file)
index 0000000..0e98d64
--- /dev/null
@@ -0,0 +1,201 @@
+/*
+
+Test program demonstrating a problem in Windows 15048's ReadConsoleOutput API.
+
+To compile:
+
+    cl /nologo /EHsc winbug-15048.cc shell32.lib
+
+Example of regressed input:
+
+Case 1:
+
+    > chcp 932
+    > winbug-15048 -face-gothic 3044
+
+    Correct output:
+
+        1**34      (nb: U+3044 replaced with '**' to avoid MSVC encoding warning)
+        5678
+
+        ReadConsoleOutputW (both rows, 3 cols)
+        row 0: U+0031(0007) U+3044(0107) U+3044(0207) U+0033(0007)
+        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007)
+
+        ReadConsoleOutputW (both rows, 4 cols)
+        row 0: U+0031(0007) U+3044(0107) U+3044(0207) U+0033(0007) U+0034(0007)
+        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007)
+
+        ReadConsoleOutputW (second row)
+        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007)
+
+        ...
+
+    Win10 15048 bad output:
+
+        1**34
+        5678
+
+        ReadConsoleOutputW (both rows, 3 cols)
+        row 0: U+0031(0007) U+3044(0007) U+0033(0007) U+0035(0007)
+        row 1: U+0036(0007) U+0037(0007) U+0038(0007) U+0000(0000)
+
+        ReadConsoleOutputW (both rows, 4 cols)
+        row 0: U+0031(0007) U+3044(0007) U+0033(0007) U+0034(0007) U+0035(0007)
+        row 1: U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007) U+0000(0000)
+
+        ReadConsoleOutputW (second row)
+        row 1: U+0035(0007) U+0036(0007) U+0037(0007) U+0038(0007) U+0020(0007)
+
+        ...
+
+    The U+3044 character (HIRAGANA LETTER I) occupies two columns, but it only
+    fills one record in the ReadConsoleOutput output buffer, which has the
+    effect of shifting the first cell of the second row into the last cell of
+    the first row.  Ordinarily, the first and second cells would also have the
+    COMMON_LVB_LEADING_BYTE and COMMON_LVB_TRAILING_BYTE attributes set, which
+    allows winpty to detect the double-column character.
+
+Case 2:
+
+    > chcp 437
+    > winbug-15048 -face "Lucida Console" -h 4 221A
+
+    The same issue happens with U+221A (SQUARE ROOT), but only in certain
+    fonts.  The console seems to think this character occupies two columns
+    if the font is sufficiently small.  The Windows console properties dialog
+    doesn't allow fonts below 5 pt, but winpty tries to use 2pt and 4pt Lucida
+    Console to allow very large console windows.
+
+Case 3:
+
+    > chcp 437
+    > winbug-15048 -face "Lucida Console" -h 12 FF12
+
+    The console selection system thinks U+FF12 (FULLWIDTH DIGIT TWO) occupies
+    two columns, which happens to be correct, but it's displayed as a single
+    column unrecognized character.  It otherwise behaves the same as the other
+    cases.
+
+*/
+
+#include <windows.h>
+#include <assert.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <wchar.h>
+
+#include <string>
+
+#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0]))
+
+// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
+const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // Japanese
+const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // Simplified Chinese
+const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // Traditional Chinese
+const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // Korean
+
+static void set_font(const wchar_t *name, int size) {
+    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+    CONSOLE_FONT_INFOEX fontex {};
+    fontex.cbSize = sizeof(fontex);
+    fontex.dwFontSize.Y = size;
+    fontex.FontWeight = 400;
+    fontex.FontFamily = 0x36;
+    wcsncpy(fontex.FaceName, name, COUNT_OF(fontex.FaceName));
+    assert(SetCurrentConsoleFontEx(conout, FALSE, &fontex));
+}
+
+static void usage(const wchar_t *prog) {
+    printf("Usage: %ls [options]\n", prog);
+    printf("  -h HEIGHT\n");
+    printf("  -face FACENAME\n");
+    printf("  -face-{gothic|simsun|minglight|gulimche) [JP,CN-sim,CN-tra,KR]\n");
+    printf("  hhhh -- print U+hhhh\n");
+    exit(1);
+}
+
+static void dump_region(SMALL_RECT region, const char *name) {
+    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    CHAR_INFO buf[1000];
+    memset(buf, 0xcc, sizeof(buf));
+
+    const int w = region.Right - region.Left + 1;
+    const int h = region.Bottom - region.Top + 1;
+
+    assert(ReadConsoleOutputW(
+        conout, buf, { (short)w, (short)h }, { 0, 0 },
+        &region));
+
+    printf("\n");
+    printf("ReadConsoleOutputW (%s)\n", name);
+    for (int y = 0; y < h; ++y) {
+        printf("row %d: ", region.Top + y);
+        for (int i = 0; i < region.Left * 13; ++i) {
+            printf(" ");
+        }
+        for (int x = 0; x < w; ++x) {
+            const int i = y * w + x;
+            printf("U+%04x(%04x) ", buf[i].Char.UnicodeChar, buf[i].Attributes);
+        }
+        printf("\n");
+    }
+}
+
+int main() {
+    wchar_t *cmdline = GetCommandLineW();
+    int argc = 0;
+    wchar_t **argv = CommandLineToArgvW(cmdline, &argc);
+    const wchar_t *font_name = L"Lucida Console";
+    int font_height = 8;
+    int test_ch = 0xff12; // U+FF12 FULLWIDTH DIGIT TWO
+
+    for (int i = 1; i < argc; ++i) {
+        const std::wstring arg = argv[i];
+        const std::wstring next = i + 1 < argc ? argv[i + 1] : L"";
+        if (arg == L"-face" && i + 1 < argc) {
+            font_name = argv[i + 1];
+            i++;
+        } else if (arg == L"-face-gothic") {
+            font_name = kMSGothic;
+        } else if (arg == L"-face-simsun") {
+            font_name = kNSimSun;
+        } else if (arg == L"-face-minglight") {
+            font_name = kMingLight;
+        } else if (arg == L"-face-gulimche") {
+            font_name = kGulimChe;
+        } else if (arg == L"-h" && i + 1 < argc) {
+            font_height = _wtoi(next.c_str());
+            i++;
+        } else if (arg.c_str()[0] != '-') {
+            test_ch = wcstol(arg.c_str(), NULL, 16);
+        } else {
+            printf("Unrecognized argument: %ls\n", arg.c_str());
+            usage(argv[0]);
+        }
+    }
+
+    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
+
+    set_font(font_name, font_height);
+
+    system("cls");
+    DWORD actual = 0;
+    wchar_t output[] = L"1234\n5678\n";
+    output[1] = test_ch;
+    WriteConsoleW(conout, output, 10, &actual, nullptr);
+
+    dump_region({ 0, 0, 3, 1 }, "both rows, 3 cols");
+    dump_region({ 0, 0, 4, 1 }, "both rows, 4 cols");
+    dump_region({ 0, 1, 4, 1 }, "second row");
+    dump_region({ 0, 0, 4, 0 }, "first row");
+    dump_region({ 1, 0, 4, 0 }, "first row, skip 1");
+    dump_region({ 2, 0, 4, 0 }, "first row, skip 2");
+    dump_region({ 3, 0, 4, 0 }, "first row, skip 3");
+
+    set_font(font_name, 14);
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/ship/build-pty4j-libpty.bat b/node_modules/node-pty/deps/winpty/ship/build-pty4j-libpty.bat
new file mode 100644 (file)
index 0000000..b6bca7b
--- /dev/null
@@ -0,0 +1,36 @@
+@echo off
+
+setlocal
+cd %~dp0..
+set Path=C:\Python27;C:\Program Files\Git\cmd;%Path%
+
+call "%VS140COMNTOOLS%\VsDevCmd.bat" || goto :fail
+
+rmdir /s/q build-libpty 2>NUL
+mkdir build-libpty\win
+mkdir build-libpty\win\x86
+mkdir build-libpty\win\x86_64
+mkdir build-libpty\win\xp
+
+rmdir /s/q src\Release  2>NUL
+rmdir /s/q src\.vs      2>NUL
+del src\*.vcxproj src\*.vcxproj.filters src\*.sln src\*.sdf 2>NUL
+
+call vcbuild.bat --msvc-platform Win32 --gyp-msvs-version 2015 --toolset v140_xp || goto :fail
+copy src\Release\Win32\winpty.dll           build-libpty\win\xp || goto :fail
+copy src\Release\Win32\winpty-agent.exe     build-libpty\win\xp || goto :fail
+
+call vcbuild.bat --msvc-platform Win32 --gyp-msvs-version 2015 || goto :fail
+copy src\Release\Win32\winpty.dll           build-libpty\win\x86 || goto :fail
+copy src\Release\Win32\winpty-agent.exe     build-libpty\win\x86 || goto :fail
+
+call vcbuild.bat --msvc-platform x64 --gyp-msvs-version 2015 || goto :fail
+copy src\Release\x64\winpty.dll             build-libpty\win\x86_64 || goto :fail
+copy src\Release\x64\winpty-agent.exe       build-libpty\win\x86_64 || goto :fail
+
+echo success
+goto :EOF
+
+:fail
+echo error: build failed
+exit /b 1
diff --git a/node_modules/node-pty/deps/winpty/ship/common_ship.py b/node_modules/node-pty/deps/winpty/ship/common_ship.py
new file mode 100644 (file)
index 0000000..b46cd5b
--- /dev/null
@@ -0,0 +1,53 @@
+import os
+import sys
+
+if os.name != "nt":
+    sys.exit("Error: ship scripts require native Python 2.7. (wrong os.name)")
+if sys.version_info[0:2] != (2,7):
+    sys.exit("Error: ship scripts require native Python 2.7. (wrong version)")
+
+import glob
+import shutil
+import subprocess
+from distutils.spawn import find_executable
+
+topDir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
+
+with open(topDir + "/VERSION.txt", "rt") as f:
+    winptyVersion = f.read().strip()
+
+def rmrf(patterns):
+    for pattern in patterns:
+        for path in glob.glob(pattern):
+            if os.path.isdir(path) and not os.path.islink(path):
+                print "+ rm -r " + path
+                sys.stdout.flush()
+                shutil.rmtree(path)
+            elif os.path.isfile(path):
+                print "+ rm " + path
+                sys.stdout.flush()
+                os.remove(path)
+
+def mkdir(path):
+    if not os.path.isdir(path):
+        os.makedirs(path)
+
+def requireExe(name, guesses):
+    if find_executable(name) is None:
+        for guess in guesses:
+            if os.path.exists(guess):
+                newDir = os.path.dirname(guess)
+                print "Adding " + newDir + " to Path to provide " + name
+                os.environ["Path"] = newDir + ";" + os.environ["Path"]
+    ret = find_executable(name)
+    if ret is None:
+        sys.exit("Error: required EXE is missing from Path: " + name)
+    return ret
+
+requireExe("git.exe", [
+    "C:\\Program Files\\Git\\cmd\\git.exe",
+    "C:\\Program Files (x86)\\Git\\cmd\\git.exe"
+])
+
+commitHash = subprocess.check_output(["git.exe", "rev-parse", "HEAD"]).decode().strip()
+defaultPathEnviron = "C:\\Windows\\System32;C:\\Windows"
diff --git a/node_modules/node-pty/deps/winpty/ship/make_msvc_package.py b/node_modules/node-pty/deps/winpty/ship/make_msvc_package.py
new file mode 100644 (file)
index 0000000..220f02b
--- /dev/null
@@ -0,0 +1,165 @@
+#!python
+
+# Copyright (c) 2016 Ryan Prichard
+#
+# 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.
+
+#
+# Run with native CPython 2.7.
+#
+# This script looks for MSVC using a version-specific environment variable,
+# such as VS140COMNTOOLS for MSVC 2015.
+#
+
+import common_ship
+
+import argparse
+import os
+import shutil
+import subprocess
+import sys
+
+os.chdir(common_ship.topDir)
+ZIP_TOOL = common_ship.requireExe("7z.exe", [
+    "C:\\Program Files\\7-Zip\\7z.exe",
+    "C:\\Program Files (x86)\\7-Zip\\7z.exe",
+])
+
+MSVC_VERSION_TABLE = {
+    "2015" : {
+        "package_name" : "msvc2015",
+        "gyp_version" : "2015",
+        "common_tools_env" : "VS140COMNTOOLS",
+        "xp_toolset" : "v140_xp",
+    },
+    "2013" : {
+        "package_name" : "msvc2013",
+        "gyp_version" : "2013",
+        "common_tools_env" : "VS120COMNTOOLS",
+        "xp_toolset" : "v120_xp",
+    },
+}
+
+ARCH_TABLE = {
+    "x64" : {
+        "msvc_platform" : "x64",
+    },
+    "ia32" : {
+        "msvc_platform" : "Win32",
+    },
+}
+
+def readArguments():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--msvc-version", default="2015")
+    ret = parser.parse_args()
+    if ret.msvc_version not in MSVC_VERSION_TABLE:
+        sys.exit("Error: unrecognized version: " + ret.msvc_version + ". " +
+            "Versions: " + " ".join(sorted(MSVC_VERSION_TABLE.keys())))
+    return ret
+
+ARGS = readArguments()
+
+def checkoutGyp():
+    if os.path.isdir("build-gyp"):
+        return
+    subprocess.check_call([
+        "git.exe",
+        "clone",
+        "https://chromium.googlesource.com/external/gyp",
+        "build-gyp"
+    ])
+
+def cleanMsvc():
+    common_ship.rmrf("""
+        src/Release src/.vs src/gen
+        src/*.vcxproj src/*.vcxproj.filters src/*.sln src/*.sdf
+    """.split())
+
+def build(arch, packageDir, xp=False):
+    archInfo = ARCH_TABLE[arch]
+    versionInfo = MSVC_VERSION_TABLE[ARGS.msvc_version]
+
+    devCmdPath = os.path.join(os.environ[versionInfo["common_tools_env"]], "VsDevCmd.bat")
+    if not os.path.isfile(devCmdPath):
+        sys.exit("Error: MSVC environment script missing: " + devCmdPath)
+
+    newEnv = os.environ.copy()
+    newEnv["PATH"] = os.path.dirname(sys.executable) + ";" + common_ship.defaultPathEnviron
+    commandLine = (
+        '"' + devCmdPath + '" && '
+        " vcbuild.bat" +
+        " --gyp-msvs-version " + versionInfo["gyp_version"] +
+        " --msvc-platform " + archInfo["msvc_platform"] +
+        " --commit-hash " + common_ship.commitHash
+    )
+
+    subprocess.check_call(commandLine, shell=True, env=newEnv)
+
+    archPackageDir = os.path.join(packageDir, arch)
+    if xp:
+        archPackageDir += "_xp"
+
+    common_ship.mkdir(archPackageDir + "/bin")
+    common_ship.mkdir(archPackageDir + "/lib")
+
+    binSrc = os.path.join(common_ship.topDir, "src/Release", archInfo["msvc_platform"])
+
+    shutil.copy(binSrc + "/winpty.dll",                 archPackageDir + "/bin")
+    shutil.copy(binSrc + "/winpty-agent.exe",           archPackageDir + "/bin")
+    shutil.copy(binSrc + "/winpty-debugserver.exe",     archPackageDir + "/bin")
+    shutil.copy(binSrc + "/winpty.lib",                 archPackageDir + "/lib")
+
+def buildPackage():
+    versionInfo = MSVC_VERSION_TABLE[ARGS.msvc_version]
+
+    packageName = "winpty-%s-%s" % (
+        common_ship.winptyVersion,
+        versionInfo["package_name"],
+    )
+
+    packageRoot = os.path.join(common_ship.topDir, "ship/packages")
+    packageDir = os.path.join(packageRoot, packageName)
+    packageFile = packageDir + ".zip"
+
+    common_ship.rmrf([packageDir])
+    common_ship.rmrf([packageFile])
+    common_ship.mkdir(packageDir)
+
+    checkoutGyp()
+    cleanMsvc()
+    build("ia32", packageDir, True)
+    build("x64", packageDir, True)
+    cleanMsvc()
+    build("ia32", packageDir)
+    build("x64", packageDir)
+
+    topDir = common_ship.topDir
+
+    common_ship.mkdir(packageDir + "/include")
+    shutil.copy(topDir + "/src/include/winpty.h",               packageDir + "/include")
+    shutil.copy(topDir + "/src/include/winpty_constants.h",     packageDir + "/include")
+    shutil.copy(topDir + "/LICENSE",                            packageDir)
+    shutil.copy(topDir + "/README.md",                          packageDir)
+    shutil.copy(topDir + "/RELEASES.md",                        packageDir)
+
+    subprocess.check_call([ZIP_TOOL, "a", packageFile, "."], cwd=packageDir)
+
+if __name__ == "__main__":
+    buildPackage()
diff --git a/node_modules/node-pty/deps/winpty/ship/ship.py b/node_modules/node-pty/deps/winpty/ship/ship.py
new file mode 100644 (file)
index 0000000..12874ba
--- /dev/null
@@ -0,0 +1,108 @@
+#!python
+
+# Copyright (c) 2015 Ryan Prichard
+#
+# 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.
+
+#
+# Run with native CPython 2.7 on a 64-bit computer.
+#
+# Each of the targets in BUILD_TARGETS must be installed to the default
+# location.  Each target must have the appropriate MinGW and non-MinGW
+# compilers installed, as well as make and tar.
+#
+
+import common_ship
+
+import multiprocessing
+import os
+import shutil
+import subprocess
+import sys
+
+os.chdir(common_ship.topDir)
+
+def dllVersion(path):
+    version = subprocess.check_output(
+        ["powershell.exe",
+        "[System.Diagnostics.FileVersionInfo]::GetVersionInfo(\"" + path + "\").FileVersion"])
+    return version.strip()
+
+# Determine other build parameters.
+print "Determining Cygwin/MSYS2 DLL versions..."
+sys.stdout.flush()
+BUILD_TARGETS = [
+    # {
+    #     "name": "msys",
+    #     "path": "C:\\MinGW\\bin;C:\\MinGW\\msys\\1.0\\bin",
+    #     # The parallel make.exe in the original MSYS/MinGW project hangs.
+    #     "make_binary": "mingw32-make.exe",
+    # },
+    {
+        "name": "msys2-" + dllVersion("C:\\msys32\\usr\\bin\\msys-2.0.dll") + "-ia32",
+        "path": "C:\\msys32\\mingw32\\bin;C:\\msys32\\usr\\bin",
+    },
+    {
+        "name": "msys2-" + dllVersion("C:\\msys64\\usr\\bin\\msys-2.0.dll") + "-x64",
+        "path": "C:\\msys64\\mingw64\\bin;C:\\msys64\\usr\\bin",
+    },
+    {
+        "name": "cygwin-" + dllVersion("C:\\cygwin\\bin\\cygwin1.dll") + "-ia32",
+        "path": "C:\\cygwin\\bin",
+    },
+    {
+        "name": "cygwin-" + dllVersion("C:\\cygwin64\\bin\\cygwin1.dll") + "-x64",
+        "path": "C:\\cygwin64\\bin",
+    },
+]
+
+def buildTarget(target):
+    packageName = "winpty-" + common_ship.winptyVersion + "-" + target["name"]
+    if os.path.exists("ship\\packages\\" + packageName):
+        shutil.rmtree("ship\\packages\\" + packageName)
+    oldPath = os.environ["PATH"]
+    os.environ["PATH"] = target["path"] + ";" + common_ship.defaultPathEnviron
+    subprocess.check_call(["sh.exe", "configure"])
+    makeBinary = target.get("make_binary", "make.exe")
+    subprocess.check_call([makeBinary, "clean"])
+    makeBaseCmd = [
+        makeBinary,
+        "USE_PCH=0",
+        "COMMIT_HASH=" + common_ship.commitHash,
+        "PREFIX=ship/packages/" + packageName
+    ]
+    subprocess.check_call(makeBaseCmd + ["all", "tests", "-j%d" % multiprocessing.cpu_count()])
+    subprocess.check_call(["build\\trivial_test.exe"])
+    subprocess.check_call(makeBaseCmd + ["install"])
+    subprocess.check_call(["tar.exe", "cvfz",
+        packageName + ".tar.gz",
+        packageName], cwd=os.path.join(os.getcwd(), "ship", "packages"))
+    os.environ["PATH"] = oldPath
+
+def main():
+    oldPath = os.environ["PATH"]
+    for t in BUILD_TARGETS:
+        os.environ["PATH"] = t["path"] + ";" + common_ship.defaultPathEnviron
+        subprocess.check_output(["tar.exe", "--help"])
+        subprocess.check_output(["make.exe", "--help"])
+    for t in BUILD_TARGETS:
+        buildTarget(t)
+
+if __name__ == "__main__":
+    main()
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Agent.cc b/node_modules/node-pty/deps/winpty/src/agent/Agent.cc
new file mode 100644 (file)
index 0000000..a77b644
--- /dev/null
@@ -0,0 +1,605 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "Agent.h"
+
+#include <windows.h>
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "../include/winpty_constants.h"
+
+#include "../shared/AgentMsg.h"
+#include "../shared/Buffer.h"
+#include "../shared/DebugClient.h"
+#include "../shared/GenRandom.h"
+#include "../shared/StringBuilder.h"
+#include "../shared/StringUtil.h"
+#include "../shared/WindowsVersion.h"
+#include "../shared/WinptyAssert.h"
+
+#include "ConsoleFont.h"
+#include "ConsoleInput.h"
+#include "NamedPipe.h"
+#include "Scraper.h"
+#include "Terminal.h"
+#include "Win32ConsoleBuffer.h"
+
+namespace {
+
+static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
+{
+    if (dwCtrlType == CTRL_C_EVENT) {
+        // Do nothing and claim to have handled the event.
+        return TRUE;
+    }
+    return FALSE;
+}
+
+// We can detect the new Windows 10 console by observing the effect of the
+// Mark command.  In older consoles, Mark temporarily moves the cursor to the
+// top-left of the console window.  In the new console, the cursor isn't
+// initially moved.
+//
+// We might like to use Mark to freeze the console, but we can't, because when
+// the Mark command ends, the console moves the cursor back to its starting
+// point, even if the console application has moved it in the meantime.
+static void detectNewWindows10Console(
+        Win32Console &console, Win32ConsoleBuffer &buffer)
+{
+    if (!isAtLeastWindows8()) {
+        return;
+    }
+
+    ConsoleScreenBufferInfo info = buffer.bufferInfo();
+
+    // Make sure the window isn't 1x1.  AFAIK, this should never happen
+    // accidentally.  It is difficult to make it happen deliberately.
+    if (info.srWindow.Left == info.srWindow.Right &&
+            info.srWindow.Top == info.srWindow.Bottom) {
+        trace("detectNewWindows10Console: Initial console window was 1x1 -- "
+              "expanding for test");
+        setSmallFont(buffer.conout(), 400, false);
+        buffer.moveWindow(SmallRect(0, 0, 1, 1));
+        buffer.resizeBuffer(Coord(400, 1));
+        buffer.moveWindow(SmallRect(0, 0, 2, 1));
+        // This use of GetLargestConsoleWindowSize ought to be unnecessary
+        // given the behavior I've seen from moveWindow(0, 0, 1, 1), but
+        // I'd like to be especially sure, considering that this code will
+        // rarely be tested.
+        const auto largest = GetLargestConsoleWindowSize(buffer.conout());
+        buffer.moveWindow(
+            SmallRect(0, 0, std::min(largest.X, buffer.bufferSize().X), 1));
+        info = buffer.bufferInfo();
+        ASSERT(info.srWindow.Right > info.srWindow.Left &&
+            "Could not expand console window from 1x1");
+    }
+
+    // Test whether MARK moves the cursor.
+    const Coord initialPosition(info.srWindow.Right, info.srWindow.Bottom);
+    buffer.setCursorPosition(initialPosition);
+    ASSERT(!console.frozen());
+    console.setFreezeUsesMark(true);
+    console.setFrozen(true);
+    const bool isNewW10 = (buffer.cursorPosition() == initialPosition);
+    console.setFrozen(false);
+    buffer.setCursorPosition(Coord(0, 0));
+
+    trace("Attempting to detect new Windows 10 console using MARK: %s",
+        isNewW10 ? "detected" : "not detected");
+    console.setFreezeUsesMark(false);
+    console.setNewW10(isNewW10);
+}
+
+static inline WriteBuffer newPacket() {
+    WriteBuffer packet;
+    packet.putRawValue<uint64_t>(0); // Reserve space for size.
+    return packet;
+}
+
+static HANDLE duplicateHandle(HANDLE h) {
+    HANDLE ret = nullptr;
+    if (!DuplicateHandle(
+            GetCurrentProcess(), h,
+            GetCurrentProcess(), &ret,
+            0, FALSE, DUPLICATE_SAME_ACCESS)) {
+        ASSERT(false && "DuplicateHandle failed!");
+    }
+    return ret;
+}
+
+// It's safe to truncate a handle from 64-bits to 32-bits, or to sign-extend it
+// back to 64-bits.  See the MSDN article, "Interprocess Communication Between
+// 32-bit and 64-bit Applications".
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203.aspx
+static int64_t int64FromHandle(HANDLE h) {
+    return static_cast<int64_t>(reinterpret_cast<intptr_t>(h));
+}
+
+} // anonymous namespace
+
+Agent::Agent(LPCWSTR controlPipeName,
+             uint64_t agentFlags,
+             int mouseMode,
+             int initialCols,
+             int initialRows) :
+    m_useConerr((agentFlags & WINPTY_FLAG_CONERR) != 0),
+    m_plainMode((agentFlags & WINPTY_FLAG_PLAIN_OUTPUT) != 0),
+    m_mouseMode(mouseMode)
+{
+    trace("Agent::Agent entered");
+
+    ASSERT(initialCols >= 1 && initialRows >= 1);
+    initialCols = std::min(initialCols, MAX_CONSOLE_WIDTH);
+    initialRows = std::min(initialRows, MAX_CONSOLE_HEIGHT);
+
+    const bool outputColor =
+        !m_plainMode || (agentFlags & WINPTY_FLAG_COLOR_ESCAPES);
+    const Coord initialSize(initialCols, initialRows);
+
+    auto primaryBuffer = openPrimaryBuffer();
+    if (m_useConerr) {
+        m_errorBuffer = Win32ConsoleBuffer::createErrorBuffer();
+    }
+
+    detectNewWindows10Console(m_console, *primaryBuffer);
+
+    m_controlPipe = &connectToControlPipe(controlPipeName);
+    m_coninPipe = &createDataServerPipe(false, L"conin");
+    m_conoutPipe = &createDataServerPipe(true, L"conout");
+    if (m_useConerr) {
+        m_conerrPipe = &createDataServerPipe(true, L"conerr");
+    }
+
+    // Send an initial response packet to winpty.dll containing pipe names.
+    {
+        auto setupPacket = newPacket();
+        setupPacket.putWString(m_coninPipe->name());
+        setupPacket.putWString(m_conoutPipe->name());
+        if (m_useConerr) {
+            setupPacket.putWString(m_conerrPipe->name());
+        }
+        writePacket(setupPacket);
+    }
+
+    std::unique_ptr<Terminal> primaryTerminal;
+    primaryTerminal.reset(new Terminal(*m_conoutPipe,
+                                       m_plainMode,
+                                       outputColor));
+    m_primaryScraper.reset(new Scraper(m_console,
+                                       *primaryBuffer,
+                                       std::move(primaryTerminal),
+                                       initialSize));
+    if (m_useConerr) {
+        std::unique_ptr<Terminal> errorTerminal;
+        errorTerminal.reset(new Terminal(*m_conerrPipe,
+                                         m_plainMode,
+                                         outputColor));
+        m_errorScraper.reset(new Scraper(m_console,
+                                         *m_errorBuffer,
+                                         std::move(errorTerminal),
+                                         initialSize));
+    }
+
+    m_console.setTitle(m_currentTitle);
+
+    const HANDLE conin = GetStdHandle(STD_INPUT_HANDLE);
+    m_consoleInput.reset(
+        new ConsoleInput(conin, m_mouseMode, *this, m_console));
+
+    // Setup Ctrl-C handling.  First restore default handling of Ctrl-C.  This
+    // attribute is inherited by child processes.  Then register a custom
+    // Ctrl-C handler that does nothing.  The handler will be called when the
+    // agent calls GenerateConsoleCtrlEvent.
+    SetConsoleCtrlHandler(NULL, FALSE);
+    SetConsoleCtrlHandler(consoleCtrlHandler, TRUE);
+
+    setPollInterval(25);
+}
+
+Agent::~Agent()
+{
+    trace("Agent::~Agent entered");
+    agentShutdown();
+    if (m_childProcess != NULL) {
+        CloseHandle(m_childProcess);
+    }
+}
+
+// Write a "Device Status Report" command to the terminal.  The terminal will
+// reply with a row+col escape sequence.  Presumably, the DSR reply will not
+// split a keypress escape sequence, so it should be safe to assume that the
+// bytes before it are complete keypresses.
+void Agent::sendDsr()
+{
+    if (!m_plainMode && !m_conoutPipe->isClosed()) {
+        m_conoutPipe->write("\x1B[6n");
+    }
+}
+
+NamedPipe &Agent::connectToControlPipe(LPCWSTR pipeName)
+{
+    NamedPipe &pipe = createNamedPipe();
+    pipe.connectToServer(pipeName, NamedPipe::OpenMode::Duplex);
+    pipe.setReadBufferSize(64 * 1024);
+    return pipe;
+}
+
+// Returns a new server named pipe.  It has not yet been connected.
+NamedPipe &Agent::createDataServerPipe(bool write, const wchar_t *kind)
+{
+    const auto name =
+        (WStringBuilder(128)
+            << L"\\\\.\\pipe\\winpty-"
+            << kind << L'-'
+            << GenRandom().uniqueName()).str_moved();
+    NamedPipe &pipe = createNamedPipe();
+    pipe.openServerPipe(
+        name.c_str(),
+        write ? NamedPipe::OpenMode::Writing
+              : NamedPipe::OpenMode::Reading,
+        write ? 8192 : 0,
+        write ? 0 : 256);
+    if (!write) {
+        pipe.setReadBufferSize(64 * 1024);
+    }
+    return pipe;
+}
+
+void Agent::onPipeIo(NamedPipe &namedPipe)
+{
+    if (&namedPipe == m_conoutPipe || &namedPipe == m_conerrPipe) {
+        autoClosePipesForShutdown();
+    } else if (&namedPipe == m_coninPipe) {
+        pollConinPipe();
+    } else if (&namedPipe == m_controlPipe) {
+        pollControlPipe();
+    }
+}
+
+void Agent::pollControlPipe()
+{
+    if (m_controlPipe->isClosed()) {
+        trace("Agent exiting (control pipe is closed)");
+        shutdown();
+        return;
+    }
+
+    while (true) {
+        uint64_t packetSize = 0;
+        const auto amt1 =
+            m_controlPipe->peek(&packetSize, sizeof(packetSize));
+        if (amt1 < sizeof(packetSize)) {
+            break;
+        }
+        ASSERT(packetSize >= sizeof(packetSize) && packetSize <= SIZE_MAX);
+        if (m_controlPipe->bytesAvailable() < packetSize) {
+            if (m_controlPipe->readBufferSize() < packetSize) {
+                m_controlPipe->setReadBufferSize(packetSize);
+            }
+            break;
+        }
+        std::vector<char> packetData;
+        packetData.resize(packetSize);
+        const auto amt2 = m_controlPipe->read(packetData.data(), packetSize);
+        ASSERT(amt2 == packetSize);
+        try {
+            ReadBuffer buffer(std::move(packetData));
+            buffer.getRawValue<uint64_t>(); // Discard the size.
+            handlePacket(buffer);
+        } catch (const ReadBuffer::DecodeError&) {
+            ASSERT(false && "Decode error");
+        }
+    }
+}
+
+void Agent::handlePacket(ReadBuffer &packet)
+{
+    const int type = packet.getInt32();
+    switch (type) {
+    case AgentMsg::StartProcess:
+        handleStartProcessPacket(packet);
+        break;
+    case AgentMsg::SetSize:
+        // TODO: I think it might make sense to collapse consecutive SetSize
+        // messages.  i.e. The terminal process can probably generate SetSize
+        // messages faster than they can be processed, and some GUIs might
+        // generate a flood of them, so if we can read multiple SetSize packets
+        // at once, we can ignore the early ones.
+        handleSetSizePacket(packet);
+        break;
+    case AgentMsg::GetConsoleProcessList:
+        handleGetConsoleProcessListPacket(packet);
+        break;
+    default:
+        trace("Unrecognized message, id:%d", type);
+    }
+}
+
+void Agent::writePacket(WriteBuffer &packet)
+{
+    const auto &bytes = packet.buf();
+    packet.replaceRawValue<uint64_t>(0, bytes.size());
+    m_controlPipe->write(bytes.data(), bytes.size());
+}
+
+void Agent::handleStartProcessPacket(ReadBuffer &packet)
+{
+    ASSERT(m_childProcess == nullptr);
+    ASSERT(!m_closingOutputPipes);
+
+    const uint64_t spawnFlags = packet.getInt64();
+    const bool wantProcessHandle = packet.getInt32() != 0;
+    const bool wantThreadHandle = packet.getInt32() != 0;
+    const auto program = packet.getWString();
+    const auto cmdline = packet.getWString();
+    const auto cwd = packet.getWString();
+    const auto env = packet.getWString();
+    const auto desktop = packet.getWString();
+    packet.assertEof();
+
+    auto cmdlineV = vectorWithNulFromString(cmdline);
+    auto desktopV = vectorWithNulFromString(desktop);
+    auto envV = vectorFromString(env);
+
+    LPCWSTR programArg = program.empty() ? nullptr : program.c_str();
+    LPWSTR cmdlineArg = cmdline.empty() ? nullptr : cmdlineV.data();
+    LPCWSTR cwdArg = cwd.empty() ? nullptr : cwd.c_str();
+    LPWSTR envArg = env.empty() ? nullptr : envV.data();
+
+    STARTUPINFOW sui = {};
+    PROCESS_INFORMATION pi = {};
+    sui.cb = sizeof(sui);
+    sui.lpDesktop = desktop.empty() ? nullptr : desktopV.data();
+    BOOL inheritHandles = FALSE;
+    if (m_useConerr) {
+        inheritHandles = TRUE;
+        sui.dwFlags |= STARTF_USESTDHANDLES;
+        sui.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
+        sui.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
+        sui.hStdError = m_errorBuffer->conout();
+    }
+
+    const BOOL success =
+        CreateProcessW(programArg, cmdlineArg, nullptr, nullptr,
+                       /*bInheritHandles=*/inheritHandles,
+                       /*dwCreationFlags=*/CREATE_UNICODE_ENVIRONMENT,
+                       envArg, cwdArg, &sui, &pi);
+    const int lastError = success ? 0 : GetLastError();
+
+    trace("CreateProcess: %s %u",
+          (success ? "success" : "fail"),
+          static_cast<unsigned int>(pi.dwProcessId));
+
+    auto reply = newPacket();
+    if (success) {
+        int64_t replyProcess = 0;
+        int64_t replyThread = 0;
+        if (wantProcessHandle) {
+            replyProcess = int64FromHandle(duplicateHandle(pi.hProcess));
+        }
+        if (wantThreadHandle) {
+            replyThread = int64FromHandle(duplicateHandle(pi.hThread));
+        }
+        CloseHandle(pi.hThread);
+        m_childProcess = pi.hProcess;
+        m_autoShutdown = (spawnFlags & WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN) != 0;
+        m_exitAfterShutdown = (spawnFlags & WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN) != 0;
+        reply.putInt32(static_cast<int32_t>(StartProcessResult::ProcessCreated));
+        reply.putInt64(replyProcess);
+        reply.putInt64(replyThread);
+    } else {
+        reply.putInt32(static_cast<int32_t>(StartProcessResult::CreateProcessFailed));
+        reply.putInt32(lastError);
+    }
+    writePacket(reply);
+}
+
+void Agent::handleSetSizePacket(ReadBuffer &packet)
+{
+    const int cols = packet.getInt32();
+    const int rows = packet.getInt32();
+    packet.assertEof();
+    resizeWindow(cols, rows);
+    auto reply = newPacket();
+    writePacket(reply);
+}
+
+void Agent::handleGetConsoleProcessListPacket(ReadBuffer &packet)
+{
+    packet.assertEof();
+
+    auto processList = std::vector<DWORD>(64);
+    auto processCount = GetConsoleProcessList(&processList[0], processList.size());
+    if (processList.size() < processCount) {
+        processList.resize(processCount);
+        processCount = GetConsoleProcessList(&processList[0], processList.size());
+    }
+
+    if (processCount == 0) {
+        trace("GetConsoleProcessList failed");
+    }
+
+    auto reply = newPacket();
+    reply.putInt32(processCount);
+    for (DWORD i = 0; i < processCount; i++) {
+        reply.putInt32(processList[i]);
+    }
+    writePacket(reply);
+}
+
+void Agent::pollConinPipe()
+{
+    const std::string newData = m_coninPipe->readAllToString();
+    if (hasDebugFlag("input_separated_bytes")) {
+        // This debug flag is intended to help with testing incomplete escape
+        // sequences and multibyte UTF-8 encodings.  (I wonder if the normal
+        // code path ought to advance a state machine one byte at a time.)
+        for (size_t i = 0; i < newData.size(); ++i) {
+            m_consoleInput->writeInput(newData.substr(i, 1));
+        }
+    } else {
+        m_consoleInput->writeInput(newData);
+    }
+}
+
+void Agent::onPollTimeout()
+{
+    m_consoleInput->updateInputFlags();
+    const bool enableMouseMode = m_consoleInput->shouldActivateTerminalMouse();
+
+    // Give the ConsoleInput object a chance to flush input from an incomplete
+    // escape sequence (e.g. pressing ESC).
+    m_consoleInput->flushIncompleteEscapeCode();
+
+    const bool shouldScrapeContent = !m_closingOutputPipes;
+
+    // Check if the child process has exited.
+    if (m_autoShutdown &&
+            m_childProcess != nullptr &&
+            WaitForSingleObject(m_childProcess, 0) == WAIT_OBJECT_0) {
+        CloseHandle(m_childProcess);
+        m_childProcess = nullptr;
+
+        // Close the data socket to signal to the client that the child
+        // process has exited.  If there's any data left to send, send it
+        // before closing the socket.
+        m_closingOutputPipes = true;
+    }
+
+    // Scrape for output *after* the above exit-check to ensure that we collect
+    // the child process's final output.
+    if (shouldScrapeContent) {
+        syncConsoleTitle();
+        scrapeBuffers();
+    }
+
+    // We must ensure that we disable mouse mode before closing the CONOUT
+    // pipe, so update the mouse mode here.
+    m_primaryScraper->terminal().enableMouseMode(
+        enableMouseMode && !m_closingOutputPipes);
+
+    autoClosePipesForShutdown();
+}
+
+void Agent::autoClosePipesForShutdown()
+{
+    if (m_closingOutputPipes) {
+        // We don't want to close a pipe before it's connected!  If we do, the
+        // libwinpty client may try to connect to a non-existent pipe.  This
+        // case is important for short-lived programs.
+        if (m_conoutPipe->isConnected() &&
+                m_conoutPipe->bytesToSend() == 0) {
+            trace("Closing CONOUT pipe (auto-shutdown)");
+            m_conoutPipe->closePipe();
+        }
+        if (m_conerrPipe != nullptr &&
+                m_conerrPipe->isConnected() &&
+                m_conerrPipe->bytesToSend() == 0) {
+            trace("Closing CONERR pipe (auto-shutdown)");
+            m_conerrPipe->closePipe();
+        }
+        if (m_exitAfterShutdown &&
+                m_conoutPipe->isClosed() &&
+                (m_conerrPipe == nullptr || m_conerrPipe->isClosed())) {
+            trace("Agent exiting (exit-after-shutdown)");
+            shutdown();
+        }
+    }
+}
+
+std::unique_ptr<Win32ConsoleBuffer> Agent::openPrimaryBuffer()
+{
+    // If we're using a separate buffer for stderr, and a program were to
+    // activate the stderr buffer, then we could accidentally scrape the same
+    // buffer twice.  That probably shouldn't happen in ordinary use, but it
+    // can be avoided anyway by using the original console screen buffer in
+    // that mode.
+    if (!m_useConerr) {
+        return Win32ConsoleBuffer::openConout();
+    } else {
+        return Win32ConsoleBuffer::openStdout();
+    }
+}
+
+void Agent::resizeWindow(int cols, int rows)
+{
+    ASSERT(cols >= 1 && rows >= 1);
+    cols = std::min(cols, MAX_CONSOLE_WIDTH);
+    rows = std::min(rows, MAX_CONSOLE_HEIGHT);
+
+    Win32Console::FreezeGuard guard(m_console, m_console.frozen());
+    const Coord newSize(cols, rows);
+    ConsoleScreenBufferInfo info;
+    auto primaryBuffer = openPrimaryBuffer();
+    m_primaryScraper->resizeWindow(*primaryBuffer, newSize, info);
+    m_consoleInput->setMouseWindowRect(info.windowRect());
+    if (m_errorScraper) {
+        m_errorScraper->resizeWindow(*m_errorBuffer, newSize, info);
+    }
+
+    // Synthesize a WINDOW_BUFFER_SIZE_EVENT event.  Normally, Windows
+    // generates this event only when the buffer size changes, not when the
+    // window size changes.  This behavior is undesirable in two ways:
+    //  - When winpty expands the window horizontally, it must expand the
+    //    buffer first, then the window.  At least some programs (e.g. the WSL
+    //    bash.exe wrapper) use the window width rather than the buffer width,
+    //    so there is a short timespan during which they can read the wrong
+    //    value.
+    //  - If the window's vertical size is changed, no event is generated,
+    //    even though a typical well-behaved console program cares about the
+    //    *window* height, not the *buffer* height.
+    // This synthesization works around a design flaw in the console.  It's probably
+    // harmless.  See https://github.com/rprichard/winpty/issues/110.
+    INPUT_RECORD sizeEvent {};
+    sizeEvent.EventType = WINDOW_BUFFER_SIZE_EVENT;
+    sizeEvent.Event.WindowBufferSizeEvent.dwSize = primaryBuffer->bufferSize();
+    DWORD actual {};
+    WriteConsoleInputW(GetStdHandle(STD_INPUT_HANDLE), &sizeEvent, 1, &actual);
+}
+
+void Agent::scrapeBuffers()
+{
+    Win32Console::FreezeGuard guard(m_console, m_console.frozen());
+    ConsoleScreenBufferInfo info;
+    m_primaryScraper->scrapeBuffer(*openPrimaryBuffer(), info);
+    m_consoleInput->setMouseWindowRect(info.windowRect());
+    if (m_errorScraper) {
+        m_errorScraper->scrapeBuffer(*m_errorBuffer, info);
+    }
+}
+
+void Agent::syncConsoleTitle()
+{
+    std::wstring newTitle = m_console.title();
+    if (newTitle != m_currentTitle) {
+        std::string command = std::string("\x1b]0;") +
+                utf8FromWide(newTitle) + "\x07";
+        m_conoutPipe->write(command.c_str());
+        m_currentTitle = newTitle;
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Agent.h b/node_modules/node-pty/deps/winpty/src/agent/Agent.h
new file mode 100644 (file)
index 0000000..1dde48f
--- /dev/null
@@ -0,0 +1,103 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_H
+#define AGENT_H
+
+#include <windows.h>
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+
+#include "DsrSender.h"
+#include "EventLoop.h"
+#include "Win32Console.h"
+
+class ConsoleInput;
+class NamedPipe;
+class ReadBuffer;
+class Scraper;
+class WriteBuffer;
+class Win32ConsoleBuffer;
+
+class Agent : public EventLoop, public DsrSender
+{
+public:
+    Agent(LPCWSTR controlPipeName,
+          uint64_t agentFlags,
+          int mouseMode,
+          int initialCols,
+          int initialRows);
+    virtual ~Agent();
+    void sendDsr() override;
+
+private:
+    NamedPipe &connectToControlPipe(LPCWSTR pipeName);
+    NamedPipe &createDataServerPipe(bool write, const wchar_t *kind);
+
+private:
+    void pollControlPipe();
+    void handlePacket(ReadBuffer &packet);
+    void writePacket(WriteBuffer &packet);
+    void handleStartProcessPacket(ReadBuffer &packet);
+    void handleSetSizePacket(ReadBuffer &packet);
+    void handleGetConsoleProcessListPacket(ReadBuffer &packet);
+    void pollConinPipe();
+
+protected:
+    virtual void onPollTimeout() override;
+    virtual void onPipeIo(NamedPipe &namedPipe) override;
+
+private:
+    void autoClosePipesForShutdown();
+    std::unique_ptr<Win32ConsoleBuffer> openPrimaryBuffer();
+    void resizeWindow(int cols, int rows);
+    void scrapeBuffers();
+    void syncConsoleTitle();
+
+private:
+    const bool m_useConerr;
+    const bool m_plainMode;
+    const int m_mouseMode;
+    Win32Console m_console;
+    std::unique_ptr<Scraper> m_primaryScraper;
+    std::unique_ptr<Scraper> m_errorScraper;
+    std::unique_ptr<Win32ConsoleBuffer> m_errorBuffer;
+    NamedPipe *m_controlPipe = nullptr;
+    NamedPipe *m_coninPipe = nullptr;
+    NamedPipe *m_conoutPipe = nullptr;
+    NamedPipe *m_conerrPipe = nullptr;
+    bool m_autoShutdown = false;
+    bool m_exitAfterShutdown = false;
+    bool m_closingOutputPipes = false;
+    std::unique_ptr<ConsoleInput> m_consoleInput;
+    HANDLE m_childProcess = nullptr;
+
+    // If the title is initialized to the empty string, then cmd.exe will
+    // sometimes print this error:
+    //     Not enough storage is available to process this command.
+    // It happens on Windows 7 when logged into a Cygwin SSH session, for
+    // example.  Using a title of a single space character avoids the problem.
+    // See https://github.com/rprichard/winpty/issues/74.
+    std::wstring m_currentTitle = L" ";
+};
+
+#endif // AGENT_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.cc b/node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.cc
new file mode 100644 (file)
index 0000000..9ad6503
--- /dev/null
@@ -0,0 +1,84 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "AgentCreateDesktop.h"
+
+#include "../shared/BackgroundDesktop.h"
+#include "../shared/Buffer.h"
+#include "../shared/DebugClient.h"
+#include "../shared/StringUtil.h"
+
+#include "EventLoop.h"
+#include "NamedPipe.h"
+
+namespace {
+
+static inline WriteBuffer newPacket() {
+    WriteBuffer packet;
+    packet.putRawValue<uint64_t>(0); // Reserve space for size.
+    return packet;
+}
+
+class CreateDesktopLoop : public EventLoop {
+public:
+    CreateDesktopLoop(LPCWSTR controlPipeName);
+
+protected:
+    virtual void onPipeIo(NamedPipe &namedPipe) override;
+
+private:
+    void writePacket(WriteBuffer &packet);
+
+    BackgroundDesktop m_desktop;
+    NamedPipe &m_pipe;
+};
+
+CreateDesktopLoop::CreateDesktopLoop(LPCWSTR controlPipeName) :
+        m_pipe(createNamedPipe()) {
+    m_pipe.connectToServer(controlPipeName, NamedPipe::OpenMode::Duplex);
+    auto packet = newPacket();
+    packet.putWString(m_desktop.desktopName());
+    writePacket(packet);
+}
+
+void CreateDesktopLoop::writePacket(WriteBuffer &packet) {
+    const auto &bytes = packet.buf();
+    packet.replaceRawValue<uint64_t>(0, bytes.size());
+    m_pipe.write(bytes.data(), bytes.size());
+}
+
+void CreateDesktopLoop::onPipeIo(NamedPipe &namedPipe) {
+    if (m_pipe.isClosed()) {
+        shutdown();
+    }
+}
+
+} // anonymous namespace
+
+void handleCreateDesktop(LPCWSTR controlPipeName) {
+    try {
+        CreateDesktopLoop loop(controlPipeName);
+        loop.run();
+        trace("Agent exiting...");
+    } catch (const WinptyException &e) {
+        trace("handleCreateDesktop: internal error: %s",
+            utf8FromWide(e.what()).c_str());
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.h b/node_modules/node-pty/deps/winpty/src/agent/AgentCreateDesktop.h
new file mode 100644 (file)
index 0000000..2ae539c
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_CREATE_DESKTOP_H
+#define AGENT_CREATE_DESKTOP_H
+
+#include <windows.h>
+
+void handleCreateDesktop(LPCWSTR controlPipeName);
+
+#endif //  AGENT_CREATE_DESKTOP_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.cc b/node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.cc
new file mode 100644 (file)
index 0000000..aa1f787
--- /dev/null
@@ -0,0 +1,698 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "ConsoleFont.h"
+
+#include <windows.h>
+#include <stdio.h>
+#include <string.h>
+#include <wchar.h>
+
+#include <algorithm>
+#include <string>
+#include <tuple>
+#include <utility>
+#include <vector>
+
+#include "../shared/DebugClient.h"
+#include "../shared/OsModule.h"
+#include "../shared/StringUtil.h"
+#include "../shared/WindowsVersion.h"
+#include "../shared/WinptyAssert.h"
+#include "../shared/winpty_snprintf.h"
+
+namespace {
+
+#define COUNT_OF(x) (sizeof(x) / sizeof((x)[0]))
+
+// See https://en.wikipedia.org/wiki/List_of_CJK_fonts
+const wchar_t kLucidaConsole[] = L"Lucida Console";
+const wchar_t kMSGothic[] = { 0xff2d, 0xff33, 0x0020, 0x30b4, 0x30b7, 0x30c3, 0x30af, 0 }; // 932, Japanese
+const wchar_t kNSimSun[] = { 0x65b0, 0x5b8b, 0x4f53, 0 }; // 936, Chinese Simplified
+const wchar_t kGulimChe[] = { 0xad74, 0xb9bc, 0xccb4, 0 }; // 949, Korean
+const wchar_t kMingLight[] = { 0x7d30, 0x660e, 0x9ad4, 0 }; // 950, Chinese Traditional
+
+struct FontSize {
+    short size;
+    int width;
+};
+
+struct Font {
+    const wchar_t *faceName;
+    unsigned int family;
+    short size;
+};
+
+// Ideographs in East Asian languages take two columns rather than one.
+// In the console screen buffer, a "full-width" character will occupy two
+// cells of the buffer, the first with attribute 0x100 and the second with
+// attribute 0x200.
+//
+// Windows does not correctly identify code points as double-width in all
+// configurations.  It depends heavily on the code page, the font facename,
+// and (somehow) even the font size.  In the 437 code page (MS-DOS), for
+// example, no codepoints are interpreted as double-width.  When the console
+// is in an East Asian code page (932, 936, 949, or 950), then sometimes
+// selecting a "Western" facename like "Lucida Console" or "Consolas" doesn't
+// register, or if the font *can* be chosen, then the console doesn't handle
+// double-width correctly.  I tested the double-width handling by writing
+// several code points with WriteConsole and checking whether one or two cells
+// were filled.
+//
+// In the Japanese code page (932), Microsoft's default font is MS Gothic.
+// MS Gothic double-width handling seems to be broken with console versions
+// prior to Windows 10 (including Windows 10's legacy mode), and it's
+// especially broken in Windows 8 and 8.1.
+//
+// Test by running: misc/Utf16Echo A2 A3 2014 3044 30FC 4000
+//
+// The first three codepoints are always rendered as half-width with the
+// Windows Japanese fonts.  (Of these, the first two must be half-width,
+// but U+2014 could be either.)  The last three are rendered as full-width,
+// and they are East_Asian_Width=Wide.
+//
+// Windows 7 fails by modeling all codepoints as full-width with font
+// sizes 22 and above.
+//
+// Windows 8 gets U+00A2, U+00A3, U+2014, U+30FC, and U+4000 wrong, but
+// using a point size not listed in the console properties dialog
+// (e.g. "9") is less wrong:
+//
+//             |        code point               |
+//  font       | 00A2 00A3 2014 3044 30FC 4000   | cell size
+// ------------+---------------------------------+----------
+//  8          |  F    F    F    F    H    H     |   4x8
+//  9          |  F    F    F    F    F    F     |   5x9
+//  16         |  F    F    F    F    H    H     |   8x16
+// raster 6x13 |  H    H    H    F    F    H(*)  |   6x13
+//
+// (*) The Raster Font renders U+4000 as a white box (i.e. an unsupported
+// character).
+//
+
+// See:
+//  - misc/Font-Report-June2016 directory for per-size details
+//  - misc/font-notes.txt
+//  - misc/Utf16Echo.cc, misc/FontSurvey.cc, misc/SetFont.cc, misc/GetFont.cc
+
+const FontSize kLucidaFontSizes[] = {
+    { 5, 3 },
+    { 6, 4 },
+    { 8, 5 },
+    { 10, 6 },
+    { 12, 7 },
+    { 14, 8 },
+    { 16, 10 },
+    { 18, 11 },
+    { 20, 12 },
+    { 36, 22 },
+    { 48, 29 },
+    { 60, 36 },
+    { 72, 43 },
+};
+
+// Japanese.  Used on Vista and Windows 7.
+const FontSize k932GothicVista[] = {
+    { 6, 3 },
+    { 8, 4 },
+    { 10, 5 },
+    { 12, 6 },
+    { 13, 7 },
+    { 15, 8 },
+    { 17, 9 },
+    { 19, 10 },
+    { 21, 11 },
+    // All larger fonts are more broken w.r.t. full-size East Asian characters.
+};
+
+// Japanese.  Used on Windows 8, 8.1, and the legacy 10 console.
+const FontSize k932GothicWin8[] = {
+    // All of these characters are broken w.r.t. full-size East Asian
+    // characters, but they're equally broken.
+    { 5, 3 },
+    { 7, 4 },
+    { 9, 5 },
+    { 11, 6 },
+    { 13, 7 },
+    { 15, 8 },
+    { 17, 9 },
+    { 20, 10 },
+    { 22, 11 },
+    { 24, 12 },
+    // include extra-large fonts for small terminals
+    { 36, 18 },
+    { 48, 24 },
+    { 60, 30 },
+    { 72, 36 },
+};
+
+// Japanese.  Used on the new Windows 10 console.
+const FontSize k932GothicWin10[] = {
+    { 6, 3 },
+    { 8, 4 },
+    { 10, 5 },
+    { 12, 6 },
+    { 14, 7 },
+    { 16, 8 },
+    { 18, 9 },
+    { 20, 10 },
+    { 22, 11 },
+    { 24, 12 },
+    // include extra-large fonts for small terminals
+    { 36, 18 },
+    { 48, 24 },
+    { 60, 30 },
+    { 72, 36 },
+};
+
+// Chinese Simplified.
+const FontSize k936SimSun[] = {
+    { 6, 3 },
+    { 8, 4 },
+    { 10, 5 },
+    { 12, 6 },
+    { 14, 7 },
+    { 16, 8 },
+    { 18, 9 },
+    { 20, 10 },
+    { 22, 11 },
+    { 24, 12 },
+    // include extra-large fonts for small terminals
+    { 36, 18 },
+    { 48, 24 },
+    { 60, 30 },
+    { 72, 36 },
+};
+
+// Korean.
+const FontSize k949GulimChe[] = {
+    { 6, 3 },
+    { 8, 4 },
+    { 10, 5 },
+    { 12, 6 },
+    { 14, 7 },
+    { 16, 8 },
+    { 18, 9 },
+    { 20, 10 },
+    { 22, 11 },
+    { 24, 12 },
+    // include extra-large fonts for small terminals
+    { 36, 18 },
+    { 48, 24 },
+    { 60, 30 },
+    { 72, 36 },
+};
+
+// Chinese Traditional.
+const FontSize k950MingLight[] = {
+    { 6, 3 },
+    { 8, 4 },
+    { 10, 5 },
+    { 12, 6 },
+    { 14, 7 },
+    { 16, 8 },
+    { 18, 9 },
+    { 20, 10 },
+    { 22, 11 },
+    { 24, 12 },
+    // include extra-large fonts for small terminals
+    { 36, 18 },
+    { 48, 24 },
+    { 60, 30 },
+    { 72, 36 },
+};
+
+// Some of these types and functions are missing from the MinGW headers.
+// Others are undocumented.
+
+struct AGENT_CONSOLE_FONT_INFO {
+    DWORD nFont;
+    COORD dwFontSize;
+};
+
+struct AGENT_CONSOLE_FONT_INFOEX {
+    ULONG cbSize;
+    DWORD nFont;
+    COORD dwFontSize;
+    UINT FontFamily;
+    UINT FontWeight;
+    WCHAR FaceName[LF_FACESIZE];
+};
+
+// undocumented XP API
+typedef BOOL WINAPI SetConsoleFont_t(
+            HANDLE hOutput,
+            DWORD dwFontIndex);
+
+// undocumented XP API
+typedef DWORD WINAPI GetNumberOfConsoleFonts_t();
+
+// XP and up
+typedef BOOL WINAPI GetCurrentConsoleFont_t(
+            HANDLE hOutput,
+            BOOL bMaximumWindow,
+            AGENT_CONSOLE_FONT_INFO *lpConsoleCurrentFont);
+
+// XP and up
+typedef COORD WINAPI GetConsoleFontSize_t(
+            HANDLE hConsoleOutput,
+            DWORD nFont);
+
+// Vista and up
+typedef BOOL WINAPI GetCurrentConsoleFontEx_t(
+            HANDLE hConsoleOutput,
+            BOOL bMaximumWindow,
+            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
+
+// Vista and up
+typedef BOOL WINAPI SetCurrentConsoleFontEx_t(
+            HANDLE hConsoleOutput,
+            BOOL bMaximumWindow,
+            AGENT_CONSOLE_FONT_INFOEX *lpConsoleCurrentFontEx);
+
+#define GET_MODULE_PROC(mod, funcName) \
+    m_##funcName = reinterpret_cast<funcName##_t*>((mod).proc(#funcName)); \
+
+#define DEFINE_ACCESSOR(funcName) \
+    funcName##_t &funcName() const { \
+        ASSERT(valid()); \
+        return *m_##funcName; \
+    }
+
+class XPFontAPI {
+public:
+    XPFontAPI() : m_kernel32(L"kernel32.dll") {
+        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFont);
+        GET_MODULE_PROC(m_kernel32, GetConsoleFontSize);
+    }
+
+    bool valid() const {
+        return m_GetCurrentConsoleFont != NULL &&
+            m_GetConsoleFontSize != NULL;
+    }
+
+    DEFINE_ACCESSOR(GetCurrentConsoleFont)
+    DEFINE_ACCESSOR(GetConsoleFontSize)
+
+private:
+    OsModule m_kernel32;
+    GetCurrentConsoleFont_t *m_GetCurrentConsoleFont;
+    GetConsoleFontSize_t *m_GetConsoleFontSize;
+};
+
+class UndocumentedXPFontAPI : public XPFontAPI {
+public:
+    UndocumentedXPFontAPI() : m_kernel32(L"kernel32.dll") {
+        GET_MODULE_PROC(m_kernel32, SetConsoleFont);
+        GET_MODULE_PROC(m_kernel32, GetNumberOfConsoleFonts);
+    }
+
+    bool valid() const {
+        return this->XPFontAPI::valid() &&
+            m_SetConsoleFont != NULL &&
+            m_GetNumberOfConsoleFonts != NULL;
+    }
+
+    DEFINE_ACCESSOR(SetConsoleFont)
+    DEFINE_ACCESSOR(GetNumberOfConsoleFonts)
+
+private:
+    OsModule m_kernel32;
+    SetConsoleFont_t *m_SetConsoleFont;
+    GetNumberOfConsoleFonts_t *m_GetNumberOfConsoleFonts;
+};
+
+class VistaFontAPI : public XPFontAPI {
+public:
+    VistaFontAPI() : m_kernel32(L"kernel32.dll") {
+        GET_MODULE_PROC(m_kernel32, GetCurrentConsoleFontEx);
+        GET_MODULE_PROC(m_kernel32, SetCurrentConsoleFontEx);
+    }
+
+    bool valid() const {
+        return this->XPFontAPI::valid() &&
+            m_GetCurrentConsoleFontEx != NULL &&
+            m_SetCurrentConsoleFontEx != NULL;
+    }
+
+    DEFINE_ACCESSOR(GetCurrentConsoleFontEx)
+    DEFINE_ACCESSOR(SetCurrentConsoleFontEx)
+
+private:
+    OsModule m_kernel32;
+    GetCurrentConsoleFontEx_t *m_GetCurrentConsoleFontEx;
+    SetCurrentConsoleFontEx_t *m_SetCurrentConsoleFontEx;
+};
+
+static std::vector<std::pair<DWORD, COORD> > readFontTable(
+        XPFontAPI &api, HANDLE conout, DWORD maxCount) {
+    std::vector<std::pair<DWORD, COORD> > ret;
+    for (DWORD i = 0; i < maxCount; ++i) {
+        COORD size = api.GetConsoleFontSize()(conout, i);
+        if (size.X == 0 && size.Y == 0) {
+            break;
+        }
+        ret.push_back(std::make_pair(i, size));
+    }
+    return ret;
+}
+
+static void dumpFontTable(HANDLE conout, const char *prefix) {
+    const int kMaxCount = 1000;
+    if (!isTracingEnabled()) {
+        return;
+    }
+    XPFontAPI api;
+    if (!api.valid()) {
+        trace("dumpFontTable: cannot dump font table -- missing APIs");
+        return;
+    }
+    std::vector<std::pair<DWORD, COORD> > table =
+        readFontTable(api, conout, kMaxCount);
+    std::string line;
+    char tmp[128];
+    size_t first = 0;
+    while (first < table.size()) {
+        size_t last = std::min(table.size() - 1, first + 10 - 1);
+        winpty_snprintf(tmp, "%sfonts %02u-%02u:",
+            prefix, static_cast<unsigned>(first), static_cast<unsigned>(last));
+        line = tmp;
+        for (size_t i = first; i <= last; ++i) {
+            if (i % 10 == 5) {
+                line += "  - ";
+            }
+            winpty_snprintf(tmp, " %2dx%-2d",
+                table[i].second.X, table[i].second.Y);
+            line += tmp;
+        }
+        trace("%s", line.c_str());
+        first = last + 1;
+    }
+    if (table.size() == kMaxCount) {
+        trace("%sfonts: ... stopped reading at %d fonts ...",
+            prefix, kMaxCount);
+    }
+}
+
+static std::string stringToCodePoints(const std::wstring &str) {
+    std::string ret = "(";
+    for (size_t i = 0; i < str.size(); ++i) {
+        char tmp[32];
+        winpty_snprintf(tmp, "%X", str[i]);
+        if (ret.size() > 1) {
+            ret.push_back(' ');
+        }
+        ret += tmp;
+    }
+    ret.push_back(')');
+    return ret;
+}
+
+static void dumpFontInfoEx(
+        const AGENT_CONSOLE_FONT_INFOEX &infoex,
+        const char *prefix) {
+    if (!isTracingEnabled()) {
+        return;
+    }
+    std::wstring faceName(infoex.FaceName,
+        winpty_wcsnlen(infoex.FaceName, COUNT_OF(infoex.FaceName)));
+    trace("%snFont=%u dwFontSize=(%d,%d) "
+        "FontFamily=0x%x FontWeight=%u FaceName=%s %s",
+        prefix,
+        static_cast<unsigned>(infoex.nFont),
+        infoex.dwFontSize.X, infoex.dwFontSize.Y,
+        infoex.FontFamily, infoex.FontWeight, utf8FromWide(faceName).c_str(),
+        stringToCodePoints(faceName).c_str());
+}
+
+static void dumpVistaFont(VistaFontAPI &api, HANDLE conout, const char *prefix) {
+    if (!isTracingEnabled()) {
+        return;
+    }
+    AGENT_CONSOLE_FONT_INFOEX infoex = {0};
+    infoex.cbSize = sizeof(infoex);
+    if (!api.GetCurrentConsoleFontEx()(conout, FALSE, &infoex)) {
+        trace("GetCurrentConsoleFontEx call failed");
+        return;
+    }
+    dumpFontInfoEx(infoex, prefix);
+}
+
+static void dumpXPFont(XPFontAPI &api, HANDLE conout, const char *prefix) {
+    if (!isTracingEnabled()) {
+        return;
+    }
+    AGENT_CONSOLE_FONT_INFO info = {0};
+    if (!api.GetCurrentConsoleFont()(conout, FALSE, &info)) {
+        trace("GetCurrentConsoleFont call failed");
+        return;
+    }
+    trace("%snFont=%u dwFontSize=(%d,%d)",
+        prefix,
+        static_cast<unsigned>(info.nFont),
+        info.dwFontSize.X, info.dwFontSize.Y);
+}
+
+static bool setFontVista(
+        VistaFontAPI &api,
+        HANDLE conout,
+        const Font &font) {
+    AGENT_CONSOLE_FONT_INFOEX infoex = {};
+    infoex.cbSize = sizeof(AGENT_CONSOLE_FONT_INFOEX);
+    infoex.dwFontSize.Y = font.size;
+    infoex.FontFamily = font.family;
+    infoex.FontWeight = 400;
+    winpty_wcsncpy_nul(infoex.FaceName, font.faceName);
+    dumpFontInfoEx(infoex, "setFontVista: setting font to: ");
+    if (!api.SetCurrentConsoleFontEx()(conout, FALSE, &infoex)) {
+        trace("setFontVista: SetCurrentConsoleFontEx call failed");
+        return false;
+    }
+    memset(&infoex, 0, sizeof(infoex));
+    infoex.cbSize = sizeof(infoex);
+    if (!api.GetCurrentConsoleFontEx()(conout, FALSE, &infoex)) {
+        trace("setFontVista: GetCurrentConsoleFontEx call failed");
+        return false;
+    }
+    if (wcsncmp(infoex.FaceName, font.faceName,
+            COUNT_OF(infoex.FaceName)) != 0) {
+        trace("setFontVista: face name was not set");
+        dumpFontInfoEx(infoex, "setFontVista: post-call font: ");
+        return false;
+    }
+    // We'd like to verify that the new font size is correct, but we can't
+    // predict what it will be, even though we just set it to `pxSize` through
+    // an apprently symmetric interface.  For the Chinese and Korean fonts, the
+    // new `infoex.dwFontSize.Y` value can be slightly larger than the height
+    // we specified.
+    return true;
+}
+
+static Font selectSmallFont(int codePage, int columns, bool isNewW10) {
+    // Iterate over a set of font sizes according to the code page, and select
+    // one.
+
+    const wchar_t *faceName = nullptr;
+    unsigned int fontFamily = 0;
+    const FontSize *table = nullptr;
+    size_t tableSize = 0;
+
+    switch (codePage) {
+        case 932: // Japanese
+            faceName = kMSGothic;
+            fontFamily = 0x36;
+            if (isNewW10) {
+                table = k932GothicWin10;
+                tableSize = COUNT_OF(k932GothicWin10);
+            } else if (isAtLeastWindows8()) {
+                table = k932GothicWin8;
+                tableSize = COUNT_OF(k932GothicWin8);
+            } else {
+                table = k932GothicVista;
+                tableSize = COUNT_OF(k932GothicVista);
+            }
+            break;
+        case 936: // Chinese Simplified
+            faceName = kNSimSun;
+            fontFamily = 0x36;
+            table = k936SimSun;
+            tableSize = COUNT_OF(k936SimSun);
+            break;
+        case 949: // Korean
+            faceName = kGulimChe;
+            fontFamily = 0x36;
+            table = k949GulimChe;
+            tableSize = COUNT_OF(k949GulimChe);
+            break;
+        case 950: // Chinese Traditional
+            faceName = kMingLight;
+            fontFamily = 0x36;
+            table = k950MingLight;
+            tableSize = COUNT_OF(k950MingLight);
+            break;
+        default:
+            faceName = kLucidaConsole;
+            fontFamily = 0x36;
+            table = kLucidaFontSizes;
+            tableSize = COUNT_OF(kLucidaFontSizes);
+            break;
+    }
+
+    size_t bestIndex = static_cast<size_t>(-1);
+    std::tuple<int, int> bestScore = std::make_tuple(-1, -1);
+
+    // We might want to pick the smallest possible font, because we don't know
+    // how large the monitor is (and the monitor size can change).  We might
+    // want to pick a larger font to accommodate console programs that resize
+    // the console on their own, like DOS edit.com, which tends to resize the
+    // console to 80 columns.
+
+    for (size_t i = 0; i < tableSize; ++i) {
+        const int width = table[i].width * columns;
+
+        // In general, we'd like to pick a font size where cutting the number
+        // of columns in half doesn't immediately violate the minimum width
+        // constraint.  (e.g. To run DOS edit.com, a user might resize their
+        // terminal to ~100 columns so it's big enough to show the 80 columns
+        // post-resize.)  To achieve this, give priority to fonts that allow
+        // this halving.  We don't want to encourage *very* large fonts,
+        // though, so disable the effect as the number of columns scales from
+        // 80 to 40.
+        const int halfColumns = std::min(columns, std::max(40, columns / 2));
+        const int halfWidth = table[i].width * halfColumns;
+
+        std::tuple<int, int> thisScore = std::make_tuple(-1, -1);
+        if (width >= 160 && halfWidth >= 160) {
+            // Both sizes are good.  Prefer the smaller fonts.
+            thisScore = std::make_tuple(2, -width);
+        } else if (width >= 160) {
+            // Prefer the smaller fonts.
+            thisScore = std::make_tuple(1, -width);
+        } else {
+            // Otherwise, prefer the largest font in our table.
+            thisScore = std::make_tuple(0, width);
+        }
+        if (thisScore > bestScore) {
+            bestIndex = i;
+            bestScore = thisScore;
+        }
+    }
+
+    ASSERT(bestIndex != static_cast<size_t>(-1));
+    return Font { faceName, fontFamily, table[bestIndex].size };
+}
+
+static void setSmallFontVista(VistaFontAPI &api, HANDLE conout,
+                              int columns, bool isNewW10) {
+    int codePage = GetConsoleOutputCP();
+    const auto font = selectSmallFont(codePage, columns, isNewW10);
+    if (setFontVista(api, conout, font)) {
+        trace("setSmallFontVista: success");
+        return;
+    }
+    if (codePage == 932 || codePage == 936 ||
+            codePage == 949 || codePage == 950) {
+        trace("setSmallFontVista: falling back to default codepage font instead");
+        const auto fontFB = selectSmallFont(0, columns, isNewW10);
+        if (setFontVista(api, conout, fontFB)) {
+            trace("setSmallFontVista: fallback was successful");
+            return;
+        }
+    }
+    trace("setSmallFontVista: failure");
+}
+
+struct FontSizeComparator {
+    bool operator()(const std::pair<DWORD, COORD> &obj1,
+                    const std::pair<DWORD, COORD> &obj2) const {
+        int score1 = obj1.second.X + obj1.second.Y;
+        int score2 = obj2.second.X + obj2.second.Y;
+        return score1 < score2;
+    }
+};
+
+static void setSmallFontXP(UndocumentedXPFontAPI &api, HANDLE conout) {
+    // Read the console font table and sort it from smallest to largest.
+    const DWORD fontCount = api.GetNumberOfConsoleFonts()();
+    trace("setSmallFontXP: number of console fonts: %u",
+        static_cast<unsigned>(fontCount));
+    std::vector<std::pair<DWORD, COORD> > table =
+        readFontTable(api, conout, fontCount);
+    std::sort(table.begin(), table.end(), FontSizeComparator());
+    for (size_t i = 0; i < table.size(); ++i) {
+        // Skip especially narrow fonts to permit narrower terminals.
+        if (table[i].second.X < 4) {
+            continue;
+        }
+        trace("setSmallFontXP: setting font to %u",
+            static_cast<unsigned>(table[i].first));
+        if (!api.SetConsoleFont()(conout, table[i].first)) {
+            trace("setSmallFontXP: SetConsoleFont call failed");
+            continue;
+        }
+        AGENT_CONSOLE_FONT_INFO info;
+        if (!api.GetCurrentConsoleFont()(conout, FALSE, &info)) {
+            trace("setSmallFontXP: GetCurrentConsoleFont call failed");
+            return;
+        }
+        if (info.nFont != table[i].first) {
+            trace("setSmallFontXP: font was not set");
+            dumpXPFont(api, conout, "setSmallFontXP: post-call font: ");
+            continue;
+        }
+        trace("setSmallFontXP: success");
+        return;
+    }
+    trace("setSmallFontXP: failure");
+}
+
+} // anonymous namespace
+
+// A Windows console window can never be larger than the desktop window.  To
+// maximize the possible size of the console in rows*cols, try to configure
+// the console with a small font.  Unfortunately, we cannot make the font *too*
+// small, because there is also a minimum window size in pixels.
+void setSmallFont(HANDLE conout, int columns, bool isNewW10) {
+    trace("setSmallFont: attempting to set a small font for %d columns "
+        "(CP=%u OutputCP=%u)",
+        columns,
+        static_cast<unsigned>(GetConsoleCP()),
+        static_cast<unsigned>(GetConsoleOutputCP()));
+    VistaFontAPI vista;
+    if (vista.valid()) {
+        dumpVistaFont(vista, conout, "previous font: ");
+        dumpFontTable(conout, "previous font table: ");
+        setSmallFontVista(vista, conout, columns, isNewW10);
+        dumpVistaFont(vista, conout, "new font: ");
+        dumpFontTable(conout, "new font table: ");
+        return;
+    }
+    UndocumentedXPFontAPI xp;
+    if (xp.valid()) {
+        dumpXPFont(xp, conout, "previous font: ");
+        dumpFontTable(conout, "previous font table: ");
+        setSmallFontXP(xp, conout);
+        dumpXPFont(xp, conout, "new font: ");
+        dumpFontTable(conout, "new font table: ");
+        return;
+    }
+    trace("setSmallFont: neither Vista nor XP APIs detected -- giving up");
+    dumpFontTable(conout, "font table: ");
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.h b/node_modules/node-pty/deps/winpty/src/agent/ConsoleFont.h
new file mode 100644 (file)
index 0000000..99cb106
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef CONSOLEFONT_H
+#define CONSOLEFONT_H
+
+#include <windows.h>
+
+void setSmallFont(HANDLE conout, int columns, bool isNewW10);
+
+#endif // CONSOLEFONT_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.cc b/node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.cc
new file mode 100644 (file)
index 0000000..192cac2
--- /dev/null
@@ -0,0 +1,852 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "ConsoleInput.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include <algorithm>
+#include <string>
+
+#include "../include/winpty_constants.h"
+
+#include "../shared/DebugClient.h"
+#include "../shared/StringBuilder.h"
+#include "../shared/UnixCtrlChars.h"
+
+#include "ConsoleInputReencoding.h"
+#include "DebugShowInput.h"
+#include "DefaultInputMap.h"
+#include "DsrSender.h"
+#include "UnicodeEncoding.h"
+#include "Win32Console.h"
+
+// MAPVK_VK_TO_VSC isn't defined by the old MinGW.
+#ifndef MAPVK_VK_TO_VSC
+#define MAPVK_VK_TO_VSC 0
+#endif
+
+namespace {
+
+struct MouseRecord {
+    bool release;
+    int flags;
+    COORD coord;
+
+    std::string toString() const;
+};
+
+std::string MouseRecord::toString() const {
+    StringBuilder sb(40);
+    sb << "pos=" << coord.X << ',' << coord.Y
+       << " flags=0x" << hexOfInt(flags);
+    if (release) {
+        sb << " release";
+    }
+    return sb.str_moved();
+}
+
+const unsigned int kIncompleteEscapeTimeoutMs = 1000u;
+
+#define CHECK(cond)                                 \
+        do {                                        \
+            if (!(cond)) { return 0; }              \
+        } while(0)
+
+#define ADVANCE()                                   \
+        do {                                        \
+            pch++;                                  \
+            if (pch == stop) { return -1; }         \
+        } while(0)
+
+#define SCAN_INT(out, maxLen)                       \
+        do {                                        \
+            (out) = 0;                              \
+            CHECK(isdigit(*pch));                   \
+            const char *begin = pch;                \
+            do {                                    \
+                CHECK(pch - begin + 1 < maxLen);    \
+                (out) = (out) * 10 + *pch - '0';    \
+                ADVANCE();                          \
+            } while (isdigit(*pch));                \
+        } while(0)
+
+#define SCAN_SIGNED_INT(out, maxLen)                \
+        do {                                        \
+            bool negative = false;                  \
+            if (*pch == '-') {                      \
+                negative = true;                    \
+                ADVANCE();                          \
+            }                                       \
+            SCAN_INT(out, maxLen);                  \
+            if (negative) {                         \
+                (out) = -(out);                     \
+            }                                       \
+        } while(0)
+
+// Match the Device Status Report console input:  ESC [ nn ; mm R
+// Returns:
+// 0   no match
+// >0  match, returns length of match
+// -1  incomplete match
+static int matchDsr(const char *input, int inputSize)
+{
+    int32_t dummy = 0;
+    const char *pch = input;
+    const char *stop = input + inputSize;
+    CHECK(*pch == '\x1B');  ADVANCE();
+    CHECK(*pch == '[');     ADVANCE();
+    SCAN_INT(dummy, 8);
+    CHECK(*pch == ';');     ADVANCE();
+    SCAN_INT(dummy, 8);
+    CHECK(*pch == 'R');
+    return pch - input + 1;
+}
+
+static int matchMouseDefault(const char *input, int inputSize,
+                             MouseRecord &out)
+{
+    const char *pch = input;
+    const char *stop = input + inputSize;
+    CHECK(*pch == '\x1B');              ADVANCE();
+    CHECK(*pch == '[');                 ADVANCE();
+    CHECK(*pch == 'M');                 ADVANCE();
+    out.flags = (*pch - 32) & 0xFF;     ADVANCE();
+    out.coord.X = (*pch - '!') & 0xFF;
+    ADVANCE();
+    out.coord.Y = (*pch - '!') & 0xFF;
+    out.release = false;
+    return pch - input + 1;
+}
+
+static int matchMouse1006(const char *input, int inputSize, MouseRecord &out)
+{
+    const char *pch = input;
+    const char *stop = input + inputSize;
+    int32_t temp;
+    CHECK(*pch == '\x1B');      ADVANCE();
+    CHECK(*pch == '[');         ADVANCE();
+    CHECK(*pch == '<');         ADVANCE();
+    SCAN_INT(out.flags, 8);
+    CHECK(*pch == ';');         ADVANCE();
+    SCAN_SIGNED_INT(temp, 8); out.coord.X = temp - 1;
+    CHECK(*pch == ';');         ADVANCE();
+    SCAN_SIGNED_INT(temp, 8); out.coord.Y = temp - 1;
+    CHECK(*pch == 'M' || *pch == 'm');
+    out.release = (*pch == 'm');
+    return pch - input + 1;
+}
+
+static int matchMouse1015(const char *input, int inputSize, MouseRecord &out)
+{
+    const char *pch = input;
+    const char *stop = input + inputSize;
+    int32_t temp;
+    CHECK(*pch == '\x1B');      ADVANCE();
+    CHECK(*pch == '[');         ADVANCE();
+    SCAN_INT(out.flags, 8); out.flags -= 32;
+    CHECK(*pch == ';');         ADVANCE();
+    SCAN_SIGNED_INT(temp, 8); out.coord.X = temp - 1;
+    CHECK(*pch == ';');         ADVANCE();
+    SCAN_SIGNED_INT(temp, 8); out.coord.Y = temp - 1;
+    CHECK(*pch == 'M');
+    out.release = false;
+    return pch - input + 1;
+}
+
+// Match a mouse input escape sequence of any kind.
+// 0   no match
+// >0  match, returns length of match
+// -1  incomplete match
+static int matchMouseRecord(const char *input, int inputSize, MouseRecord &out)
+{
+    memset(&out, 0, sizeof(out));
+    int ret;
+    if ((ret = matchMouse1006(input, inputSize, out)) != 0) { return ret; }
+    if ((ret = matchMouse1015(input, inputSize, out)) != 0) { return ret; }
+    if ((ret = matchMouseDefault(input, inputSize, out)) != 0) { return ret; }
+    return 0;
+}
+
+#undef CHECK
+#undef ADVANCE
+#undef SCAN_INT
+
+} // anonymous namespace
+
+ConsoleInput::ConsoleInput(HANDLE conin, int mouseMode, DsrSender &dsrSender,
+                           Win32Console &console) :
+    m_console(console),
+    m_conin(conin),
+    m_mouseMode(mouseMode),
+    m_dsrSender(dsrSender)
+{
+    addDefaultEntriesToInputMap(m_inputMap);
+    if (hasDebugFlag("dump_input_map")) {
+        m_inputMap.dumpInputMap();
+    }
+
+    // Configure Quick Edit mode according to the mouse mode.  Enable
+    // InsertMode for two reasons:
+    //  - If it's OFF, it's difficult for the user to turn it ON.  The
+    //    properties dialog is inaccesible.  winpty still faithfully handles
+    //    the Insert key, which toggles between the insertion and overwrite
+    //    modes.
+    //  - When we modify the QuickEdit setting, if ExtendedFlags is OFF,
+    //    then we must choose the InsertMode setting.  I don't *think* this
+    //    case happens, though, because a new console always has ExtendedFlags
+    //    ON.
+    // See misc/EnableExtendedFlags.txt.
+    DWORD mode = 0;
+    if (!GetConsoleMode(conin, &mode)) {
+        trace("Agent startup: GetConsoleMode failed");
+    } else {
+        mode |= ENABLE_EXTENDED_FLAGS;
+        mode |= ENABLE_INSERT_MODE;
+        if (m_mouseMode == WINPTY_MOUSE_MODE_AUTO) {
+            mode |= ENABLE_QUICK_EDIT_MODE;
+        } else {
+            mode &= ~ENABLE_QUICK_EDIT_MODE;
+        }
+        if (!SetConsoleMode(conin, mode)) {
+            trace("Agent startup: SetConsoleMode failed");
+        }
+    }
+
+    updateInputFlags(true);
+}
+
+void ConsoleInput::writeInput(const std::string &input)
+{
+    if (input.size() == 0) {
+        return;
+    }
+
+    if (isTracingEnabled()) {
+        static bool debugInput = hasDebugFlag("input");
+        if (debugInput) {
+            std::string dumpString;
+            for (size_t i = 0; i < input.size(); ++i) {
+                const char ch = input[i];
+                const char ctrl = decodeUnixCtrlChar(ch);
+                if (ctrl != '\0') {
+                    dumpString += '^';
+                    dumpString += ctrl;
+                } else {
+                    dumpString += ch;
+                }
+            }
+            dumpString += " (";
+            for (size_t i = 0; i < input.size(); ++i) {
+                if (i > 0) {
+                    dumpString += ' ';
+                }
+                const unsigned char uch = input[i];
+                char buf[32];
+                winpty_snprintf(buf, "%02X", uch);
+                dumpString += buf;
+            }
+            dumpString += ')';
+            trace("input chars: %s", dumpString.c_str());
+        }
+    }
+
+    m_byteQueue.append(input);
+    doWrite(false);
+    if (!m_byteQueue.empty() && !m_dsrSent) {
+        trace("send DSR");
+        m_dsrSender.sendDsr();
+        m_dsrSent = true;
+    }
+    m_lastWriteTick = GetTickCount();
+}
+
+void ConsoleInput::flushIncompleteEscapeCode()
+{
+    if (!m_byteQueue.empty() &&
+            (GetTickCount() - m_lastWriteTick) > kIncompleteEscapeTimeoutMs) {
+        doWrite(true);
+        m_byteQueue.clear();
+    }
+}
+
+void ConsoleInput::updateInputFlags(bool forceTrace)
+{
+    const DWORD mode = inputConsoleMode();
+    const bool newFlagEE = (mode & ENABLE_EXTENDED_FLAGS) != 0;
+    const bool newFlagMI = (mode & ENABLE_MOUSE_INPUT) != 0;
+    const bool newFlagQE = (mode & ENABLE_QUICK_EDIT_MODE) != 0;
+    const bool newFlagEI = (mode & 0x200) != 0;
+    if (forceTrace ||
+            newFlagEE != m_enableExtendedEnabled ||
+            newFlagMI != m_mouseInputEnabled ||
+            newFlagQE != m_quickEditEnabled ||
+            newFlagEI != m_escapeInputEnabled) {
+        trace("CONIN modes: Extended=%s, MouseInput=%s QuickEdit=%s EscapeInput=%s",
+            newFlagEE ? "on" : "off",
+            newFlagMI ? "on" : "off",
+            newFlagQE ? "on" : "off",
+            newFlagEI ? "on" : "off");
+    }
+    m_enableExtendedEnabled = newFlagEE;
+    m_mouseInputEnabled = newFlagMI;
+    m_quickEditEnabled = newFlagQE;
+    m_escapeInputEnabled = newFlagEI;
+}
+
+bool ConsoleInput::shouldActivateTerminalMouse()
+{
+    // Return whether the agent should activate the terminal's mouse mode.
+    if (m_mouseMode == WINPTY_MOUSE_MODE_AUTO) {
+        // Some programs (e.g. Cygwin command-line programs like bash.exe and
+        // python2.7.exe) turn off ENABLE_EXTENDED_FLAGS and turn on
+        // ENABLE_MOUSE_INPUT, but do not turn off QuickEdit mode and do not
+        // actually care about mouse input.  Only enable the terminal mouse
+        // mode if ENABLE_EXTENDED_FLAGS is on.  See
+        // misc/EnableExtendedFlags.txt.
+        return m_mouseInputEnabled && !m_quickEditEnabled &&
+                m_enableExtendedEnabled;
+    } else if (m_mouseMode == WINPTY_MOUSE_MODE_FORCE) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+void ConsoleInput::doWrite(bool isEof)
+{
+    const char *data = m_byteQueue.c_str();
+    std::vector<INPUT_RECORD> records;
+    size_t idx = 0;
+    while (idx < m_byteQueue.size()) {
+        int charSize = scanInput(records, &data[idx], m_byteQueue.size() - idx, isEof);
+        if (charSize == -1)
+            break;
+        idx += charSize;
+    }
+    m_byteQueue.erase(0, idx);
+    flushInputRecords(records);
+}
+
+void ConsoleInput::flushInputRecords(std::vector<INPUT_RECORD> &records)
+{
+    if (records.size() == 0) {
+        return;
+    }
+    DWORD actual = 0;
+    if (!WriteConsoleInputW(m_conin, records.data(), records.size(), &actual)) {
+        trace("WriteConsoleInputW failed");
+    }
+    records.clear();
+}
+
+// This behavior isn't strictly correct, because the keypresses (probably?)
+// adopt the keyboard state (e.g. Ctrl/Alt/Shift modifiers) of the current
+// window station's keyboard, which has no necessary relationship to the winpty
+// instance.  It's unlikely to be an issue in practice, but it's conceivable.
+// (Imagine a foreground SSH server, where the local user holds down Ctrl,
+// while the remote user tries to use WSL navigation keys.)  I suspect using
+// the BackgroundDesktop mechanism in winpty would fix the problem.
+//
+// https://github.com/rprichard/winpty/issues/116
+static void sendKeyMessage(HWND hwnd, bool isKeyDown, uint16_t virtualKey)
+{
+    uint32_t scanCode = MapVirtualKey(virtualKey, MAPVK_VK_TO_VSC);
+    if (scanCode > 255) {
+        scanCode = 0;
+    }
+    SendMessage(hwnd, isKeyDown ? WM_KEYDOWN : WM_KEYUP, virtualKey,
+        (scanCode << 16) | 1u | (isKeyDown ? 0u : 0xc0000000u));
+}
+
+int ConsoleInput::scanInput(std::vector<INPUT_RECORD> &records,
+                            const char *input,
+                            int inputSize,
+                            bool isEof)
+{
+    ASSERT(inputSize >= 1);
+
+    // Ctrl-C.
+    //
+    // In processed mode, use GenerateConsoleCtrlEvent so that Ctrl-C handlers
+    // are called.  GenerateConsoleCtrlEvent unfortunately doesn't interrupt
+    // ReadConsole calls[1].  Using WM_KEYDOWN/UP fixes the ReadConsole
+    // problem, but breaks in background window stations/desktops.
+    //
+    // In unprocessed mode, there's an entry for Ctrl-C in the SimpleEncoding
+    // table in DefaultInputMap.
+    //
+    // [1] https://github.com/rprichard/winpty/issues/116
+    if (input[0] == '\x03' && (inputConsoleMode() & ENABLE_PROCESSED_INPUT)) {
+        flushInputRecords(records);
+        trace("Ctrl-C");
+        const BOOL ret = GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
+        trace("GenerateConsoleCtrlEvent: %d", ret);
+        return 1;
+    }
+
+    if (input[0] == '\x1B') {
+        // Attempt to match the Device Status Report (DSR) reply.
+        int dsrLen = matchDsr(input, inputSize);
+        if (dsrLen > 0) {
+            trace("Received a DSR reply");
+            m_dsrSent = false;
+            return dsrLen;
+        } else if (!isEof && dsrLen == -1) {
+            // Incomplete DSR match.
+            trace("Incomplete DSR match");
+            return -1;
+        }
+
+        int mouseLen = scanMouseInput(records, input, inputSize);
+        if (mouseLen > 0 || (!isEof && mouseLen == -1)) {
+            return mouseLen;
+        }
+    }
+
+    // Search the input map.
+    InputMap::Key match;
+    bool incomplete;
+    int matchLen = m_inputMap.lookupKey(input, inputSize, match, incomplete);
+    if (!isEof && incomplete) {
+        // Incomplete match -- need more characters (or wait for a
+        // timeout to signify flushed input).
+        trace("Incomplete escape sequence");
+        return -1;
+    } else if (matchLen > 0) {
+        uint32_t winCodePointDn = match.unicodeChar;
+        if ((match.keyState & LEFT_CTRL_PRESSED) && (match.keyState & LEFT_ALT_PRESSED)) {
+            winCodePointDn = '\0';
+        }
+        uint32_t winCodePointUp = winCodePointDn;
+        if (match.keyState & LEFT_ALT_PRESSED) {
+            winCodePointUp = '\0';
+        }
+        appendKeyPress(records, match.virtualKey,
+                       winCodePointDn, winCodePointUp, match.keyState,
+                       match.unicodeChar, match.keyState);
+        return matchLen;
+    }
+
+    // Recognize Alt-<character>.
+    //
+    // This code doesn't match Alt-ESC, which is encoded as `ESC ESC`, but
+    // maybe it should.  I was concerned that pressing ESC rapidly enough could
+    // accidentally trigger Alt-ESC.  (e.g. The user would have to be faster
+    // than the DSR flushing mechanism or use a decrepit terminal.  The user
+    // might be on a slow network connection.)
+    if (input[0] == '\x1B' && inputSize >= 2 && input[1] != '\x1B') {
+        const int len = utf8CharLength(input[1]);
+        if (len > 0) {
+            if (1 + len > inputSize) {
+                // Incomplete character.
+                trace("Incomplete UTF-8 character in Alt-<Char>");
+                return -1;
+            }
+            appendUtf8Char(records, &input[1], len, true);
+            return 1 + len;
+        }
+    }
+
+    // A UTF-8 character.
+    const int len = utf8CharLength(input[0]);
+    if (len == 0) {
+        static bool debugInput = isTracingEnabled() && hasDebugFlag("input");
+        if (debugInput) {
+            trace("Discarding invalid input byte: %02X",
+                static_cast<unsigned char>(input[0]));
+        }
+        return 1;
+    }
+    if (len > inputSize) {
+        // Incomplete character.
+        trace("Incomplete UTF-8 character");
+        return -1;
+    }
+    appendUtf8Char(records, &input[0], len, false);
+    return len;
+}
+
+int ConsoleInput::scanMouseInput(std::vector<INPUT_RECORD> &records,
+                                 const char *input,
+                                 int inputSize)
+{
+    MouseRecord record;
+    const int len = matchMouseRecord(input, inputSize, record);
+    if (len <= 0) {
+        return len;
+    }
+
+    if (isTracingEnabled()) {
+        static bool debugInput = hasDebugFlag("input");
+        if (debugInput) {
+            trace("mouse input: %s", record.toString().c_str());
+        }
+    }
+
+    const int button = record.flags & 0x03;
+    INPUT_RECORD newRecord = {0};
+    newRecord.EventType = MOUSE_EVENT;
+    MOUSE_EVENT_RECORD &mer = newRecord.Event.MouseEvent;
+
+    mer.dwMousePosition.X =
+        m_mouseWindowRect.Left +
+            std::max(0, std::min<int>(record.coord.X,
+                                      m_mouseWindowRect.width() - 1));
+
+    mer.dwMousePosition.Y =
+        m_mouseWindowRect.Top +
+            std::max(0, std::min<int>(record.coord.Y,
+                                      m_mouseWindowRect.height() - 1));
+
+    // The modifier state is neatly independent of everything else.
+    if (record.flags & 0x04) { mer.dwControlKeyState |= SHIFT_PRESSED;     }
+    if (record.flags & 0x08) { mer.dwControlKeyState |= LEFT_ALT_PRESSED;  }
+    if (record.flags & 0x10) { mer.dwControlKeyState |= LEFT_CTRL_PRESSED; }
+
+    if (record.flags & 0x40) {
+        // Mouse wheel
+        mer.dwEventFlags |= MOUSE_WHEELED;
+        if (button == 0) {
+            // up
+            mer.dwButtonState |= 0x00780000;
+        } else if (button == 1) {
+            // down
+            mer.dwButtonState |= 0xff880000;
+        } else {
+            // Invalid -- do nothing
+            return len;
+        }
+    } else {
+        // Ordinary mouse event
+        if (record.flags & 0x20) { mer.dwEventFlags |= MOUSE_MOVED; }
+        if (button == 3) {
+            m_mouseButtonState = 0;
+            // Potentially advance double-click detection.
+            m_doubleClick.released = true;
+        } else {
+            const DWORD relevantFlag =
+                (button == 0) ? FROM_LEFT_1ST_BUTTON_PRESSED :
+                (button == 1) ? FROM_LEFT_2ND_BUTTON_PRESSED :
+                (button == 2) ? RIGHTMOST_BUTTON_PRESSED :
+                0;
+            ASSERT(relevantFlag != 0);
+            if (record.release) {
+                m_mouseButtonState &= ~relevantFlag;
+                if (relevantFlag == m_doubleClick.button) {
+                    // Potentially advance double-click detection.
+                    m_doubleClick.released = true;
+                } else {
+                    // End double-click detection.
+                    m_doubleClick = DoubleClickDetection();
+                }
+            } else if ((m_mouseButtonState & relevantFlag) == 0) {
+                // The button has been newly pressed.
+                m_mouseButtonState |= relevantFlag;
+                // Detect a double-click.  This code looks for an exact
+                // coordinate match, which is stricter than what Windows does,
+                // but Windows has pixel coordinates, and we only have terminal
+                // coordinates.
+                if (m_doubleClick.button == relevantFlag &&
+                        m_doubleClick.pos == record.coord &&
+                        (GetTickCount() - m_doubleClick.tick <
+                            GetDoubleClickTime())) {
+                    // Record a double-click and end double-click detection.
+                    mer.dwEventFlags |= DOUBLE_CLICK;
+                    m_doubleClick = DoubleClickDetection();
+                } else {
+                    // Begin double-click detection.
+                    m_doubleClick.button = relevantFlag;
+                    m_doubleClick.pos = record.coord;
+                    m_doubleClick.tick = GetTickCount();
+                }
+            }
+        }
+    }
+
+    mer.dwButtonState |= m_mouseButtonState;
+
+    if (m_mouseInputEnabled && !m_quickEditEnabled) {
+        if (isTracingEnabled()) {
+            static bool debugInput = hasDebugFlag("input");
+            if (debugInput) {
+                trace("mouse event: %s", mouseEventToString(mer).c_str());
+            }
+        }
+
+        records.push_back(newRecord);
+    }
+
+    return len;
+}
+
+void ConsoleInput::appendUtf8Char(std::vector<INPUT_RECORD> &records,
+                                  const char *charBuffer,
+                                  const int charLen,
+                                  const bool terminalAltEscape)
+{
+    const uint32_t codePoint = decodeUtf8(charBuffer);
+    if (codePoint == static_cast<uint32_t>(-1)) {
+        static bool debugInput = isTracingEnabled() && hasDebugFlag("input");
+        if (debugInput) {
+            StringBuilder error(64);
+            error << "Discarding invalid UTF-8 sequence:";
+            for (int i = 0; i < charLen; ++i) {
+                error << ' ';
+                error << hexOfInt<true, uint8_t>(charBuffer[i]);
+            }
+            trace("%s", error.c_str());
+        }
+        return;
+    }
+
+    const short charScan = codePoint > 0xFFFF ? -1 : VkKeyScan(codePoint);
+    uint16_t virtualKey = 0;
+    uint16_t winKeyState = 0;
+    uint32_t winCodePointDn = codePoint;
+    uint32_t winCodePointUp = codePoint;
+    uint16_t vtKeyState = 0;
+
+    if (charScan != -1) {
+        virtualKey = charScan & 0xFF;
+        if (charScan & 0x100) {
+            winKeyState |= SHIFT_PRESSED;
+        }
+        if (charScan & 0x200) {
+            winKeyState |= LEFT_CTRL_PRESSED;
+        }
+        if (charScan & 0x400) {
+            winKeyState |= RIGHT_ALT_PRESSED;
+        }
+        if (terminalAltEscape && (winKeyState & LEFT_CTRL_PRESSED)) {
+            // If the terminal escapes a Ctrl-<Key> with Alt, then set the
+            // codepoint to 0.  On the other hand, if a character requires
+            // AltGr (like U+00B2 on a German layout), then VkKeyScan will
+            // report both Ctrl and Alt pressed, and we should keep the
+            // codepoint.  See https://github.com/rprichard/winpty/issues/109.
+            winCodePointDn = 0;
+            winCodePointUp = 0;
+        }
+    }
+    if (terminalAltEscape) {
+        winCodePointUp = 0;
+        winKeyState |= LEFT_ALT_PRESSED;
+        vtKeyState |= LEFT_ALT_PRESSED;
+    }
+
+    appendKeyPress(records, virtualKey,
+                   winCodePointDn, winCodePointUp, winKeyState,
+                   codePoint, vtKeyState);
+}
+
+void ConsoleInput::appendKeyPress(std::vector<INPUT_RECORD> &records,
+                                  const uint16_t virtualKey,
+                                  const uint32_t winCodePointDn,
+                                  const uint32_t winCodePointUp,
+                                  const uint16_t winKeyState,
+                                  const uint32_t vtCodePoint,
+                                  const uint16_t vtKeyState)
+{
+    const bool ctrl = (winKeyState & LEFT_CTRL_PRESSED) != 0;
+    const bool leftAlt = (winKeyState & LEFT_ALT_PRESSED) != 0;
+    const bool rightAlt = (winKeyState & RIGHT_ALT_PRESSED) != 0;
+    const bool shift = (winKeyState & SHIFT_PRESSED) != 0;
+    const bool enhanced = (winKeyState & ENHANCED_KEY) != 0;
+    bool hasDebugInput = false;
+
+    if (isTracingEnabled()) {
+        static bool debugInput = hasDebugFlag("input");
+        if (debugInput) {
+            hasDebugInput = true;
+            InputMap::Key key = { virtualKey, winCodePointDn, winKeyState };
+            trace("keypress: %s", key.toString().c_str());
+        }
+    }
+
+    if (m_escapeInputEnabled &&
+            (virtualKey == VK_UP ||
+                virtualKey == VK_DOWN ||
+                virtualKey == VK_LEFT ||
+                virtualKey == VK_RIGHT ||
+                virtualKey == VK_HOME ||
+                virtualKey == VK_END) &&
+            !ctrl && !leftAlt && !rightAlt && !shift) {
+        flushInputRecords(records);
+        if (hasDebugInput) {
+            trace("sending keypress to console HWND");
+        }
+        sendKeyMessage(m_console.hwnd(), true, virtualKey);
+        sendKeyMessage(m_console.hwnd(), false, virtualKey);
+        return;
+    }
+
+    uint16_t stepKeyState = 0;
+    if (ctrl) {
+        stepKeyState |= LEFT_CTRL_PRESSED;
+        appendInputRecord(records, TRUE, VK_CONTROL, 0, stepKeyState);
+    }
+    if (leftAlt) {
+        stepKeyState |= LEFT_ALT_PRESSED;
+        appendInputRecord(records, TRUE, VK_MENU, 0, stepKeyState);
+    }
+    if (rightAlt) {
+        stepKeyState |= RIGHT_ALT_PRESSED;
+        appendInputRecord(records, TRUE, VK_MENU, 0, stepKeyState | ENHANCED_KEY);
+    }
+    if (shift) {
+        stepKeyState |= SHIFT_PRESSED;
+        appendInputRecord(records, TRUE, VK_SHIFT, 0, stepKeyState);
+    }
+    if (enhanced) {
+        stepKeyState |= ENHANCED_KEY;
+    }
+    if (m_escapeInputEnabled) {
+        reencodeEscapedKeyPress(records, virtualKey, vtCodePoint, vtKeyState);
+    } else {
+        appendCPInputRecords(records, TRUE, virtualKey, winCodePointDn, stepKeyState);
+    }
+    appendCPInputRecords(records, FALSE, virtualKey, winCodePointUp, stepKeyState);
+    if (enhanced) {
+        stepKeyState &= ~ENHANCED_KEY;
+    }
+    if (shift) {
+        stepKeyState &= ~SHIFT_PRESSED;
+        appendInputRecord(records, FALSE, VK_SHIFT, 0, stepKeyState);
+    }
+    if (rightAlt) {
+        stepKeyState &= ~RIGHT_ALT_PRESSED;
+        appendInputRecord(records, FALSE, VK_MENU, 0, stepKeyState | ENHANCED_KEY);
+    }
+    if (leftAlt) {
+        stepKeyState &= ~LEFT_ALT_PRESSED;
+        appendInputRecord(records, FALSE, VK_MENU, 0, stepKeyState);
+    }
+    if (ctrl) {
+        stepKeyState &= ~LEFT_CTRL_PRESSED;
+        appendInputRecord(records, FALSE, VK_CONTROL, 0, stepKeyState);
+    }
+}
+
+void ConsoleInput::appendCPInputRecords(std::vector<INPUT_RECORD> &records,
+                                        BOOL keyDown,
+                                        uint16_t virtualKey,
+                                        uint32_t codePoint,
+                                        uint16_t keyState)
+{
+    // This behavior really doesn't match that of the Windows console (in
+    // normal, non-escape-mode).  Judging by the copy-and-paste behavior,
+    // Windows apparently handles everything outside of the keyboard layout by
+    // first sending a sequence of Alt+KeyPad events, then finally a key-up
+    // event whose UnicodeChar has the appropriate value.  For U+00A2 (CENT
+    // SIGN):
+    //
+    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
+    //      key: dn rpt=1 scn=79 LAlt-NUMPAD1 ch=0
+    //      key: up rpt=1 scn=79 LAlt-NUMPAD1 ch=0
+    //      key: dn rpt=1 scn=76 LAlt-NUMPAD5 ch=0
+    //      key: up rpt=1 scn=76 LAlt-NUMPAD5 ch=0
+    //      key: dn rpt=1 scn=76 LAlt-NUMPAD5 ch=0
+    //      key: up rpt=1 scn=76 LAlt-NUMPAD5 ch=0
+    //      key: up rpt=1 scn=56 MENU ch=0xa2
+    //
+    // The Alt+155 value matches the encoding of U+00A2 in CP-437.  Curiously,
+    // if I use "chcp 1252" to change the encoding, then copy-and-pasting
+    // produces Alt+162 instead.  (U+00A2 is 162 in CP-1252.)  However, typing
+    // Alt+155 or Alt+162 produce the same characters regardless of console
+    // code page.  (That is, they use CP-437 and yield U+00A2 and U+00F3.)
+    //
+    // For characters outside the BMP, Windows repeats the process for both
+    // UTF-16 code units, e.g, for U+1F300 (CYCLONE):
+    //
+    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
+    //      key: dn rpt=1 scn=77 LAlt-NUMPAD6 ch=0
+    //      key: up rpt=1 scn=77 LAlt-NUMPAD6 ch=0
+    //      key: dn rpt=1 scn=81 LAlt-NUMPAD3 ch=0
+    //      key: up rpt=1 scn=81 LAlt-NUMPAD3 ch=0
+    //      key: up rpt=1 scn=56 MENU ch=0xd83c
+    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
+    //      key: dn rpt=1 scn=77 LAlt-NUMPAD6 ch=0
+    //      key: up rpt=1 scn=77 LAlt-NUMPAD6 ch=0
+    //      key: dn rpt=1 scn=81 LAlt-NUMPAD3 ch=0
+    //      key: up rpt=1 scn=81 LAlt-NUMPAD3 ch=0
+    //      key: up rpt=1 scn=56 MENU ch=0xdf00
+    //
+    // In this case, it sends Alt+63 twice, which signifies '?'.  Apparently
+    // CMD and Cygwin bash are both able to decode this.
+    //
+    // Also note that typing Alt+NNN still works if NumLock is off, e.g.:
+    //
+    //      key: dn rpt=1 scn=56 LAlt-MENU ch=0
+    //      key: dn rpt=1 scn=79 LAlt-END ch=0
+    //      key: up rpt=1 scn=79 LAlt-END ch=0
+    //      key: dn rpt=1 scn=76 LAlt-CLEAR ch=0
+    //      key: up rpt=1 scn=76 LAlt-CLEAR ch=0
+    //      key: dn rpt=1 scn=76 LAlt-CLEAR ch=0
+    //      key: up rpt=1 scn=76 LAlt-CLEAR ch=0
+    //      key: up rpt=1 scn=56 MENU ch=0xa2
+    //
+    // Evidently, the Alt+NNN key events are not intended to be decoded to a
+    // character.  Maybe programs are looking for a key-up ALT/MENU event with
+    // a non-zero character?
+
+    wchar_t ws[2];
+    const int wslen = encodeUtf16(ws, codePoint);
+
+    if (wslen == 1) {
+        appendInputRecord(records, keyDown, virtualKey, ws[0], keyState);
+    } else if (wslen == 2) {
+        appendInputRecord(records, keyDown, virtualKey, ws[0], keyState);
+        appendInputRecord(records, keyDown, virtualKey, ws[1], keyState);
+    } else {
+        // This situation isn't that bad, but it should never happen,
+        // because invalid codepoints shouldn't reach this point.
+        trace("INTERNAL ERROR: appendInputRecordCP: invalid codePoint: "
+              "U+%04X", codePoint);
+    }
+}
+
+void ConsoleInput::appendInputRecord(std::vector<INPUT_RECORD> &records,
+                                     BOOL keyDown,
+                                     uint16_t virtualKey,
+                                     wchar_t utf16Char,
+                                     uint16_t keyState)
+{
+    INPUT_RECORD ir = {};
+    ir.EventType = KEY_EVENT;
+    ir.Event.KeyEvent.bKeyDown = keyDown;
+    ir.Event.KeyEvent.wRepeatCount = 1;
+    ir.Event.KeyEvent.wVirtualKeyCode = virtualKey;
+    ir.Event.KeyEvent.wVirtualScanCode =
+            MapVirtualKey(virtualKey, MAPVK_VK_TO_VSC);
+    ir.Event.KeyEvent.uChar.UnicodeChar = utf16Char;
+    ir.Event.KeyEvent.dwControlKeyState = keyState;
+    records.push_back(ir);
+}
+
+DWORD ConsoleInput::inputConsoleMode()
+{
+    DWORD mode = 0;
+    if (!GetConsoleMode(m_conin, &mode)) {
+        trace("GetConsoleMode failed");
+        return 0;
+    }
+    return mode;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.h b/node_modules/node-pty/deps/winpty/src/agent/ConsoleInput.h
new file mode 100644 (file)
index 0000000..e807d97
--- /dev/null
@@ -0,0 +1,109 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#ifndef CONSOLEINPUT_H
+#define CONSOLEINPUT_H
+
+#include <windows.h>
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "Coord.h"
+#include "InputMap.h"
+#include "SmallRect.h"
+
+class Win32Console;
+class DsrSender;
+
+class ConsoleInput
+{
+public:
+    ConsoleInput(HANDLE conin, int mouseMode, DsrSender &dsrSender,
+                 Win32Console &console);
+    void writeInput(const std::string &input);
+    void flushIncompleteEscapeCode();
+    void setMouseWindowRect(SmallRect val) { m_mouseWindowRect = val; }
+    void updateInputFlags(bool forceTrace=false);
+    bool shouldActivateTerminalMouse();
+
+private:
+    void doWrite(bool isEof);
+    void flushInputRecords(std::vector<INPUT_RECORD> &records);
+    int scanInput(std::vector<INPUT_RECORD> &records,
+                  const char *input,
+                  int inputSize,
+                  bool isEof);
+    int scanMouseInput(std::vector<INPUT_RECORD> &records,
+                       const char *input,
+                       int inputSize);
+    void appendUtf8Char(std::vector<INPUT_RECORD> &records,
+                        const char *charBuffer,
+                        int charLen,
+                        bool terminalAltEscape);
+    void appendKeyPress(std::vector<INPUT_RECORD> &records,
+                        uint16_t virtualKey,
+                        uint32_t winCodePointDn,
+                        uint32_t winCodePointUp,
+                        uint16_t winKeyState,
+                        uint32_t vtCodePoint,
+                        uint16_t vtKeyState);
+
+public:
+    static void appendCPInputRecords(std::vector<INPUT_RECORD> &records,
+                                     BOOL keyDown,
+                                     uint16_t virtualKey,
+                                     uint32_t codePoint,
+                                     uint16_t keyState);
+    static void appendInputRecord(std::vector<INPUT_RECORD> &records,
+                                  BOOL keyDown,
+                                  uint16_t virtualKey,
+                                  wchar_t utf16Char,
+                                  uint16_t keyState);
+
+private:
+    DWORD inputConsoleMode();
+
+private:
+    Win32Console &m_console;
+    HANDLE m_conin = nullptr;
+    int m_mouseMode = 0;
+    DsrSender &m_dsrSender;
+    bool m_dsrSent = false;
+    std::string m_byteQueue;
+    InputMap m_inputMap;
+    DWORD m_lastWriteTick = 0;
+    DWORD m_mouseButtonState = 0;
+    struct DoubleClickDetection {
+        DWORD button = 0;
+        Coord pos;
+        DWORD tick = 0;
+        bool released = false;
+    } m_doubleClick;
+    bool m_enableExtendedEnabled = false;
+    bool m_mouseInputEnabled = false;
+    bool m_quickEditEnabled = false;
+    bool m_escapeInputEnabled = false;
+    SmallRect m_mouseWindowRect;
+};
+
+#endif // CONSOLEINPUT_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.cc b/node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.cc
new file mode 100644 (file)
index 0000000..b79545e
--- /dev/null
@@ -0,0 +1,121 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "ConsoleInputReencoding.h"
+
+#include "ConsoleInput.h"
+
+namespace {
+
+static void outch(std::vector<INPUT_RECORD> &out, wchar_t ch) {
+    ConsoleInput::appendInputRecord(out, TRUE, 0, ch, 0);
+}
+
+} // anonymous namespace
+
+void reencodeEscapedKeyPress(
+        std::vector<INPUT_RECORD> &out,
+        uint16_t virtualKey,
+        uint32_t codePoint,
+        uint16_t keyState) {
+
+    struct EscapedKey {
+        enum { None, Numeric, Letter } kind;
+        wchar_t content[2];
+    };
+
+    EscapedKey escapeCode = {};
+    switch (virtualKey) {
+        case VK_UP:     escapeCode = { EscapedKey::Letter, {'A'} }; break;
+        case VK_DOWN:   escapeCode = { EscapedKey::Letter, {'B'} }; break;
+        case VK_RIGHT:  escapeCode = { EscapedKey::Letter, {'C'} }; break;
+        case VK_LEFT:   escapeCode = { EscapedKey::Letter, {'D'} }; break;
+        case VK_CLEAR:  escapeCode = { EscapedKey::Letter, {'E'} }; break;
+        case VK_F1:     escapeCode = { EscapedKey::Numeric, {'1', '1'} }; break;
+        case VK_F2:     escapeCode = { EscapedKey::Numeric, {'1', '2'} }; break;
+        case VK_F3:     escapeCode = { EscapedKey::Numeric, {'1', '3'} }; break;
+        case VK_F4:     escapeCode = { EscapedKey::Numeric, {'1', '4'} }; break;
+        case VK_F5:     escapeCode = { EscapedKey::Numeric, {'1', '5'} }; break;
+        case VK_F6:     escapeCode = { EscapedKey::Numeric, {'1', '7'} }; break;
+        case VK_F7:     escapeCode = { EscapedKey::Numeric, {'1', '8'} }; break;
+        case VK_F8:     escapeCode = { EscapedKey::Numeric, {'1', '9'} }; break;
+        case VK_F9:     escapeCode = { EscapedKey::Numeric, {'2', '0'} }; break;
+        case VK_F10:    escapeCode = { EscapedKey::Numeric, {'2', '1'} }; break;
+        case VK_F11:    escapeCode = { EscapedKey::Numeric, {'2', '3'} }; break;
+        case VK_F12:    escapeCode = { EscapedKey::Numeric, {'2', '4'} }; break;
+        case VK_HOME:   escapeCode = { EscapedKey::Letter, {'H'} }; break;
+        case VK_INSERT: escapeCode = { EscapedKey::Numeric, {'2'} }; break;
+        case VK_DELETE: escapeCode = { EscapedKey::Numeric, {'3'} }; break;
+        case VK_END:    escapeCode = { EscapedKey::Letter, {'F'} }; break;
+        case VK_PRIOR:  escapeCode = { EscapedKey::Numeric, {'5'} }; break;
+        case VK_NEXT:   escapeCode = { EscapedKey::Numeric, {'6'} }; break;
+    }
+    if (escapeCode.kind != EscapedKey::None) {
+        int flags = 0;
+        if (keyState & SHIFT_PRESSED)       { flags |= 0x1; }
+        if (keyState & LEFT_ALT_PRESSED)    { flags |= 0x2; }
+        if (keyState & LEFT_CTRL_PRESSED)   { flags |= 0x4; }
+        outch(out, L'\x1b');
+        outch(out, L'[');
+        if (escapeCode.kind == EscapedKey::Numeric) {
+            for (wchar_t ch : escapeCode.content) {
+                if (ch != L'\0') {
+                    outch(out, ch);
+                }
+            }
+        } else if (flags != 0) {
+            outch(out, L'1');
+        }
+        if (flags != 0) {
+            outch(out, L';');
+            outch(out, L'1' + flags);
+        }
+        if (escapeCode.kind == EscapedKey::Numeric) {
+            outch(out, L'~');
+        } else {
+            outch(out, escapeCode.content[0]);
+        }
+        return;
+    }
+
+    switch (virtualKey) {
+        case VK_BACK:
+            if (keyState & LEFT_ALT_PRESSED) {
+                outch(out, L'\x1b');
+            }
+            outch(out, L'\x7f');
+            return;
+        case VK_TAB:
+            if (keyState & SHIFT_PRESSED) {
+                outch(out, L'\x1b');
+                outch(out, L'[');
+                outch(out, L'Z');
+                return;
+            }
+            break;
+    }
+
+    if (codePoint != 0) {
+        if (keyState & LEFT_ALT_PRESSED) {
+            outch(out, L'\x1b');
+        }
+        ConsoleInput::appendCPInputRecords(out, TRUE, 0, codePoint, 0);
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.h b/node_modules/node-pty/deps/winpty/src/agent/ConsoleInputReencoding.h
new file mode 100644 (file)
index 0000000..63bc006
--- /dev/null
@@ -0,0 +1,36 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_CONSOLE_INPUT_REENCODING_H
+#define AGENT_CONSOLE_INPUT_REENCODING_H
+
+#include <windows.h>
+
+#include <stdint.h>
+
+#include <vector>
+
+void reencodeEscapedKeyPress(
+    std::vector<INPUT_RECORD> &records,
+    uint16_t virtualKey,
+    uint32_t codePoint,
+    uint16_t keyState);
+
+#endif // AGENT_CONSOLE_INPUT_REENCODING_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.cc b/node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.cc
new file mode 100644 (file)
index 0000000..1d2bcb7
--- /dev/null
@@ -0,0 +1,152 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+//
+// ConsoleLine
+//
+// This data structure keep tracks of the previous CHAR_INFO content of an
+// output line and determines when a line has changed.  Detecting line changes
+// is made complicated by terminal resizing.
+//
+
+#include "ConsoleLine.h"
+
+#include <algorithm>
+
+#include "../shared/WinptyAssert.h"
+
+static CHAR_INFO blankChar(WORD attributes)
+{
+    // N.B.: As long as we write to UnicodeChar rather than AsciiChar, there
+    // are no padding bytes that could contain uninitialized bytes.  This fact
+    // is important for efficient comparison.
+    CHAR_INFO ret;
+    ret.Attributes = attributes;
+    ret.Char.UnicodeChar = L' ';
+    return ret;
+}
+
+static bool isLineBlank(const CHAR_INFO *line, int length, WORD attributes)
+{
+    for (int col = 0; col < length; ++col) {
+        if (line[col].Attributes != attributes ||
+                line[col].Char.UnicodeChar != L' ') {
+            return false;
+        }
+    }
+    return true;
+}
+
+static inline bool areLinesEqual(
+    const CHAR_INFO *line1,
+    const CHAR_INFO *line2,
+    int length)
+{
+    return memcmp(line1, line2, sizeof(CHAR_INFO) * length) == 0;
+}
+
+ConsoleLine::ConsoleLine() : m_prevLength(0)
+{
+}
+
+void ConsoleLine::reset()
+{
+    m_prevLength = 0;
+    m_prevData.clear();
+}
+
+// Determines whether the given line is sufficiently different from the
+// previously seen line as to justify reoutputting the line.  The function
+// also sets the `ConsoleLine` to the given line, exactly as if `setLine` had
+// been called.
+bool ConsoleLine::detectChangeAndSetLine(const CHAR_INFO *const line, const int newLength)
+{
+    ASSERT(newLength >= 1);
+    ASSERT(m_prevLength <= static_cast<int>(m_prevData.size()));
+
+    if (newLength == m_prevLength) {
+        bool equalLines = areLinesEqual(m_prevData.data(), line, newLength);
+        if (!equalLines) {
+            setLine(line, newLength);
+        }
+        return !equalLines;
+    } else {
+        if (m_prevLength == 0) {
+            setLine(line, newLength);
+            return true;
+        }
+
+        ASSERT(m_prevLength >= 1);
+        const WORD prevBlank = m_prevData[m_prevLength - 1].Attributes;
+        const WORD newBlank = line[newLength - 1].Attributes;
+
+        bool equalLines = false;
+        if (newLength < m_prevLength) {
+            // The line has become shorter.  The lines are equal if the common
+            // part is equal, and if the newly truncated characters were blank.
+            equalLines =
+                areLinesEqual(m_prevData.data(), line, newLength) &&
+                isLineBlank(m_prevData.data() + newLength,
+                            m_prevLength - newLength,
+                            newBlank);
+        } else {
+            //
+            // The line has become longer.  The lines are equal if the common
+            // part is equal, and if both the extra characters and any
+            // potentially reexposed characters are blank.
+            //
+            // Two of the most relevant terminals for winpty--mintty and
+            // jediterm--don't (currently) erase the obscured content when a
+            // line is cleared, so we should anticipate its existence when
+            // making a terminal wider and reoutput the line.  See:
+            //
+            //  * https://github.com/mintty/mintty/issues/480
+            //  * https://github.com/JetBrains/jediterm/issues/118
+            //
+            ASSERT(newLength > m_prevLength);
+            equalLines =
+                areLinesEqual(m_prevData.data(), line, m_prevLength) &&
+                isLineBlank(m_prevData.data() + m_prevLength,
+                            std::min<int>(m_prevData.size(), newLength) - m_prevLength,
+                            prevBlank) &&
+                isLineBlank(line + m_prevLength,
+                            newLength - m_prevLength,
+                            prevBlank);
+        }
+        setLine(line, newLength);
+        return !equalLines;
+    }
+}
+
+void ConsoleLine::setLine(const CHAR_INFO *const line, const int newLength)
+{
+    if (static_cast<int>(m_prevData.size()) < newLength) {
+        m_prevData.resize(newLength);
+    }
+    memcpy(m_prevData.data(), line, sizeof(CHAR_INFO) * newLength);
+    m_prevLength = newLength;
+}
+
+void ConsoleLine::blank(WORD attributes)
+{
+    m_prevData.resize(1);
+    m_prevData[0] = blankChar(attributes);
+    m_prevLength = 1;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.h b/node_modules/node-pty/deps/winpty/src/agent/ConsoleLine.h
new file mode 100644 (file)
index 0000000..802c189
--- /dev/null
@@ -0,0 +1,41 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef CONSOLE_LINE_H
+#define CONSOLE_LINE_H
+
+#include <windows.h>
+
+#include <vector>
+
+class ConsoleLine
+{
+public:
+    ConsoleLine();
+    void reset();
+    bool detectChangeAndSetLine(const CHAR_INFO *line, int newLength);
+    void setLine(const CHAR_INFO *line, int newLength);
+    void blank(WORD attributes);
+private:
+    int m_prevLength;
+    std::vector<CHAR_INFO> m_prevData;
+};
+
+#endif // CONSOLE_LINE_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Coord.h b/node_modules/node-pty/deps/winpty/src/agent/Coord.h
new file mode 100644 (file)
index 0000000..74c98ad
--- /dev/null
@@ -0,0 +1,87 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef COORD_H
+#define COORD_H
+
+#include <windows.h>
+
+#include <string>
+
+#include "../shared/winpty_snprintf.h"
+
+struct Coord : COORD {
+    Coord()
+    {
+        X = 0;
+        Y = 0;
+    }
+
+    Coord(SHORT x, SHORT y)
+    {
+        X = x;
+        Y = y;
+    }
+
+    Coord(COORD other)
+    {
+        *(COORD*)this = other;
+    }
+
+    Coord(const Coord &other)
+    {
+        *(COORD*)this = *(const COORD*)&other;
+    }
+
+    Coord &operator=(const Coord &other)
+    {
+        *(COORD*)this = *(const COORD*)&other;
+        return *this;
+    }
+
+    bool operator==(const Coord &other) const
+    {
+        return X == other.X && Y == other.Y;
+    }
+
+    bool operator!=(const Coord &other) const
+    {
+        return !(*this == other);
+    }
+
+    Coord operator+(const Coord &other) const
+    {
+        return Coord(X + other.X, Y + other.Y);
+    }
+
+    bool isEmpty() const
+    {
+        return X <= 0 || Y <= 0;
+    }
+
+    std::string toString() const
+    {
+        char ret[32];
+        winpty_snprintf(ret, "(%d,%d)", X, Y);
+        return std::string(ret);
+    }
+};
+
+#endif // COORD_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.cc b/node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.cc
new file mode 100644 (file)
index 0000000..191b2e1
--- /dev/null
@@ -0,0 +1,239 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "DebugShowInput.h"
+
+#include <windows.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <string>
+
+#include "../shared/StringBuilder.h"
+#include "InputMap.h"
+
+namespace {
+
+struct Flag {
+    DWORD value;
+    const char *text;
+};
+
+static const Flag kButtonStates[] = {
+    { FROM_LEFT_1ST_BUTTON_PRESSED, "1" },
+    { FROM_LEFT_2ND_BUTTON_PRESSED, "2" },
+    { FROM_LEFT_3RD_BUTTON_PRESSED, "3" },
+    { FROM_LEFT_4TH_BUTTON_PRESSED, "4" },
+    { RIGHTMOST_BUTTON_PRESSED,     "R" },
+};
+
+static const Flag kControlKeyStates[] = {
+    { CAPSLOCK_ON,          "CapsLock"      },
+    { ENHANCED_KEY,         "Enhanced"      },
+    { LEFT_ALT_PRESSED,     "LAlt"          },
+    { LEFT_CTRL_PRESSED,    "LCtrl"         },
+    { NUMLOCK_ON,           "NumLock"       },
+    { RIGHT_ALT_PRESSED,    "RAlt"          },
+    { RIGHT_CTRL_PRESSED,   "RCtrl"         },
+    { SCROLLLOCK_ON,        "ScrollLock"    },
+    { SHIFT_PRESSED,        "Shift"         },
+};
+
+static const Flag kMouseEventFlags[] = {
+    { DOUBLE_CLICK,         "Double"        },
+    { 8/*MOUSE_HWHEELED*/,  "HWheel"        },
+    { MOUSE_MOVED,          "Move"          },
+    { MOUSE_WHEELED,        "Wheel"         },
+};
+
+static void writeFlags(StringBuilder &out, DWORD flags,
+                       const char *remainderName,
+                       const Flag *table, size_t tableSize,
+                       char pre, char sep, char post) {
+    DWORD remaining = flags;
+    bool wroteSomething = false;
+    for (size_t i = 0; i < tableSize; ++i) {
+        const Flag &f = table[i];
+        if ((f.value & flags) == f.value) {
+            if (!wroteSomething && pre != '\0') {
+                out << pre;
+            } else if (wroteSomething && sep != '\0') {
+                out << sep;
+            }
+            out << f.text;
+            wroteSomething = true;
+            remaining &= ~f.value;
+        }
+    }
+    if (remaining != 0) {
+        if (!wroteSomething && pre != '\0') {
+            out << pre;
+        } else if (wroteSomething && sep != '\0') {
+            out << sep;
+        }
+        out << remainderName << "(0x" << hexOfInt(remaining) << ')';
+        wroteSomething = true;
+    }
+    if (wroteSomething && post != '\0') {
+        out << post;
+    }
+}
+
+template <size_t n>
+static void writeFlags(StringBuilder &out, DWORD flags,
+                       const char *remainderName,
+                       const Flag (&table)[n],
+                       char pre, char sep, char post) {
+    writeFlags(out, flags, remainderName, table, n, pre, sep, post);
+}
+
+} // anonymous namespace
+
+std::string controlKeyStatePrefix(DWORD controlKeyState) {
+    StringBuilder sb;
+    writeFlags(sb, controlKeyState,
+               "keyState", kControlKeyStates, '\0', '-', '-');
+    return sb.str_moved();
+}
+
+std::string mouseEventToString(const MOUSE_EVENT_RECORD &mer) {
+    const uint16_t buttons = mer.dwButtonState & 0xFFFF;
+    const int16_t wheel = mer.dwButtonState >> 16;
+    StringBuilder sb;
+    sb << "pos=" << mer.dwMousePosition.X << ','
+                 << mer.dwMousePosition.Y;
+    writeFlags(sb, mer.dwControlKeyState, "keyState", kControlKeyStates, ' ', ' ', '\0');
+    writeFlags(sb, mer.dwEventFlags, "flags", kMouseEventFlags, ' ', ' ', '\0');
+    writeFlags(sb, buttons, "buttons", kButtonStates, ' ', ' ', '\0');
+    if (wheel != 0) {
+        sb << " wheel=" << wheel;
+    }
+    return sb.str_moved();
+}
+
+void debugShowInput(bool enableMouse, bool escapeInput) {
+    HANDLE conin = GetStdHandle(STD_INPUT_HANDLE);
+    DWORD origConsoleMode = 0;
+    if (!GetConsoleMode(conin, &origConsoleMode)) {
+        fprintf(stderr, "Error: could not read console mode -- "
+                        "is STDIN a console handle?\n");
+        exit(1);
+    }
+    DWORD restoreConsoleMode = origConsoleMode;
+    if (enableMouse && !(restoreConsoleMode & ENABLE_EXTENDED_FLAGS)) {
+        // We need to disable QuickEdit mode, because it blocks mouse events.
+        // If ENABLE_EXTENDED_FLAGS wasn't originally in the console mode, then
+        // we have no way of knowning whether QuickEdit or InsertMode are
+        // currently enabled.  Enable them both (eventually), because they're
+        // sensible defaults.  This case shouldn't happen typically.  See
+        // misc/EnableExtendedFlags.txt.
+        restoreConsoleMode |= ENABLE_EXTENDED_FLAGS;
+        restoreConsoleMode |= ENABLE_QUICK_EDIT_MODE;
+        restoreConsoleMode |= ENABLE_INSERT_MODE;
+    }
+    DWORD newConsoleMode = restoreConsoleMode;
+    newConsoleMode &= ~ENABLE_PROCESSED_INPUT;
+    newConsoleMode &= ~ENABLE_LINE_INPUT;
+    newConsoleMode &= ~ENABLE_ECHO_INPUT;
+    newConsoleMode |= ENABLE_WINDOW_INPUT;
+    if (enableMouse) {
+        newConsoleMode |= ENABLE_MOUSE_INPUT;
+        newConsoleMode &= ~ENABLE_QUICK_EDIT_MODE;
+    } else {
+        newConsoleMode &= ~ENABLE_MOUSE_INPUT;
+    }
+    if (escapeInput) {
+        // As of this writing (2016-06-05), Microsoft has shipped two preview
+        // builds of Windows 10 (14316 and 14342) that include a new "Windows
+        // Subsystem for Linux" that runs Ubuntu in a new subsystem.  Running
+        // bash in this subsystem requires the non-legacy console mode, and the
+        // console input buffer is put into a special mode where escape
+        // sequences are written into the console input buffer.  This mode is
+        // enabled with the 0x200 flag, which is as-yet undocumented.
+        // See https://github.com/rprichard/winpty/issues/82.
+        newConsoleMode |= 0x200;
+    }
+    if (!SetConsoleMode(conin, newConsoleMode)) {
+        fprintf(stderr, "Error: could not set console mode "
+            "(0x%x -> 0x%x -> 0x%x)\n",
+            static_cast<unsigned int>(origConsoleMode),
+            static_cast<unsigned int>(newConsoleMode),
+            static_cast<unsigned int>(restoreConsoleMode));
+        exit(1);
+    }
+    printf("\nPress any keys -- Ctrl-D exits\n\n");
+    INPUT_RECORD records[32];
+    DWORD actual = 0;
+    bool finished = false;
+    while (!finished &&
+            ReadConsoleInputW(conin, records, 32, &actual) && actual >= 1) {
+        StringBuilder sb;
+        for (DWORD i = 0; i < actual; ++i) {
+            const INPUT_RECORD &record = records[i];
+            if (record.EventType == KEY_EVENT) {
+                const KEY_EVENT_RECORD &ker = record.Event.KeyEvent;
+                InputMap::Key key = {
+                    ker.wVirtualKeyCode,
+                    ker.uChar.UnicodeChar,
+                    static_cast<uint16_t>(ker.dwControlKeyState),
+                };
+                sb << "key: " << (ker.bKeyDown ? "dn" : "up")
+                   << " rpt=" << ker.wRepeatCount
+                   << " scn=" << (ker.wVirtualScanCode ? "0x" : "") << hexOfInt(ker.wVirtualScanCode)
+                   << ' ' << key.toString() << '\n';
+                if ((ker.dwControlKeyState &
+                        (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) &&
+                        ker.wVirtualKeyCode == 'D') {
+                    finished = true;
+                    break;
+                } else if (ker.wVirtualKeyCode == 0 &&
+                        ker.wVirtualScanCode == 0 &&
+                        ker.uChar.UnicodeChar == 4) {
+                    // Also look for a zeroed-out Ctrl-D record generated for
+                    // ENABLE_VIRTUAL_TERMINAL_INPUT.
+                    finished = true;
+                    break;
+                }
+            } else if (record.EventType == MOUSE_EVENT) {
+                const MOUSE_EVENT_RECORD &mer = record.Event.MouseEvent;
+                sb << "mouse: " << mouseEventToString(mer) << '\n';
+            } else if (record.EventType == WINDOW_BUFFER_SIZE_EVENT) {
+                const WINDOW_BUFFER_SIZE_RECORD &wbsr =
+                    record.Event.WindowBufferSizeEvent;
+                sb << "buffer-resized: dwSize=("
+                   << wbsr.dwSize.X << ','
+                   << wbsr.dwSize.Y << ")\n";
+            } else if (record.EventType == MENU_EVENT) {
+                const MENU_EVENT_RECORD &mer = record.Event.MenuEvent;
+                sb << "menu-event: commandId=0x"
+                   << hexOfInt(mer.dwCommandId) << '\n';
+            } else if (record.EventType == FOCUS_EVENT) {
+                const FOCUS_EVENT_RECORD &fer = record.Event.FocusEvent;
+                sb << "focus: " << (fer.bSetFocus ? "gained" : "lost") << '\n';
+            }
+        }
+
+        const auto str = sb.str_moved();
+        fwrite(str.data(), 1, str.size(), stdout);
+        fflush(stdout);
+    }
+    SetConsoleMode(conin, restoreConsoleMode);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.h b/node_modules/node-pty/deps/winpty/src/agent/DebugShowInput.h
new file mode 100644 (file)
index 0000000..4fa1360
--- /dev/null
@@ -0,0 +1,32 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_DEBUG_SHOW_INPUT_H
+#define AGENT_DEBUG_SHOW_INPUT_H
+
+#include <windows.h>
+
+#include <string>
+
+std::string controlKeyStatePrefix(DWORD controlKeyState);
+std::string mouseEventToString(const MOUSE_EVENT_RECORD &mer);
+void debugShowInput(bool enableMouse, bool escapeInput);
+
+#endif // AGENT_DEBUG_SHOW_INPUT_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.cc b/node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.cc
new file mode 100644 (file)
index 0000000..5e29d98
--- /dev/null
@@ -0,0 +1,422 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "DefaultInputMap.h"
+
+#include <windows.h>
+#include <string.h>
+
+#include <algorithm>
+
+#include "../shared/StringBuilder.h"
+#include "../shared/WinptyAssert.h"
+#include "InputMap.h"
+
+#define ESC "\x1B"
+#define DIM(x) (sizeof(x) / sizeof((x)[0]))
+
+namespace {
+
+struct EscapeEncoding {
+    bool alt_prefix_allowed;
+    char prefix;
+    char id;
+    int modifiers;
+    InputMap::Key key;
+};
+
+// Modifiers.  A "modifier" is an integer from 2 to 8 that conveys the status
+// of Shift(1), Alt(2), and Ctrl(4).  The value is constructed by OR'ing the
+// appropriate value for each active modifier, then adding 1.
+//
+// Details:
+//  - kBare:    expands to: ESC <prefix> <suffix>
+//  - kSemiMod: expands to: ESC <prefix> <numid> ; <mod> <suffix>
+//  - kBareMod: expands to: ESC <prefix> <mod> <suffix>
+const int kBare        = 0x01;
+const int kSemiMod     = 0x02;
+const int kBareMod     = 0x04;
+
+// Numeric escape sequences suffixes:
+//  - with no flag: accept: ~
+//  - kSuffixCtrl:  accept: ~ ^
+//  - kSuffixShift: accept: ~ $
+//  - kSuffixBoth:  accept: ~ ^ $ @
+const int kSuffixCtrl  = 0x08;
+const int kSuffixShift = 0x10;
+const int kSuffixBoth  = kSuffixCtrl | kSuffixShift;
+
+static const EscapeEncoding escapeLetterEncodings[] = {
+    // Conventional arrow keys
+    // kBareMod: Ubuntu /etc/inputrc and IntelliJ/JediTerm use escapes like: ESC [ n ABCD
+    { true,  '[', 'A', kBare | kBareMod | kSemiMod, { VK_UP,      '\0', 0             } },
+    { true,  '[', 'B', kBare | kBareMod | kSemiMod, { VK_DOWN,    '\0', 0             } },
+    { true,  '[', 'C', kBare | kBareMod | kSemiMod, { VK_RIGHT,   '\0', 0             } },
+    { true,  '[', 'D', kBare | kBareMod | kSemiMod, { VK_LEFT,    '\0', 0             } },
+
+    // putty.  putty uses this sequence for Ctrl-Arrow, Shift-Arrow, and
+    // Ctrl-Shift-Arrow, but I can only decode to one choice, so I'm just
+    // leaving the modifier off altogether.
+    { true,  'O', 'A', kBare,                       { VK_UP,      '\0', 0             } },
+    { true,  'O', 'B', kBare,                       { VK_DOWN,    '\0', 0             } },
+    { true,  'O', 'C', kBare,                       { VK_RIGHT,   '\0', 0             } },
+    { true,  'O', 'D', kBare,                       { VK_LEFT,    '\0', 0             } },
+
+    // rxvt, rxvt-unicode
+    // Shift-Ctrl-Arrow can't be identified.  It's the same as Shift-Arrow.
+    { true,  '[', 'a', kBare,                       { VK_UP,      '\0', SHIFT_PRESSED       } },
+    { true,  '[', 'b', kBare,                       { VK_DOWN,    '\0', SHIFT_PRESSED       } },
+    { true,  '[', 'c', kBare,                       { VK_RIGHT,   '\0', SHIFT_PRESSED       } },
+    { true,  '[', 'd', kBare,                       { VK_LEFT,    '\0', SHIFT_PRESSED       } },
+    { true,  'O', 'a', kBare,                       { VK_UP,      '\0', LEFT_CTRL_PRESSED   } },
+    { true,  'O', 'b', kBare,                       { VK_DOWN,    '\0', LEFT_CTRL_PRESSED   } },
+    { true,  'O', 'c', kBare,                       { VK_RIGHT,   '\0', LEFT_CTRL_PRESSED   } },
+    { true,  'O', 'd', kBare,                       { VK_LEFT,    '\0', LEFT_CTRL_PRESSED   } },
+
+    // Numpad 5 with NumLock off
+    //  * xterm, mintty, and gnome-terminal use `ESC [ E`.
+    //  * putty, TERM=cygwin, TERM=linux all use `ESC [ G` for 5
+    //  * putty uses `ESC O G` for Ctrl-5 and Shift-5.  Omit the modifier
+    //    as with putty's arrow keys.
+    //  * I never saw modifiers inserted into these escapes, but I think
+    //    it should be completely OK with the CSI escapes.
+    { true,  '[', 'E', kBare | kSemiMod,            { VK_CLEAR,   '\0', 0             } },
+    { true,  '[', 'G', kBare | kSemiMod,            { VK_CLEAR,   '\0', 0             } },
+    { true,  'O', 'G', kBare,                       { VK_CLEAR,   '\0', 0             } },
+
+    // Home/End, letter version
+    //  * gnome-terminal uses `ESC O [HF]`.  I never saw it modified.
+    // kBareMod: IntelliJ/JediTerm uses escapes like: ESC [ n HF
+    { true,  '[', 'H', kBare | kBareMod | kSemiMod, { VK_HOME,    '\0', 0             } },
+    { true,  '[', 'F', kBare | kBareMod | kSemiMod, { VK_END,     '\0', 0             } },
+    { true,  'O', 'H', kBare,                       { VK_HOME,    '\0', 0             } },
+    { true,  'O', 'F', kBare,                       { VK_END,     '\0', 0             } },
+
+    // F1-F4, letter version (xterm, VTE, konsole)
+    { true,  '[', 'P', kSemiMod,                    { VK_F1,      '\0', 0             } },
+    { true,  '[', 'Q', kSemiMod,                    { VK_F2,      '\0', 0             } },
+    { true,  '[', 'R', kSemiMod,                    { VK_F3,      '\0', 0             } },
+    { true,  '[', 'S', kSemiMod,                    { VK_F4,      '\0', 0             } },
+
+    // GNOME VTE and Konsole have special encodings for modified F1-F4:
+    //  * [VTE]     ESC O 1 ; n [PQRS]
+    //  * [Konsole] ESC O     n [PQRS]
+    { false, 'O', 'P', kBare | kBareMod | kSemiMod, { VK_F1,      '\0', 0             } },
+    { false, 'O', 'Q', kBare | kBareMod | kSemiMod, { VK_F2,      '\0', 0             } },
+    { false, 'O', 'R', kBare | kBareMod | kSemiMod, { VK_F3,      '\0', 0             } },
+    { false, 'O', 'S', kBare | kBareMod | kSemiMod, { VK_F4,      '\0', 0             } },
+
+    // Handle the "application numpad" escape sequences.
+    //
+    // Terminals output these codes under various circumstances:
+    //  * rxvt-unicode: numpad, hold down SHIFT
+    //  * rxvt: numpad, by default
+    //  * xterm: numpad, after enabling app-mode using DECPAM (`ESC =`).  xterm
+    //    generates `ESC O <mod> <letter>` for modified numpad presses,
+    //    necessitating kBareMod.
+    //  * mintty: by combining Ctrl with various keys such as '1' or ','.
+    //    Handling those keys is difficult, because mintty is generating the
+    //    same sequence for Ctrl-1 and Ctrl-NumPadEnd -- should the virtualKey
+    //    be '1' or VK_HOME?
+
+    { true,  'O', 'M', kBare | kBareMod,            { VK_RETURN,   '\r',   0 } },
+    { true,  'O', 'j', kBare | kBareMod,            { VK_MULTIPLY, '*',    0 } },
+    { true,  'O', 'k', kBare | kBareMod,            { VK_ADD,      '+',    0 } },
+    { true,  'O', 'm', kBare | kBareMod,            { VK_SUBTRACT, '-',    0 } },
+    { true,  'O', 'n', kBare | kBareMod,            { VK_DELETE,   '\0',   0 } },
+    { true,  'O', 'o', kBare | kBareMod,            { VK_DIVIDE,   '/',    0 } },
+    { true,  'O', 'p', kBare | kBareMod,            { VK_INSERT,   '\0',   0 } },
+    { true,  'O', 'q', kBare | kBareMod,            { VK_END,      '\0',   0 } },
+    { true,  'O', 'r', kBare | kBareMod,            { VK_DOWN,     '\0',   0 } },
+    { true,  'O', 's', kBare | kBareMod,            { VK_NEXT,     '\0',   0 } },
+    { true,  'O', 't', kBare | kBareMod,            { VK_LEFT,     '\0',   0 } },
+    { true,  'O', 'u', kBare | kBareMod,            { VK_CLEAR,    '\0',   0 } },
+    { true,  'O', 'v', kBare | kBareMod,            { VK_RIGHT,    '\0',   0 } },
+    { true,  'O', 'w', kBare | kBareMod,            { VK_HOME,     '\0',   0 } },
+    { true,  'O', 'x', kBare | kBareMod,            { VK_UP,       '\0',   0 } },
+    { true,  'O', 'y', kBare | kBareMod,            { VK_PRIOR,    '\0',   0 } },
+
+    { true,  '[', 'M', kBare | kSemiMod,            { VK_RETURN,   '\r',   0 } },
+    { true,  '[', 'j', kBare | kSemiMod,            { VK_MULTIPLY, '*',    0 } },
+    { true,  '[', 'k', kBare | kSemiMod,            { VK_ADD,      '+',    0 } },
+    { true,  '[', 'm', kBare | kSemiMod,            { VK_SUBTRACT, '-',    0 } },
+    { true,  '[', 'n', kBare | kSemiMod,            { VK_DELETE,   '\0',   0 } },
+    { true,  '[', 'o', kBare | kSemiMod,            { VK_DIVIDE,   '/',    0 } },
+    { true,  '[', 'p', kBare | kSemiMod,            { VK_INSERT,   '\0',   0 } },
+    { true,  '[', 'q', kBare | kSemiMod,            { VK_END,      '\0',   0 } },
+    { true,  '[', 'r', kBare | kSemiMod,            { VK_DOWN,     '\0',   0 } },
+    { true,  '[', 's', kBare | kSemiMod,            { VK_NEXT,     '\0',   0 } },
+    { true,  '[', 't', kBare | kSemiMod,            { VK_LEFT,     '\0',   0 } },
+    { true,  '[', 'u', kBare | kSemiMod,            { VK_CLEAR,    '\0',   0 } },
+    { true,  '[', 'v', kBare | kSemiMod,            { VK_RIGHT,    '\0',   0 } },
+    { true,  '[', 'w', kBare | kSemiMod,            { VK_HOME,     '\0',   0 } },
+    { true,  '[', 'x', kBare | kSemiMod,            { VK_UP,       '\0',   0 } },
+    { true,  '[', 'y', kBare | kSemiMod,            { VK_PRIOR,    '\0',   0 } },
+
+    { false, '[', 'Z', kBare,                       { VK_TAB,     '\t', SHIFT_PRESSED } },
+};
+
+static const EscapeEncoding escapeNumericEncodings[] = {
+    { true,  '[',  1,  kBare | kSemiMod | kSuffixBoth,      { VK_HOME,    '\0', 0             } },
+    { true,  '[',  2,  kBare | kSemiMod | kSuffixBoth,      { VK_INSERT,  '\0', 0             } },
+    { true,  '[',  3,  kBare | kSemiMod | kSuffixBoth,      { VK_DELETE,  '\0', 0             } },
+    { true,  '[',  4,  kBare | kSemiMod | kSuffixBoth,      { VK_END,     '\0', 0             } },
+    { true,  '[',  5,  kBare | kSemiMod | kSuffixBoth,      { VK_PRIOR,   '\0', 0             } },
+    { true,  '[',  6,  kBare | kSemiMod | kSuffixBoth,      { VK_NEXT,    '\0', 0             } },
+    { true,  '[',  7,  kBare | kSemiMod | kSuffixBoth,      { VK_HOME,    '\0', 0             } },
+    { true,  '[',  8,  kBare | kSemiMod | kSuffixBoth,      { VK_END,     '\0', 0             } },
+    { true,  '[', 11,  kBare | kSemiMod | kSuffixBoth,      { VK_F1,      '\0', 0             } },
+    { true,  '[', 12,  kBare | kSemiMod | kSuffixBoth,      { VK_F2,      '\0', 0             } },
+    { true,  '[', 13,  kBare | kSemiMod | kSuffixBoth,      { VK_F3,      '\0', 0             } },
+    { true,  '[', 14,  kBare | kSemiMod | kSuffixBoth,      { VK_F4,      '\0', 0             } },
+    { true,  '[', 15,  kBare | kSemiMod | kSuffixBoth,      { VK_F5,      '\0', 0             } },
+    { true,  '[', 17,  kBare | kSemiMod | kSuffixBoth,      { VK_F6,      '\0', 0             } },
+    { true,  '[', 18,  kBare | kSemiMod | kSuffixBoth,      { VK_F7,      '\0', 0             } },
+    { true,  '[', 19,  kBare | kSemiMod | kSuffixBoth,      { VK_F8,      '\0', 0             } },
+    { true,  '[', 20,  kBare | kSemiMod | kSuffixBoth,      { VK_F9,      '\0', 0             } },
+    { true,  '[', 21,  kBare | kSemiMod | kSuffixBoth,      { VK_F10,     '\0', 0             } },
+    { true,  '[', 23,  kBare | kSemiMod | kSuffixBoth,      { VK_F11,     '\0', 0             } },
+    { true,  '[', 24,  kBare | kSemiMod | kSuffixBoth,      { VK_F12,     '\0', 0             } },
+    { true,  '[', 25,  kBare | kSemiMod | kSuffixBoth,      { VK_F3,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 26,  kBare | kSemiMod | kSuffixBoth,      { VK_F4,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 28,  kBare | kSemiMod | kSuffixBoth,      { VK_F5,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 29,  kBare | kSemiMod | kSuffixBoth,      { VK_F6,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 31,  kBare | kSemiMod | kSuffixBoth,      { VK_F7,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 32,  kBare | kSemiMod | kSuffixBoth,      { VK_F8,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 33,  kBare | kSemiMod | kSuffixBoth,      { VK_F9,      '\0', SHIFT_PRESSED } },
+    { true,  '[', 34,  kBare | kSemiMod | kSuffixBoth,      { VK_F10,     '\0', SHIFT_PRESSED } },
+};
+
+const int kCsiShiftModifier = 1;
+const int kCsiAltModifier   = 2;
+const int kCsiCtrlModifier  = 4;
+
+static inline bool useEnhancedForVirtualKey(uint16_t vk) {
+    switch (vk) {
+        case VK_UP:
+        case VK_DOWN:
+        case VK_LEFT:
+        case VK_RIGHT:
+        case VK_INSERT:
+        case VK_DELETE:
+        case VK_HOME:
+        case VK_END:
+        case VK_PRIOR:
+        case VK_NEXT:
+            return true;
+        default:
+            return false;
+    }
+}
+
+static void addSimpleEntries(InputMap &inputMap) {
+    struct SimpleEncoding {
+        const char *encoding;
+        InputMap::Key key;
+    };
+
+    static const SimpleEncoding simpleEncodings[] = {
+        // Ctrl-<letter/digit> seems to be handled OK by the default code path.
+
+        {   "\x7F",         { VK_BACK,  '\x08', 0,                                  } },
+        {   ESC "\x7F",     { VK_BACK,  '\x08', LEFT_ALT_PRESSED,                   } },
+        {   "\x03",         { 'C',      '\x03', LEFT_CTRL_PRESSED,                  } },
+
+        // Handle special F1-F5 for TERM=linux and TERM=cygwin.
+        {   ESC "[[A",      { VK_F1,    '\0',   0                                   } },
+        {   ESC "[[B",      { VK_F2,    '\0',   0                                   } },
+        {   ESC "[[C",      { VK_F3,    '\0',   0                                   } },
+        {   ESC "[[D",      { VK_F4,    '\0',   0                                   } },
+        {   ESC "[[E",      { VK_F5,    '\0',   0                                   } },
+
+        {   ESC ESC "[[A",  { VK_F1,    '\0',   LEFT_ALT_PRESSED                    } },
+        {   ESC ESC "[[B",  { VK_F2,    '\0',   LEFT_ALT_PRESSED                    } },
+        {   ESC ESC "[[C",  { VK_F3,    '\0',   LEFT_ALT_PRESSED                    } },
+        {   ESC ESC "[[D",  { VK_F4,    '\0',   LEFT_ALT_PRESSED                    } },
+        {   ESC ESC "[[E",  { VK_F5,    '\0',   LEFT_ALT_PRESSED                    } },
+    };
+
+    for (size_t i = 0; i < DIM(simpleEncodings); ++i) {
+        auto k = simpleEncodings[i].key;
+        if (useEnhancedForVirtualKey(k.virtualKey)) {
+            k.keyState |= ENHANCED_KEY;
+        }
+        inputMap.set(simpleEncodings[i].encoding,
+                     strlen(simpleEncodings[i].encoding),
+                     k);
+    }
+}
+
+struct ExpandContext {
+    InputMap &inputMap;
+    const EscapeEncoding &e;
+    char *buffer;
+    char *bufferEnd;
+};
+
+static inline void setEncoding(const ExpandContext &ctx, char *end,
+                               uint16_t extraKeyState) {
+    InputMap::Key k = ctx.e.key;
+    k.keyState |= extraKeyState;
+    if (k.keyState & LEFT_CTRL_PRESSED) {
+        switch (k.virtualKey) {
+            case VK_ADD:
+            case VK_DIVIDE:
+            case VK_MULTIPLY:
+            case VK_SUBTRACT:
+                k.unicodeChar = '\0';
+                break;
+            case VK_RETURN:
+                k.unicodeChar = '\n';
+                break;
+        }
+    }
+    if (useEnhancedForVirtualKey(k.virtualKey)) {
+        k.keyState |= ENHANCED_KEY;
+    }
+    ctx.inputMap.set(ctx.buffer, end - ctx.buffer, k);
+}
+
+static inline uint16_t keyStateForMod(int mod) {
+    int ret = 0;
+    if ((mod - 1) & kCsiShiftModifier)  ret |= SHIFT_PRESSED;
+    if ((mod - 1) & kCsiAltModifier)    ret |= LEFT_ALT_PRESSED;
+    if ((mod - 1) & kCsiCtrlModifier)   ret |= LEFT_CTRL_PRESSED;
+    return ret;
+}
+
+static void expandNumericEncodingSuffix(const ExpandContext &ctx, char *p,
+        uint16_t extraKeyState) {
+    ASSERT(p <= ctx.bufferEnd - 1);
+    {
+        char *q = p;
+        *q++ = '~';
+        setEncoding(ctx, q, extraKeyState);
+    }
+    if (ctx.e.modifiers & kSuffixShift) {
+        char *q = p;
+        *q++ = '$';
+        setEncoding(ctx, q, extraKeyState | SHIFT_PRESSED);
+    }
+    if (ctx.e.modifiers & kSuffixCtrl) {
+        char *q = p;
+        *q++ = '^';
+        setEncoding(ctx, q, extraKeyState | LEFT_CTRL_PRESSED);
+    }
+    if (ctx.e.modifiers & (kSuffixCtrl | kSuffixShift)) {
+        char *q = p;
+        *q++ = '@';
+        setEncoding(ctx, q, extraKeyState | SHIFT_PRESSED | LEFT_CTRL_PRESSED);
+    }
+}
+
+template <bool is_numeric>
+static inline void expandEncodingAfterAltPrefix(
+        const ExpandContext &ctx, char *p, uint16_t extraKeyState) {
+    auto appendId = [&](char *&ptr) {
+        const auto idstr = decOfInt(ctx.e.id);
+        ASSERT(ptr <= ctx.bufferEnd - idstr.size());
+        std::copy(idstr.data(), idstr.data() + idstr.size(), ptr);
+        ptr += idstr.size();
+    };
+    ASSERT(p <= ctx.bufferEnd - 2);
+    *p++ = '\x1b';
+    *p++ = ctx.e.prefix;
+    if (ctx.e.modifiers & kBare) {
+        char *q = p;
+        if (is_numeric) {
+            appendId(q);
+            expandNumericEncodingSuffix(ctx, q, extraKeyState);
+        } else {
+            ASSERT(q <= ctx.bufferEnd - 1);
+            *q++ = ctx.e.id;
+            setEncoding(ctx, q, extraKeyState);
+        }
+    }
+    if (ctx.e.modifiers & kBareMod) {
+        ASSERT(!is_numeric && "kBareMod is invalid with numeric sequences");
+        for (int mod = 2; mod <= 8; ++mod) {
+            char *q = p;
+            ASSERT(q <= ctx.bufferEnd - 2);
+            *q++ = '0' + mod;
+            *q++ = ctx.e.id;
+            setEncoding(ctx, q, extraKeyState | keyStateForMod(mod));
+        }
+    }
+    if (ctx.e.modifiers & kSemiMod) {
+        for (int mod = 2; mod <= 8; ++mod) {
+            char *q = p;
+            if (is_numeric) {
+                appendId(q);
+                ASSERT(q <= ctx.bufferEnd - 2);
+                *q++ = ';';
+                *q++ = '0' + mod;
+                expandNumericEncodingSuffix(
+                    ctx, q, extraKeyState | keyStateForMod(mod));
+            } else {
+                ASSERT(q <= ctx.bufferEnd - 4);
+                *q++ = '1';
+                *q++ = ';';
+                *q++ = '0' + mod;
+                *q++ = ctx.e.id;
+                setEncoding(ctx, q, extraKeyState | keyStateForMod(mod));
+            }
+        }
+    }
+}
+
+template <bool is_numeric>
+static inline void expandEncoding(const ExpandContext &ctx) {
+    if (ctx.e.alt_prefix_allowed) {
+        // For better or for worse, this code expands all of:
+        //  *     ESC [       <key>     -- <key>
+        //  * ESC ESC [       <key>     -- Alt-<key>
+        //  *     ESC [ 1 ; 3 <key>     -- Alt-<key>
+        //  * ESC ESC [ 1 ; 3 <key>     -- Alt-<key> specified twice
+        // I suspect no terminal actually emits the last one (i.e. specifying
+        // the Alt modifier using both methods), but I have seen a terminal
+        // that emitted a prefix ESC for Alt and a non-Alt modifier.
+        char *p = ctx.buffer;
+        ASSERT(p <= ctx.bufferEnd - 1);
+        *p++ = '\x1b';
+        expandEncodingAfterAltPrefix<is_numeric>(ctx, p, LEFT_ALT_PRESSED);
+    }
+    expandEncodingAfterAltPrefix<is_numeric>(ctx, ctx.buffer, 0);
+}
+
+template <bool is_numeric, size_t N>
+static void addEscapes(InputMap &inputMap, const EscapeEncoding (&encodings)[N]) {
+    char buffer[32];
+    for (size_t i = 0; i < DIM(encodings); ++i) {
+        ExpandContext ctx = {
+            inputMap, encodings[i],
+            buffer, buffer + sizeof(buffer)
+        };
+        expandEncoding<is_numeric>(ctx);
+    }
+}
+
+} // anonymous namespace
+
+void addDefaultEntriesToInputMap(InputMap &inputMap) {
+    addEscapes<false>(inputMap, escapeLetterEncodings);
+    addEscapes<true>(inputMap, escapeNumericEncodings);
+    addSimpleEntries(inputMap);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.h b/node_modules/node-pty/deps/winpty/src/agent/DefaultInputMap.h
new file mode 100644 (file)
index 0000000..c4b9083
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef DEFAULT_INPUT_MAP_H
+#define DEFAULT_INPUT_MAP_H
+
+class InputMap;
+
+void addDefaultEntriesToInputMap(InputMap &inputMap);
+
+#endif // DEFAULT_INPUT_MAP_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/DsrSender.h b/node_modules/node-pty/deps/winpty/src/agent/DsrSender.h
new file mode 100644 (file)
index 0000000..1ec0a97
--- /dev/null
@@ -0,0 +1,30 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef DSRSENDER_H
+#define DSRSENDER_H
+
+class DsrSender
+{
+public:
+    virtual void sendDsr() = 0;
+};
+
+#endif // DSRSENDER_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/EventLoop.cc b/node_modules/node-pty/deps/winpty/src/agent/EventLoop.cc
new file mode 100644 (file)
index 0000000..ba5cf18
--- /dev/null
@@ -0,0 +1,99 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#include "EventLoop.h"
+
+#include <algorithm>
+
+#include "NamedPipe.h"
+#include "../shared/DebugClient.h"
+#include "../shared/WinptyAssert.h"
+
+EventLoop::~EventLoop() {
+    for (NamedPipe *pipe : m_pipes) {
+        delete pipe;
+    }
+    m_pipes.clear();
+}
+
+// Enter the event loop.  Runs until the I/O or timeout handler calls exit().
+void EventLoop::run()
+{
+    std::vector<HANDLE> waitHandles;
+    DWORD lastTime = GetTickCount();
+    while (!m_exiting) {
+        bool didSomething = false;
+
+        // Attempt to make progress with the pipes.
+        waitHandles.clear();
+        for (size_t i = 0; i < m_pipes.size(); ++i) {
+            if (m_pipes[i]->serviceIo(&waitHandles)) {
+                onPipeIo(*m_pipes[i]);
+                didSomething = true;
+            }
+        }
+
+        // Call the timeout if enough time has elapsed.
+        if (m_pollInterval > 0) {
+            int elapsed = GetTickCount() - lastTime;
+            if (elapsed >= m_pollInterval) {
+                onPollTimeout();
+                lastTime = GetTickCount();
+                didSomething = true;
+            }
+        }
+
+        if (didSomething)
+            continue;
+
+        // If there's nothing to do, wait.
+        DWORD timeout = INFINITE;
+        if (m_pollInterval > 0)
+            timeout = std::max(0, (int)(lastTime + m_pollInterval - GetTickCount()));
+        if (waitHandles.size() == 0) {
+            ASSERT(timeout != INFINITE);
+            if (timeout > 0)
+                Sleep(timeout);
+        } else {
+            DWORD result = WaitForMultipleObjects(waitHandles.size(),
+                                                  waitHandles.data(),
+                                                  FALSE,
+                                                  timeout);
+            ASSERT(result != WAIT_FAILED);
+        }
+    }
+}
+
+NamedPipe &EventLoop::createNamedPipe()
+{
+    NamedPipe *ret = new NamedPipe();
+    m_pipes.push_back(ret);
+    return *ret;
+}
+
+void EventLoop::setPollInterval(int ms)
+{
+    m_pollInterval = ms;
+}
+
+void EventLoop::shutdown()
+{
+    m_exiting = true;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/EventLoop.h b/node_modules/node-pty/deps/winpty/src/agent/EventLoop.h
new file mode 100644 (file)
index 0000000..eddb0f6
--- /dev/null
@@ -0,0 +1,47 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef EVENTLOOP_H
+#define EVENTLOOP_H
+
+#include <vector>
+
+class NamedPipe;
+
+class EventLoop
+{
+public:
+    virtual ~EventLoop();
+    void run();
+
+protected:
+    NamedPipe &createNamedPipe();
+    void setPollInterval(int ms);
+    void shutdown();
+    virtual void onPollTimeout()                    {}
+    virtual void onPipeIo(NamedPipe &namedPipe)     {}
+
+private:
+    bool m_exiting = false;
+    std::vector<NamedPipe*> m_pipes;
+    int m_pollInterval = 0;
+};
+
+#endif // EVENTLOOP_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/InputMap.cc b/node_modules/node-pty/deps/winpty/src/agent/InputMap.cc
new file mode 100644 (file)
index 0000000..b1fbfc2
--- /dev/null
@@ -0,0 +1,246 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "InputMap.h"
+
+#include <windows.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "DebugShowInput.h"
+#include "SimplePool.h"
+#include "../shared/DebugClient.h"
+#include "../shared/UnixCtrlChars.h"
+#include "../shared/WinptyAssert.h"
+#include "../shared/winpty_snprintf.h"
+
+namespace {
+
+static const char *getVirtualKeyString(int virtualKey)
+{
+    switch (virtualKey) {
+#define WINPTY_GVKS_KEY(x) case VK_##x: return #x;
+        WINPTY_GVKS_KEY(RBUTTON)    WINPTY_GVKS_KEY(F9)
+        WINPTY_GVKS_KEY(CANCEL)     WINPTY_GVKS_KEY(F10)
+        WINPTY_GVKS_KEY(MBUTTON)    WINPTY_GVKS_KEY(F11)
+        WINPTY_GVKS_KEY(XBUTTON1)   WINPTY_GVKS_KEY(F12)
+        WINPTY_GVKS_KEY(XBUTTON2)   WINPTY_GVKS_KEY(F13)
+        WINPTY_GVKS_KEY(BACK)       WINPTY_GVKS_KEY(F14)
+        WINPTY_GVKS_KEY(TAB)        WINPTY_GVKS_KEY(F15)
+        WINPTY_GVKS_KEY(CLEAR)      WINPTY_GVKS_KEY(F16)
+        WINPTY_GVKS_KEY(RETURN)     WINPTY_GVKS_KEY(F17)
+        WINPTY_GVKS_KEY(SHIFT)      WINPTY_GVKS_KEY(F18)
+        WINPTY_GVKS_KEY(CONTROL)    WINPTY_GVKS_KEY(F19)
+        WINPTY_GVKS_KEY(MENU)       WINPTY_GVKS_KEY(F20)
+        WINPTY_GVKS_KEY(PAUSE)      WINPTY_GVKS_KEY(F21)
+        WINPTY_GVKS_KEY(CAPITAL)    WINPTY_GVKS_KEY(F22)
+        WINPTY_GVKS_KEY(HANGUL)     WINPTY_GVKS_KEY(F23)
+        WINPTY_GVKS_KEY(JUNJA)      WINPTY_GVKS_KEY(F24)
+        WINPTY_GVKS_KEY(FINAL)      WINPTY_GVKS_KEY(NUMLOCK)
+        WINPTY_GVKS_KEY(KANJI)      WINPTY_GVKS_KEY(SCROLL)
+        WINPTY_GVKS_KEY(ESCAPE)     WINPTY_GVKS_KEY(LSHIFT)
+        WINPTY_GVKS_KEY(CONVERT)    WINPTY_GVKS_KEY(RSHIFT)
+        WINPTY_GVKS_KEY(NONCONVERT) WINPTY_GVKS_KEY(LCONTROL)
+        WINPTY_GVKS_KEY(ACCEPT)     WINPTY_GVKS_KEY(RCONTROL)
+        WINPTY_GVKS_KEY(MODECHANGE) WINPTY_GVKS_KEY(LMENU)
+        WINPTY_GVKS_KEY(SPACE)      WINPTY_GVKS_KEY(RMENU)
+        WINPTY_GVKS_KEY(PRIOR)      WINPTY_GVKS_KEY(BROWSER_BACK)
+        WINPTY_GVKS_KEY(NEXT)       WINPTY_GVKS_KEY(BROWSER_FORWARD)
+        WINPTY_GVKS_KEY(END)        WINPTY_GVKS_KEY(BROWSER_REFRESH)
+        WINPTY_GVKS_KEY(HOME)       WINPTY_GVKS_KEY(BROWSER_STOP)
+        WINPTY_GVKS_KEY(LEFT)       WINPTY_GVKS_KEY(BROWSER_SEARCH)
+        WINPTY_GVKS_KEY(UP)         WINPTY_GVKS_KEY(BROWSER_FAVORITES)
+        WINPTY_GVKS_KEY(RIGHT)      WINPTY_GVKS_KEY(BROWSER_HOME)
+        WINPTY_GVKS_KEY(DOWN)       WINPTY_GVKS_KEY(VOLUME_MUTE)
+        WINPTY_GVKS_KEY(SELECT)     WINPTY_GVKS_KEY(VOLUME_DOWN)
+        WINPTY_GVKS_KEY(PRINT)      WINPTY_GVKS_KEY(VOLUME_UP)
+        WINPTY_GVKS_KEY(EXECUTE)    WINPTY_GVKS_KEY(MEDIA_NEXT_TRACK)
+        WINPTY_GVKS_KEY(SNAPSHOT)   WINPTY_GVKS_KEY(MEDIA_PREV_TRACK)
+        WINPTY_GVKS_KEY(INSERT)     WINPTY_GVKS_KEY(MEDIA_STOP)
+        WINPTY_GVKS_KEY(DELETE)     WINPTY_GVKS_KEY(MEDIA_PLAY_PAUSE)
+        WINPTY_GVKS_KEY(HELP)       WINPTY_GVKS_KEY(LAUNCH_MAIL)
+        WINPTY_GVKS_KEY(LWIN)       WINPTY_GVKS_KEY(LAUNCH_MEDIA_SELECT)
+        WINPTY_GVKS_KEY(RWIN)       WINPTY_GVKS_KEY(LAUNCH_APP1)
+        WINPTY_GVKS_KEY(APPS)       WINPTY_GVKS_KEY(LAUNCH_APP2)
+        WINPTY_GVKS_KEY(SLEEP)      WINPTY_GVKS_KEY(OEM_1)
+        WINPTY_GVKS_KEY(NUMPAD0)    WINPTY_GVKS_KEY(OEM_PLUS)
+        WINPTY_GVKS_KEY(NUMPAD1)    WINPTY_GVKS_KEY(OEM_COMMA)
+        WINPTY_GVKS_KEY(NUMPAD2)    WINPTY_GVKS_KEY(OEM_MINUS)
+        WINPTY_GVKS_KEY(NUMPAD3)    WINPTY_GVKS_KEY(OEM_PERIOD)
+        WINPTY_GVKS_KEY(NUMPAD4)    WINPTY_GVKS_KEY(OEM_2)
+        WINPTY_GVKS_KEY(NUMPAD5)    WINPTY_GVKS_KEY(OEM_3)
+        WINPTY_GVKS_KEY(NUMPAD6)    WINPTY_GVKS_KEY(OEM_4)
+        WINPTY_GVKS_KEY(NUMPAD7)    WINPTY_GVKS_KEY(OEM_5)
+        WINPTY_GVKS_KEY(NUMPAD8)    WINPTY_GVKS_KEY(OEM_6)
+        WINPTY_GVKS_KEY(NUMPAD9)    WINPTY_GVKS_KEY(OEM_7)
+        WINPTY_GVKS_KEY(MULTIPLY)   WINPTY_GVKS_KEY(OEM_8)
+        WINPTY_GVKS_KEY(ADD)        WINPTY_GVKS_KEY(OEM_102)
+        WINPTY_GVKS_KEY(SEPARATOR)  WINPTY_GVKS_KEY(PROCESSKEY)
+        WINPTY_GVKS_KEY(SUBTRACT)   WINPTY_GVKS_KEY(PACKET)
+        WINPTY_GVKS_KEY(DECIMAL)    WINPTY_GVKS_KEY(ATTN)
+        WINPTY_GVKS_KEY(DIVIDE)     WINPTY_GVKS_KEY(CRSEL)
+        WINPTY_GVKS_KEY(F1)         WINPTY_GVKS_KEY(EXSEL)
+        WINPTY_GVKS_KEY(F2)         WINPTY_GVKS_KEY(EREOF)
+        WINPTY_GVKS_KEY(F3)         WINPTY_GVKS_KEY(PLAY)
+        WINPTY_GVKS_KEY(F4)         WINPTY_GVKS_KEY(ZOOM)
+        WINPTY_GVKS_KEY(F5)         WINPTY_GVKS_KEY(NONAME)
+        WINPTY_GVKS_KEY(F6)         WINPTY_GVKS_KEY(PA1)
+        WINPTY_GVKS_KEY(F7)         WINPTY_GVKS_KEY(OEM_CLEAR)
+        WINPTY_GVKS_KEY(F8)
+#undef WINPTY_GVKS_KEY
+        default:                        return NULL;
+    }
+}
+
+} // anonymous namespace
+
+std::string InputMap::Key::toString() const {
+    std::string ret;
+    ret += controlKeyStatePrefix(keyState);
+    char buf[256];
+    const char *vkString = getVirtualKeyString(virtualKey);
+    if (vkString != NULL) {
+        ret += vkString;
+    } else if ((virtualKey >= 'A' && virtualKey <= 'Z') ||
+               (virtualKey >= '0' && virtualKey <= '9')) {
+        ret += static_cast<char>(virtualKey);
+    } else {
+        winpty_snprintf(buf, "%#x", virtualKey);
+        ret += buf;
+    }
+    if (unicodeChar >= 32 && unicodeChar <= 126) {
+        winpty_snprintf(buf, " ch='%c'",
+                        static_cast<char>(unicodeChar));
+    } else {
+        winpty_snprintf(buf, " ch=%#x",
+                        static_cast<unsigned int>(unicodeChar));
+    }
+    ret += buf;
+    return ret;
+}
+
+void InputMap::set(const char *encoding, int encodingLen, const Key &key) {
+    ASSERT(encodingLen > 0);
+    setHelper(m_root, encoding, encodingLen, key);
+}
+
+void InputMap::setHelper(Node &node, const char *encoding, int encodingLen, const Key &key) {
+    if (encodingLen == 0) {
+        node.key = key;
+    } else {
+        setHelper(getOrCreateChild(node, encoding[0]), encoding + 1, encodingLen - 1, key);
+    }
+}
+
+InputMap::Node &InputMap::getOrCreateChild(Node &node, unsigned char ch) {
+    Node *ret = getChild(node, ch);
+    if (ret != NULL) {
+        return *ret;
+    }
+    if (node.childCount < Node::kTinyCount) {
+        // Maintain sorted order for the sake of the InputMap dumping.
+        int insertIndex = node.childCount;
+        for (int i = 0; i < node.childCount; ++i) {
+            if (ch < node.u.tiny.values[i]) {
+                insertIndex = i;
+                break;
+            }
+        }
+        for (int j = node.childCount; j > insertIndex; --j) {
+            node.u.tiny.values[j] = node.u.tiny.values[j - 1];
+            node.u.tiny.children[j] = node.u.tiny.children[j - 1];
+        }
+        node.u.tiny.values[insertIndex] = ch;
+        node.u.tiny.children[insertIndex] = ret = m_nodePool.alloc();
+        ++node.childCount;
+        return *ret;
+    }
+    if (node.childCount == Node::kTinyCount) {
+        Branch *branch = m_branchPool.alloc();
+        for (int i = 0; i < node.childCount; ++i) {
+            branch->children[node.u.tiny.values[i]] = node.u.tiny.children[i];
+        }
+        node.u.branch = branch;
+    }
+    node.u.branch->children[ch] = ret = m_nodePool.alloc();
+    ++node.childCount;
+    return *ret;
+}
+
+// Find the longest matching key and node.
+int InputMap::lookupKey(const char *input, int inputSize,
+                        Key &keyOut, bool &incompleteOut) const {
+    keyOut = kKeyZero;
+    incompleteOut = false;
+
+    const Node *node = &m_root;
+    InputMap::Key longestMatch = kKeyZero;
+    int longestMatchLen = 0;
+
+    for (int i = 0; i < inputSize; ++i) {
+        unsigned char ch = input[i];
+        node = getChild(*node, ch);
+        if (node == NULL) {
+            keyOut = longestMatch;
+            return longestMatchLen;
+        } else if (node->hasKey()) {
+            longestMatchLen = i + 1;
+            longestMatch = node->key;
+        }
+    }
+    keyOut = longestMatch;
+    incompleteOut = node->childCount > 0;
+    return longestMatchLen;
+}
+
+void InputMap::dumpInputMap() const {
+    std::string encoding;
+    dumpInputMapHelper(m_root, encoding);
+}
+
+void InputMap::dumpInputMapHelper(
+        const Node &node, std::string &encoding) const {
+    if (node.hasKey()) {
+        trace("%s -> %s",
+            encoding.c_str(),
+            node.key.toString().c_str());
+    }
+    for (int i = 0; i < 256; ++i) {
+        const Node *child = getChild(node, i);
+        if (child != NULL) {
+            size_t oldSize = encoding.size();
+            if (!encoding.empty()) {
+                encoding.push_back(' ');
+            }
+            char ctrlChar = decodeUnixCtrlChar(i);
+            if (ctrlChar != '\0') {
+                encoding.push_back('^');
+                encoding.push_back(static_cast<char>(ctrlChar));
+            } else if (i == ' ') {
+                encoding.append("' '");
+            } else {
+                encoding.push_back(static_cast<char>(i));
+            }
+            dumpInputMapHelper(*child, encoding);
+            encoding.resize(oldSize);
+        }
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/InputMap.h b/node_modules/node-pty/deps/winpty/src/agent/InputMap.h
new file mode 100644 (file)
index 0000000..9a666c7
--- /dev/null
@@ -0,0 +1,114 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#ifndef INPUT_MAP_H
+#define INPUT_MAP_H
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <string>
+
+#include "SimplePool.h"
+#include "../shared/WinptyAssert.h"
+
+class InputMap {
+public:
+    struct Key {
+        uint16_t virtualKey;
+        uint32_t unicodeChar;
+        uint16_t keyState;
+
+        std::string toString() const;
+    };
+
+private:
+    struct Node;
+
+    struct Branch {
+        Branch() {
+            memset(&children, 0, sizeof(children));
+        }
+
+        Node *children[256];
+    };
+
+    struct Node {
+        Node() : childCount(0) {
+            Key zeroKey = { 0, 0, 0 };
+            key = zeroKey;
+        }
+
+        Key key;
+        int childCount;
+        enum { kTinyCount = 8 };
+        union {
+            Branch *branch;
+            struct {
+                unsigned char values[kTinyCount];
+                Node *children[kTinyCount];
+            } tiny;
+        } u;
+
+        bool hasKey() const {
+            return key.virtualKey != 0 || key.unicodeChar != 0;
+        }
+    };
+
+private:
+    SimplePool<Node, 256> m_nodePool;
+    SimplePool<Branch, 8> m_branchPool;
+    Node m_root;
+
+public:
+    void set(const char *encoding, int encodingLen, const Key &key);
+    int lookupKey(const char *input, int inputSize,
+                  Key &keyOut, bool &incompleteOut) const;
+    void dumpInputMap() const;
+
+private:
+    Node *getChild(Node &node, unsigned char ch) {
+        return const_cast<Node*>(getChild(static_cast<const Node&>(node), ch));
+    }
+
+    const Node *getChild(const Node &node, unsigned char ch) const {
+        if (node.childCount <= Node::kTinyCount) {
+            for (int i = 0; i < node.childCount; ++i) {
+                if (node.u.tiny.values[i] == ch) {
+                    return node.u.tiny.children[i];
+                }
+            }
+            return NULL;
+        } else {
+            return node.u.branch->children[ch];
+        }
+    }
+
+    void setHelper(Node &node, const char *encoding, int encodingLen, const Key &key);
+    Node &getOrCreateChild(Node &node, unsigned char ch);
+    void dumpInputMapHelper(const Node &node, std::string &encoding) const;
+};
+
+const InputMap::Key kKeyZero = { 0, 0, 0 };
+
+void dumpInputMap(InputMap &inputMap);
+
+#endif // INPUT_MAP_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.cc b/node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.cc
new file mode 100644 (file)
index 0000000..80ac640
--- /dev/null
@@ -0,0 +1,71 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "LargeConsoleRead.h"
+
+#include <stdlib.h>
+
+#include "../shared/WindowsVersion.h"
+#include "Scraper.h"
+#include "Win32ConsoleBuffer.h"
+
+LargeConsoleReadBuffer::LargeConsoleReadBuffer() :
+    m_rect(0, 0, 0, 0), m_rectWidth(0)
+{
+}
+
+void largeConsoleRead(LargeConsoleReadBuffer &out,
+                      Win32ConsoleBuffer &buffer,
+                      const SmallRect &readArea,
+                      WORD attributesMask) {
+    ASSERT(readArea.Left >= 0 &&
+           readArea.Top >= 0 &&
+           readArea.Right >= readArea.Left &&
+           readArea.Bottom >= readArea.Top &&
+           readArea.width() <= MAX_CONSOLE_WIDTH);
+    const size_t count = readArea.width() * readArea.height();
+    if (out.m_data.size() < count) {
+        out.m_data.resize(count);
+    }
+    out.m_rect = readArea;
+    out.m_rectWidth = readArea.width();
+
+    static const bool useLargeReads = isAtLeastWindows8();
+    if (useLargeReads) {
+        buffer.read(readArea, out.m_data.data());
+    } else {
+        const int maxReadLines = std::max(1, MAX_CONSOLE_WIDTH / readArea.width());
+        int curLine = readArea.Top;
+        while (curLine <= readArea.Bottom) {
+            const SmallRect subReadArea(
+                readArea.Left,
+                curLine,
+                readArea.width(),
+                std::min(maxReadLines, readArea.Bottom + 1 - curLine));
+            buffer.read(subReadArea, out.lineDataMut(curLine));
+            curLine = subReadArea.Bottom + 1;
+        }
+    }
+    if (attributesMask != static_cast<WORD>(~0)) {
+        for (size_t i = 0; i < count; ++i) {
+            out.m_data[i].Attributes &= attributesMask;
+        }
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.h b/node_modules/node-pty/deps/winpty/src/agent/LargeConsoleRead.h
new file mode 100644 (file)
index 0000000..1bcf2c0
--- /dev/null
@@ -0,0 +1,68 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef LARGE_CONSOLE_READ_H
+#define LARGE_CONSOLE_READ_H
+
+#include <windows.h>
+#include <stdlib.h>
+
+#include <vector>
+
+#include "SmallRect.h"
+#include "../shared/DebugClient.h"
+#include "../shared/WinptyAssert.h"
+
+class Win32ConsoleBuffer;
+
+class LargeConsoleReadBuffer {
+public:
+    LargeConsoleReadBuffer();
+    const SmallRect &rect() const { return m_rect; }
+    const CHAR_INFO *lineData(int line) const {
+        validateLineNumber(line);
+        return &m_data[(line - m_rect.Top) * m_rectWidth];
+    }
+
+private:
+    CHAR_INFO *lineDataMut(int line) {
+        validateLineNumber(line);
+        return &m_data[(line - m_rect.Top) * m_rectWidth];
+    }
+
+    void validateLineNumber(int line) const {
+        if (line < m_rect.Top || line > m_rect.Bottom) {
+            trace("Fatal error: LargeConsoleReadBuffer: invalid line %d for "
+                  "read rect %s", line, m_rect.toString().c_str());
+            abort();
+        }
+    }
+
+    SmallRect m_rect;
+    int m_rectWidth;
+    std::vector<CHAR_INFO> m_data;
+
+    friend void largeConsoleRead(LargeConsoleReadBuffer &out,
+                                 Win32ConsoleBuffer &buffer,
+                                 const SmallRect &readArea,
+                                 WORD attributesMask);
+};
+
+#endif // LARGE_CONSOLE_READ_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/NamedPipe.cc b/node_modules/node-pty/deps/winpty/src/agent/NamedPipe.cc
new file mode 100644 (file)
index 0000000..64044e6
--- /dev/null
@@ -0,0 +1,378 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#include <string.h>
+
+#include <algorithm>
+
+#include "EventLoop.h"
+#include "NamedPipe.h"
+#include "../shared/DebugClient.h"
+#include "../shared/StringUtil.h"
+#include "../shared/WindowsSecurity.h"
+#include "../shared/WinptyAssert.h"
+
+// Returns true if anything happens (data received, data sent, pipe error).
+bool NamedPipe::serviceIo(std::vector<HANDLE> *waitHandles)
+{
+    bool justConnected = false;
+    const auto kError = ServiceResult::Error;
+    const auto kProgress = ServiceResult::Progress;
+    const auto kNoProgress = ServiceResult::NoProgress;
+    if (m_handle == NULL) {
+        return false;
+    }
+    if (m_connectEvent.get() != nullptr) {
+        // We're still connecting this server pipe.  Check whether the pipe is
+        // now connected.  If it isn't, add the pipe to the list of handles to
+        // wait on.
+        DWORD actual = 0;
+        BOOL success =
+            GetOverlappedResult(m_handle, &m_connectOver, &actual, FALSE);
+        if (!success && GetLastError() == ERROR_PIPE_CONNECTED) {
+            // I'm not sure this can happen, but it's easy to handle if it
+            // does.
+            success = TRUE;
+        }
+        if (!success) {
+            ASSERT(GetLastError() == ERROR_IO_INCOMPLETE &&
+                "Pended ConnectNamedPipe call failed");
+            waitHandles->push_back(m_connectEvent.get());
+        } else {
+            TRACE("Server pipe [%s] connected",
+                utf8FromWide(m_name).c_str());
+            m_connectEvent.dispose();
+            startPipeWorkers();
+            justConnected = true;
+        }
+    }
+    const auto readProgress = m_inputWorker ? m_inputWorker->service() : kNoProgress;
+    const auto writeProgress = m_outputWorker ? m_outputWorker->service() : kNoProgress;
+    if (readProgress == kError || writeProgress == kError) {
+        closePipe();
+        return true;
+    }
+    if (m_inputWorker && m_inputWorker->getWaitEvent() != nullptr) {
+        waitHandles->push_back(m_inputWorker->getWaitEvent());
+    }
+    if (m_outputWorker && m_outputWorker->getWaitEvent() != nullptr) {
+        waitHandles->push_back(m_outputWorker->getWaitEvent());
+    }
+    return justConnected
+        || readProgress == kProgress
+        || writeProgress == kProgress;
+}
+
+// manual reset, initially unset
+static OwnedHandle createEvent() {
+    HANDLE ret = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+    ASSERT(ret != nullptr && "CreateEventW failed");
+    return OwnedHandle(ret);
+}
+
+NamedPipe::IoWorker::IoWorker(NamedPipe &namedPipe) :
+    m_namedPipe(namedPipe),
+    m_event(createEvent())
+{
+}
+
+NamedPipe::ServiceResult NamedPipe::IoWorker::service()
+{
+    ServiceResult progress = ServiceResult::NoProgress;
+    if (m_pending) {
+        DWORD actual = 0;
+        BOOL ret = GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, FALSE);
+        if (!ret) {
+            if (GetLastError() == ERROR_IO_INCOMPLETE) {
+                // There is a pending I/O.
+                return progress;
+            } else {
+                // Pipe error.
+                return ServiceResult::Error;
+            }
+        }
+        ResetEvent(m_event.get());
+        m_pending = false;
+        completeIo(actual);
+        m_currentIoSize = 0;
+        progress = ServiceResult::Progress;
+    }
+    DWORD nextSize = 0;
+    bool isRead = false;
+    while (shouldIssueIo(&nextSize, &isRead)) {
+        m_currentIoSize = nextSize;
+        DWORD actual = 0;
+        memset(&m_over, 0, sizeof(m_over));
+        m_over.hEvent = m_event.get();
+        BOOL ret = isRead
+                ? ReadFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over)
+                : WriteFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over);
+        if (!ret) {
+            if (GetLastError() == ERROR_IO_PENDING) {
+                // There is a pending I/O.
+                m_pending = true;
+                return progress;
+            } else {
+                // Pipe error.
+                return ServiceResult::Error;
+            }
+        }
+        ResetEvent(m_event.get());
+        completeIo(actual);
+        m_currentIoSize = 0;
+        progress = ServiceResult::Progress;
+    }
+    return progress;
+}
+
+// This function is called after CancelIo has returned.  We need to block until
+// the I/O operations have completed, which should happen very quickly.
+// https://blogs.msdn.microsoft.com/oldnewthing/20110202-00/?p=11613
+void NamedPipe::IoWorker::waitForCanceledIo()
+{
+    if (m_pending) {
+        DWORD actual = 0;
+        GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, TRUE);
+        m_pending = false;
+    }
+}
+
+HANDLE NamedPipe::IoWorker::getWaitEvent()
+{
+    return m_pending ? m_event.get() : NULL;
+}
+
+void NamedPipe::InputWorker::completeIo(DWORD size)
+{
+    m_namedPipe.m_inQueue.append(m_buffer, size);
+}
+
+bool NamedPipe::InputWorker::shouldIssueIo(DWORD *size, bool *isRead)
+{
+    *isRead = true;
+    ASSERT(!m_namedPipe.isConnecting());
+    if (m_namedPipe.isClosed()) {
+        return false;
+    } else if (m_namedPipe.m_inQueue.size() < m_namedPipe.readBufferSize()) {
+        *size = kIoSize;
+        return true;
+    } else {
+        return false;
+    }
+}
+
+void NamedPipe::OutputWorker::completeIo(DWORD size)
+{
+    ASSERT(size == m_currentIoSize);
+}
+
+bool NamedPipe::OutputWorker::shouldIssueIo(DWORD *size, bool *isRead)
+{
+    *isRead = false;
+    if (!m_namedPipe.m_outQueue.empty()) {
+        auto &out = m_namedPipe.m_outQueue;
+        const DWORD writeSize = std::min<size_t>(out.size(), kIoSize);
+        std::copy(&out[0], &out[writeSize], m_buffer);
+        out.erase(0, writeSize);
+        *size = writeSize;
+        return true;
+    } else {
+        return false;
+    }
+}
+
+DWORD NamedPipe::OutputWorker::getPendingIoSize()
+{
+    return m_pending ? m_currentIoSize : 0;
+}
+
+void NamedPipe::openServerPipe(LPCWSTR pipeName, OpenMode::t openMode,
+                               int outBufferSize, int inBufferSize) {
+    ASSERT(isClosed());
+    ASSERT((openMode & OpenMode::Duplex) != 0);
+    const DWORD winOpenMode =
+              ((openMode & OpenMode::Reading) ? PIPE_ACCESS_INBOUND : 0)
+            | ((openMode & OpenMode::Writing) ? PIPE_ACCESS_OUTBOUND : 0)
+            | FILE_FLAG_FIRST_PIPE_INSTANCE
+            | FILE_FLAG_OVERLAPPED;
+    const auto sd = createPipeSecurityDescriptorOwnerFullControl();
+    ASSERT(sd && "error creating data pipe SECURITY_DESCRIPTOR");
+    SECURITY_ATTRIBUTES sa = {};
+    sa.nLength = sizeof(sa);
+    sa.lpSecurityDescriptor = sd.get();
+    HANDLE handle = CreateNamedPipeW(
+        pipeName,
+        /*dwOpenMode=*/winOpenMode,
+        /*dwPipeMode=*/rejectRemoteClientsPipeFlag(),
+        /*nMaxInstances=*/1,
+        /*nOutBufferSize=*/outBufferSize,
+        /*nInBufferSize=*/inBufferSize,
+        /*nDefaultTimeOut=*/30000,
+        &sa);
+    TRACE("opened server pipe [%s], handle == %p",
+        utf8FromWide(pipeName).c_str(), handle);
+    ASSERT(handle != INVALID_HANDLE_VALUE && "Could not open server pipe");
+    m_name = pipeName;
+    m_handle = handle;
+    m_openMode = openMode;
+
+    // Start an asynchronous connection attempt.
+    m_connectEvent = createEvent();
+    memset(&m_connectOver, 0, sizeof(m_connectOver));
+    m_connectOver.hEvent = m_connectEvent.get();
+    BOOL success = ConnectNamedPipe(m_handle, &m_connectOver);
+    const auto err = GetLastError();
+    if (!success && err == ERROR_PIPE_CONNECTED) {
+        success = TRUE;
+    }
+    if (success) {
+        TRACE("Server pipe [%s] connected", utf8FromWide(pipeName).c_str());
+        m_connectEvent.dispose();
+        startPipeWorkers();
+    } else if (err != ERROR_IO_PENDING) {
+        ASSERT(false && "ConnectNamedPipe call failed");
+    }
+}
+
+void NamedPipe::connectToServer(LPCWSTR pipeName, OpenMode::t openMode)
+{
+    ASSERT(isClosed());
+    ASSERT((openMode & OpenMode::Duplex) != 0);
+    HANDLE handle = CreateFileW(
+        pipeName,
+        GENERIC_READ | GENERIC_WRITE,
+        0,
+        NULL,
+        OPEN_EXISTING,
+        SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED,
+        NULL);
+    TRACE("connected to [%s], handle == %p",
+        utf8FromWide(pipeName).c_str(), handle);
+    ASSERT(handle != INVALID_HANDLE_VALUE && "Could not connect to pipe");
+    m_name = pipeName;
+    m_handle = handle;
+    m_openMode = openMode;
+    startPipeWorkers();
+}
+
+void NamedPipe::startPipeWorkers()
+{
+    if (m_openMode & OpenMode::Reading) {
+        m_inputWorker.reset(new InputWorker(*this));
+    }
+    if (m_openMode & OpenMode::Writing) {
+        m_outputWorker.reset(new OutputWorker(*this));
+    }
+}
+
+size_t NamedPipe::bytesToSend()
+{
+    ASSERT(m_openMode & OpenMode::Writing);
+    auto ret = m_outQueue.size();
+    if (m_outputWorker != NULL) {
+        ret += m_outputWorker->getPendingIoSize();
+    }
+    return ret;
+}
+
+void NamedPipe::write(const void *data, size_t size)
+{
+    ASSERT(m_openMode & OpenMode::Writing);
+    m_outQueue.append(reinterpret_cast<const char*>(data), size);
+}
+
+void NamedPipe::write(const char *text)
+{
+    write(text, strlen(text));
+}
+
+size_t NamedPipe::readBufferSize()
+{
+    ASSERT(m_openMode & OpenMode::Reading);
+    return m_readBufferSize;
+}
+
+void NamedPipe::setReadBufferSize(size_t size)
+{
+    ASSERT(m_openMode & OpenMode::Reading);
+    m_readBufferSize = size;
+}
+
+size_t NamedPipe::bytesAvailable()
+{
+    ASSERT(m_openMode & OpenMode::Reading);
+    return m_inQueue.size();
+}
+
+size_t NamedPipe::peek(void *data, size_t size)
+{
+    ASSERT(m_openMode & OpenMode::Reading);
+    const auto out = reinterpret_cast<char*>(data);
+    const size_t ret = std::min(size, m_inQueue.size());
+    std::copy(&m_inQueue[0], &m_inQueue[ret], out);
+    return ret;
+}
+
+size_t NamedPipe::read(void *data, size_t size)
+{
+    size_t ret = peek(data, size);
+    m_inQueue.erase(0, ret);
+    return ret;
+}
+
+std::string NamedPipe::readToString(size_t size)
+{
+    ASSERT(m_openMode & OpenMode::Reading);
+    size_t retSize = std::min(size, m_inQueue.size());
+    std::string ret = m_inQueue.substr(0, retSize);
+    m_inQueue.erase(0, retSize);
+    return ret;
+}
+
+std::string NamedPipe::readAllToString()
+{
+    ASSERT(m_openMode & OpenMode::Reading);
+    std::string ret = m_inQueue;
+    m_inQueue.clear();
+    return ret;
+}
+
+void NamedPipe::closePipe()
+{
+    if (m_handle == NULL) {
+        return;
+    }
+    CancelIo(m_handle);
+    if (m_connectEvent.get() != nullptr) {
+        DWORD actual = 0;
+        GetOverlappedResult(m_handle, &m_connectOver, &actual, TRUE);
+        m_connectEvent.dispose();
+    }
+    if (m_inputWorker) {
+        m_inputWorker->waitForCanceledIo();
+        m_inputWorker.reset();
+    }
+    if (m_outputWorker) {
+        m_outputWorker->waitForCanceledIo();
+        m_outputWorker.reset();
+    }
+    CloseHandle(m_handle);
+    m_handle = NULL;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/NamedPipe.h b/node_modules/node-pty/deps/winpty/src/agent/NamedPipe.h
new file mode 100644 (file)
index 0000000..0a4d8b0
--- /dev/null
@@ -0,0 +1,125 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef NAMEDPIPE_H
+#define NAMEDPIPE_H
+
+#include <windows.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "../shared/OwnedHandle.h"
+
+class EventLoop;
+
+class NamedPipe
+{
+private:
+    // The EventLoop uses these private members.
+    friend class EventLoop;
+    NamedPipe() {}
+    ~NamedPipe() { closePipe(); }
+    bool serviceIo(std::vector<HANDLE> *waitHandles);
+    void startPipeWorkers();
+
+    enum class ServiceResult { NoProgress, Error, Progress };
+
+private:
+    class IoWorker
+    {
+    public:
+        IoWorker(NamedPipe &namedPipe);
+        virtual ~IoWorker() {}
+        ServiceResult service();
+        void waitForCanceledIo();
+        HANDLE getWaitEvent();
+    protected:
+        NamedPipe &m_namedPipe;
+        bool m_pending = false;
+        DWORD m_currentIoSize = 0;
+        OwnedHandle m_event;
+        OVERLAPPED m_over = {};
+        enum { kIoSize = 64 * 1024 };
+        char m_buffer[kIoSize];
+        virtual void completeIo(DWORD size) = 0;
+        virtual bool shouldIssueIo(DWORD *size, bool *isRead) = 0;
+    };
+
+    class InputWorker : public IoWorker
+    {
+    public:
+        InputWorker(NamedPipe &namedPipe) : IoWorker(namedPipe) {}
+    protected:
+        virtual void completeIo(DWORD size) override;
+        virtual bool shouldIssueIo(DWORD *size, bool *isRead) override;
+    };
+
+    class OutputWorker : public IoWorker
+    {
+    public:
+        OutputWorker(NamedPipe &namedPipe) : IoWorker(namedPipe) {}
+        DWORD getPendingIoSize();
+    protected:
+        virtual void completeIo(DWORD size) override;
+        virtual bool shouldIssueIo(DWORD *size, bool *isRead) override;
+    };
+
+public:
+    struct OpenMode {
+        typedef int t;
+        enum { None = 0, Reading = 1, Writing = 2, Duplex = 3 };
+    };
+
+    std::wstring name() const { return m_name; }
+    void openServerPipe(LPCWSTR pipeName, OpenMode::t openMode,
+                        int outBufferSize, int inBufferSize);
+    void connectToServer(LPCWSTR pipeName, OpenMode::t openMode);
+    size_t bytesToSend();
+    void write(const void *data, size_t size);
+    void write(const char *text);
+    size_t readBufferSize();
+    void setReadBufferSize(size_t size);
+    size_t bytesAvailable();
+    size_t peek(void *data, size_t size);
+    size_t read(void *data, size_t size);
+    std::string readToString(size_t size);
+    std::string readAllToString();
+    void closePipe();
+    bool isClosed() { return m_handle == nullptr; }
+    bool isConnected() { return !isClosed() && !isConnecting(); }
+    bool isConnecting() { return m_connectEvent.get() != nullptr; }
+
+private:
+    // Input/output buffers
+    std::wstring m_name;
+    OVERLAPPED m_connectOver = {};
+    OwnedHandle m_connectEvent;
+    OpenMode::t m_openMode = OpenMode::None;
+    size_t m_readBufferSize = 64 * 1024;
+    std::string m_inQueue;
+    std::string m_outQueue;
+    HANDLE m_handle = nullptr;
+    std::unique_ptr<InputWorker> m_inputWorker;
+    std::unique_ptr<OutputWorker> m_outputWorker;
+};
+
+#endif // NAMEDPIPE_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Scraper.cc b/node_modules/node-pty/deps/winpty/src/agent/Scraper.cc
new file mode 100644 (file)
index 0000000..21f9c67
--- /dev/null
@@ -0,0 +1,699 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "Scraper.h"
+
+#include <windows.h>
+
+#include <stdint.h>
+
+#include <algorithm>
+#include <utility>
+
+#include "../shared/WinptyAssert.h"
+#include "../shared/winpty_snprintf.h"
+
+#include "ConsoleFont.h"
+#include "Win32Console.h"
+#include "Win32ConsoleBuffer.h"
+
+namespace {
+
+template <typename T>
+T constrained(T min, T val, T max) {
+    ASSERT(min <= max);
+    return std::min(std::max(min, val), max);
+}
+
+} // anonymous namespace
+
+Scraper::Scraper(
+        Win32Console &console,
+        Win32ConsoleBuffer &buffer,
+        std::unique_ptr<Terminal> terminal,
+        Coord initialSize) :
+    m_console(console),
+    m_terminal(std::move(terminal)),
+    m_ptySize(initialSize)
+{
+    m_consoleBuffer = &buffer;
+
+    resetConsoleTracking(Terminal::OmitClear, buffer.windowRect().top());
+
+    m_bufferData.resize(BUFFER_LINE_COUNT);
+
+    // Setup the initial screen buffer and window size.
+    //
+    // Use SetConsoleWindowInfo to shrink the console window as much as
+    // possible -- to a 1x1 cell at the top-left.  This call always succeeds.
+    // Prior to the new Windows 10 console, it also actually resizes the GUI
+    // window to 1x1 cell.  Nevertheless, even though the GUI window can
+    // therefore be narrower than its minimum, calling
+    // SetConsoleScreenBufferSize with a 1x1 size still fails.
+    //
+    // While the small font intends to support large buffers, a user could
+    // still hit a limit imposed by their monitor width, so cap the new window
+    // size to GetLargestConsoleWindowSize().
+    setSmallFont(buffer.conout(), initialSize.X, m_console.isNewW10());
+    buffer.moveWindow(SmallRect(0, 0, 1, 1));
+    buffer.resizeBufferRange(Coord(initialSize.X, BUFFER_LINE_COUNT));
+    const auto largest = GetLargestConsoleWindowSize(buffer.conout());
+    buffer.moveWindow(SmallRect(
+        0, 0,
+        std::min(initialSize.X, largest.X),
+        std::min(initialSize.Y, largest.Y)));
+    buffer.setCursorPosition(Coord(0, 0));
+
+    // For the sake of the color translation heuristic, set the console color
+    // to LtGray-on-Black.
+    buffer.setTextAttribute(Win32ConsoleBuffer::kDefaultAttributes);
+    buffer.clearAllLines(m_consoleBuffer->bufferInfo());
+
+    m_consoleBuffer = nullptr;
+}
+
+Scraper::~Scraper()
+{
+}
+
+// Whether or not the agent is frozen on entry, it will be frozen on exit.
+void Scraper::resizeWindow(Win32ConsoleBuffer &buffer,
+                           Coord newSize,
+                           ConsoleScreenBufferInfo &finalInfoOut)
+{
+    m_consoleBuffer = &buffer;
+    m_ptySize = newSize;
+    syncConsoleContentAndSize(true, finalInfoOut);
+    m_consoleBuffer = nullptr;
+}
+
+// This function may freeze the agent, but it will not unfreeze it.
+void Scraper::scrapeBuffer(Win32ConsoleBuffer &buffer,
+                           ConsoleScreenBufferInfo &finalInfoOut)
+{
+    m_consoleBuffer = &buffer;
+    syncConsoleContentAndSize(false, finalInfoOut);
+    m_consoleBuffer = nullptr;
+}
+
+void Scraper::resetConsoleTracking(
+    Terminal::SendClearFlag sendClear, int64_t scrapedLineCount)
+{
+    for (ConsoleLine &line : m_bufferData) {
+        line.reset();
+    }
+    m_syncRow = -1;
+    m_scrapedLineCount = scrapedLineCount;
+    m_scrolledCount = 0;
+    m_maxBufferedLine = -1;
+    m_dirtyWindowTop = -1;
+    m_dirtyLineCount = 0;
+    m_terminal->reset(sendClear, m_scrapedLineCount);
+}
+
+// Detect window movement.  If the window moves down (presumably as a
+// result of scrolling), then assume that all screen buffer lines down to
+// the bottom of the window are dirty.
+void Scraper::markEntireWindowDirty(const SmallRect &windowRect)
+{
+    m_dirtyLineCount = std::max(m_dirtyLineCount,
+                                windowRect.top() + windowRect.height());
+}
+
+// Scan the screen buffer and advance the dirty line count when we find
+// non-empty lines.
+void Scraper::scanForDirtyLines(const SmallRect &windowRect)
+{
+    const int w = m_readBuffer.rect().width();
+    ASSERT(m_dirtyLineCount >= 1);
+    const CHAR_INFO *const prevLine =
+        m_readBuffer.lineData(m_dirtyLineCount - 1);
+    WORD prevLineAttr = prevLine[w - 1].Attributes;
+    const int stopLine = windowRect.top() + windowRect.height();
+
+    for (int line = m_dirtyLineCount; line < stopLine; ++line) {
+        const CHAR_INFO *lineData = m_readBuffer.lineData(line);
+        for (int col = 0; col < w; ++col) {
+            const WORD colAttr = lineData[col].Attributes;
+            if (lineData[col].Char.UnicodeChar != L' ' ||
+                    colAttr != prevLineAttr) {
+                m_dirtyLineCount = line + 1;
+                break;
+            }
+        }
+        prevLineAttr = lineData[w - 1].Attributes;
+    }
+}
+
+// Clear lines in the line buffer.  The `firstRow` parameter is in
+// screen-buffer coordinates.
+void Scraper::clearBufferLines(
+        const int firstRow,
+        const int count)
+{
+    ASSERT(!m_directMode);
+    for (int row = firstRow; row < firstRow + count; ++row) {
+        const int64_t bufLine = row + m_scrolledCount;
+        m_maxBufferedLine = std::max(m_maxBufferedLine, bufLine);
+        m_bufferData[bufLine % BUFFER_LINE_COUNT].blank(
+            Win32ConsoleBuffer::kDefaultAttributes);
+    }
+}
+
+static bool cursorInWindow(const ConsoleScreenBufferInfo &info)
+{
+    return info.dwCursorPosition.Y >= info.srWindow.Top &&
+           info.dwCursorPosition.Y <= info.srWindow.Bottom;
+}
+
+void Scraper::resizeImpl(const ConsoleScreenBufferInfo &origInfo)
+{
+    ASSERT(m_console.frozen());
+    const int cols = m_ptySize.X;
+    const int rows = m_ptySize.Y;
+    Coord finalBufferSize;
+
+    {
+        //
+        // To accommodate Windows 10, erase all lines up to the top of the
+        // visible window.  It's hard to tell whether this is strictly
+        // necessary.  It ensures that the sync marker won't move downward,
+        // and it ensures that we won't repeat lines that have already scrolled
+        // up into the scrollback.
+        //
+        // It *is* possible for these blank lines to reappear in the visible
+        // window (e.g. if the window is made taller), but because we blanked
+        // the lines in the line buffer, we still don't output them again.
+        //
+        const Coord origBufferSize = origInfo.bufferSize();
+        const SmallRect origWindowRect = origInfo.windowRect();
+
+        if (m_directMode) {
+            for (ConsoleLine &line : m_bufferData) {
+                line.reset();
+            }
+        } else {
+            m_consoleBuffer->clearLines(0, origWindowRect.Top, origInfo);
+            clearBufferLines(0, origWindowRect.Top);
+            if (m_syncRow != -1) {
+                createSyncMarker(std::min(
+                    m_syncRow,
+                    BUFFER_LINE_COUNT - rows
+                                      - SYNC_MARKER_LEN
+                                      - SYNC_MARKER_MARGIN));
+            }
+        }
+
+        finalBufferSize = Coord(
+            cols,
+            // If there was previously no scrollback (e.g. a full-screen app
+            // in direct mode) and we're reducing the window height, then
+            // reduce the console buffer's height too.
+            (origWindowRect.height() == origBufferSize.Y)
+                ? rows
+                : std::max<int>(rows, origBufferSize.Y));
+
+        // Reset the console font size.  We need to do this before shrinking
+        // the window, because we might need to make the font bigger to permit
+        // a smaller window width.  Making the font smaller could expand the
+        // screen buffer, which would hang the conhost process in the
+        // Windows 10 (10240 build) if the console selection is in progress, so
+        // unfreeze it first.
+        m_console.setFrozen(false);
+        setSmallFont(m_consoleBuffer->conout(), cols, m_console.isNewW10());
+    }
+
+    // We try to make the font small enough so that the entire screen buffer
+    // fits on the monitor, but it can't be guaranteed.
+    const auto largest =
+        GetLargestConsoleWindowSize(m_consoleBuffer->conout());
+    const short visibleCols = std::min<short>(cols, largest.X);
+    const short visibleRows = std::min<short>(rows, largest.Y);
+
+    {
+        // Make the window small enough.  We want the console frozen during
+        // this step so we don't accidentally move the window above the cursor.
+        m_console.setFrozen(true);
+        const auto info = m_consoleBuffer->bufferInfo();
+        const auto &bufferSize = info.dwSize;
+        const int tmpWindowWidth = std::min(bufferSize.X, visibleCols);
+        const int tmpWindowHeight = std::min(bufferSize.Y, visibleRows);
+        SmallRect tmpWindowRect(
+            0,
+            std::min<int>(bufferSize.Y - tmpWindowHeight,
+                          info.windowRect().Top),
+            tmpWindowWidth,
+            tmpWindowHeight);
+        if (cursorInWindow(info)) {
+            tmpWindowRect = tmpWindowRect.ensureLineIncluded(
+                info.cursorPosition().Y);
+        }
+        m_consoleBuffer->moveWindow(tmpWindowRect);
+    }
+
+    {
+        // Resize the buffer to the final desired size.
+        m_console.setFrozen(false);
+        m_consoleBuffer->resizeBufferRange(finalBufferSize);
+    }
+
+    {
+        // Expand the window to its full size.
+        m_console.setFrozen(true);
+        const ConsoleScreenBufferInfo info = m_consoleBuffer->bufferInfo();
+
+        SmallRect finalWindowRect(
+            0,
+            std::min<int>(info.bufferSize().Y - visibleRows,
+                          info.windowRect().Top),
+            visibleCols,
+            visibleRows);
+
+        //
+        // Once a line in the screen buffer is "dirty", it should stay visible
+        // in the console window, so that we continue to update its content in
+        // the terminal.  This code is particularly (only?) necessary on
+        // Windows 10, where making the buffer wider can rewrap lines and move
+        // the console window upward.
+        //
+        if (!m_directMode && m_dirtyLineCount > finalWindowRect.Bottom + 1) {
+            // In theory, we avoid ensureLineIncluded, because, a massive
+            // amount of output could have occurred while the console was
+            // unfrozen, so that the *top* of the window is now below the
+            // dirtiest tracked line.
+            finalWindowRect = SmallRect(
+                0, m_dirtyLineCount - visibleRows,
+                visibleCols, visibleRows);
+        }
+
+        // Highest priority constraint: ensure that the cursor remains visible.
+        if (cursorInWindow(info)) {
+            finalWindowRect = finalWindowRect.ensureLineIncluded(
+                info.cursorPosition().Y);
+        }
+
+        m_consoleBuffer->moveWindow(finalWindowRect);
+        m_dirtyWindowTop = finalWindowRect.Top;
+    }
+
+    ASSERT(m_console.frozen());
+}
+
+void Scraper::syncConsoleContentAndSize(
+    bool forceResize,
+    ConsoleScreenBufferInfo &finalInfoOut)
+{
+    // We'll try to avoid freezing the console by reading large chunks (or
+    // all!) of the screen buffer without otherwise attempting to synchronize
+    // with the console application.  We can only do this on Windows 10 and up
+    // because:
+    //  - Prior to Windows 8, the size of a ReadConsoleOutputW call was limited
+    //    by the ~32KB RPC buffer.
+    //  - Prior to Windows 10, an out-of-range read region crashes the caller.
+    //    (See misc/WindowsBugCrashReader.cc.)
+    //
+    if (!m_console.isNewW10() || forceResize) {
+        m_console.setFrozen(true);
+    }
+
+    const ConsoleScreenBufferInfo info = m_consoleBuffer->bufferInfo();
+    bool cursorVisible = true;
+    CONSOLE_CURSOR_INFO cursorInfo = {};
+    if (!GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo)) {
+        trace("GetConsoleCursorInfo failed");
+    } else {
+        cursorVisible = cursorInfo.bVisible != 0;
+    }
+
+    // If an app resizes the buffer height, then we enter "direct mode", where
+    // we stop trying to track incremental console changes.
+    const bool newDirectMode = (info.bufferSize().Y != BUFFER_LINE_COUNT);
+    if (newDirectMode != m_directMode) {
+        trace("Entering %s mode", newDirectMode ? "direct" : "scrolling");
+        resetConsoleTracking(Terminal::SendClear,
+                             newDirectMode ? 0 : info.windowRect().top());
+        m_directMode = newDirectMode;
+
+        // When we switch from direct->scrolling mode, make sure the console is
+        // the right size.
+        if (!m_directMode) {
+            m_console.setFrozen(true);
+            forceResize = true;
+        }
+    }
+
+    if (m_directMode) {
+        // In direct-mode, resizing the console redraws the terminal, so do it
+        // before scraping.
+        if (forceResize) {
+            resizeImpl(info);
+        }
+        directScrapeOutput(info, cursorVisible);
+    } else {
+        if (!m_console.frozen()) {
+            if (!scrollingScrapeOutput(info, cursorVisible, true)) {
+                m_console.setFrozen(true);
+            }
+        }
+        if (m_console.frozen()) {
+            scrollingScrapeOutput(info, cursorVisible, false);
+        }
+        // In scrolling mode, we want to scrape before resizing, because we'll
+        // erase everything in the console buffer up to the top of the console
+        // window.
+        if (forceResize) {
+            resizeImpl(info);
+        }
+    }
+
+    finalInfoOut = forceResize ? m_consoleBuffer->bufferInfo() : info;
+}
+
+// Try to match Windows' behavior w.r.t. to the LVB attribute flags.  In some
+// situations, Windows ignores the LVB flags on a character cell because of
+// backwards compatibility -- apparently some programs set the flags without
+// intending to enable reverse-video or underscores.
+//
+// [rprichard 2017-01-15] I haven't actually noticed any old programs that need
+// this treatment -- the motivation for this function comes from the MSDN
+// documentation for SetConsoleMode and ENABLE_LVB_GRID_WORLDWIDE.
+WORD Scraper::attributesMask()
+{
+    const auto WINPTY_ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4u;
+    const auto WINPTY_ENABLE_LVB_GRID_WORLDWIDE          = 0x10u;
+    const auto WINPTY_COMMON_LVB_REVERSE_VIDEO           = 0x4000u;
+    const auto WINPTY_COMMON_LVB_UNDERSCORE              = 0x8000u;
+
+    const auto cp = GetConsoleOutputCP();
+    const auto isCjk = (cp == 932 || cp == 936 || cp == 949 || cp == 950);
+
+    const DWORD outputMode = [this]{
+        ASSERT(this->m_consoleBuffer != nullptr);
+        DWORD mode = 0;
+        if (!GetConsoleMode(this->m_consoleBuffer->conout(), &mode)) {
+            mode = 0;
+        }
+        return mode;
+    }();
+    const bool hasEnableLvbGridWorldwide =
+        (outputMode & WINPTY_ENABLE_LVB_GRID_WORLDWIDE) != 0;
+    const bool hasEnableVtProcessing =
+        (outputMode & WINPTY_ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;
+
+    // The new Windows 10 console (as of 14393) seems to respect
+    // COMMON_LVB_REVERSE_VIDEO even in CP437 w/o the other enabling modes, so
+    // try to match that behavior.
+    const auto isReverseSupported =
+        isCjk || hasEnableLvbGridWorldwide || hasEnableVtProcessing || m_console.isNewW10();
+    const auto isUnderscoreSupported =
+        isCjk || hasEnableLvbGridWorldwide || hasEnableVtProcessing;
+
+    WORD mask = ~0;
+    if (!isReverseSupported)    { mask &= ~WINPTY_COMMON_LVB_REVERSE_VIDEO; }
+    if (!isUnderscoreSupported) { mask &= ~WINPTY_COMMON_LVB_UNDERSCORE; }
+    return mask;
+}
+
+void Scraper::directScrapeOutput(const ConsoleScreenBufferInfo &info,
+                                 bool consoleCursorVisible)
+{
+    const SmallRect windowRect = info.windowRect();
+
+    const SmallRect scrapeRect(
+        windowRect.left(), windowRect.top(),
+        std::min<SHORT>(std::min(windowRect.width(), m_ptySize.X),
+                        MAX_CONSOLE_WIDTH),
+        std::min<SHORT>(std::min(windowRect.height(), m_ptySize.Y),
+                        BUFFER_LINE_COUNT));
+    const int w = scrapeRect.width();
+    const int h = scrapeRect.height();
+
+    const Coord cursor = info.cursorPosition();
+    const bool showTerminalCursor =
+        consoleCursorVisible && scrapeRect.contains(cursor);
+    const int cursorColumn = !showTerminalCursor ? -1 : cursor.X - scrapeRect.Left;
+    const int cursorLine = !showTerminalCursor ? -1 : cursor.Y - scrapeRect.Top;
+
+    if (!showTerminalCursor) {
+        m_terminal->hideTerminalCursor();
+    }
+
+    largeConsoleRead(m_readBuffer, *m_consoleBuffer, scrapeRect, attributesMask());
+
+    for (int line = 0; line < h; ++line) {
+        const CHAR_INFO *const curLine =
+            m_readBuffer.lineData(scrapeRect.top() + line);
+        ConsoleLine &bufLine = m_bufferData[line];
+        if (bufLine.detectChangeAndSetLine(curLine, w)) {
+            const int lineCursorColumn =
+                line == cursorLine ? cursorColumn : -1;
+            m_terminal->sendLine(line, curLine, w, lineCursorColumn);
+        }
+    }
+
+    if (showTerminalCursor) {
+        m_terminal->showTerminalCursor(cursorColumn, cursorLine);
+    }
+}
+
+bool Scraper::scrollingScrapeOutput(const ConsoleScreenBufferInfo &info,
+                                    bool consoleCursorVisible,
+                                    bool tentative)
+{
+    const Coord cursor = info.cursorPosition();
+    const SmallRect windowRect = info.windowRect();
+
+    if (m_syncRow != -1) {
+        // If a synchronizing marker was placed into the history, look for it
+        // and adjust the scroll count.
+        const int markerRow = findSyncMarker();
+        if (markerRow == -1) {
+            if (tentative) {
+                // I *think* it's possible to keep going, but it's simple to
+                // bail out.
+                return false;
+            }
+            // Something has happened.  Reset the terminal.
+            trace("Sync marker has disappeared -- resetting the terminal"
+                  " (m_syncCounter=%u)",
+                  m_syncCounter);
+            resetConsoleTracking(Terminal::SendClear, windowRect.top());
+        } else if (markerRow != m_syncRow) {
+            ASSERT(markerRow < m_syncRow);
+            m_scrolledCount += (m_syncRow - markerRow);
+            m_syncRow = markerRow;
+            // If the buffer has scrolled, then the entire window is dirty.
+            markEntireWindowDirty(windowRect);
+        }
+    }
+
+    // Creating a new sync row requires clearing part of the console buffer, so
+    // avoid doing it if there's already a sync row that's good enough.
+    const int newSyncRow =
+        static_cast<int>(windowRect.top()) - SYNC_MARKER_LEN - SYNC_MARKER_MARGIN;
+    const bool shouldCreateSyncRow =
+        newSyncRow >= m_syncRow + SYNC_MARKER_LEN + SYNC_MARKER_MARGIN;
+    if (tentative && shouldCreateSyncRow) {
+        // It's difficult even in principle to put down a new marker if the
+        // console can scroll an arbitrarily amount while we're writing.
+        return false;
+    }
+
+    // Update the dirty line count:
+    //  - If the window has moved, the entire window is dirty.
+    //  - Everything up to the cursor is dirty.
+    //  - All lines above the window are dirty.
+    //  - Any non-blank lines are dirty.
+    if (m_dirtyWindowTop != -1) {
+        if (windowRect.top() > m_dirtyWindowTop) {
+            // The window has moved down, presumably as a result of scrolling.
+            markEntireWindowDirty(windowRect);
+        } else if (windowRect.top() < m_dirtyWindowTop) {
+            if (tentative) {
+                // I *think* it's possible to keep going, but it's simple to
+                // bail out.
+                return false;
+            }
+            // The window has moved upward.  This is generally not expected to
+            // happen, but the CMD/PowerShell CLS command will move the window
+            // to the top as part of clearing everything else in the console.
+            trace("Window moved upward -- resetting the terminal"
+                  " (m_syncCounter=%u)",
+                  m_syncCounter);
+            resetConsoleTracking(Terminal::SendClear, windowRect.top());
+        }
+    }
+    m_dirtyWindowTop = windowRect.top();
+    m_dirtyLineCount = std::max(m_dirtyLineCount, cursor.Y + 1);
+    m_dirtyLineCount = std::max(m_dirtyLineCount, (int)windowRect.top());
+
+    // There will be at least one dirty line, because there is a cursor.
+    ASSERT(m_dirtyLineCount >= 1);
+
+    // The first line to scrape, in virtual line coordinates.
+    const int64_t firstVirtLine = std::min(m_scrapedLineCount,
+                                           windowRect.top() + m_scrolledCount);
+
+    // Read all the data we will need from the console.  Start reading with the
+    // first line to scrape, but adjust the the read area upward to account for
+    // scanForDirtyLines' need to read the previous attribute.  Read to the
+    // bottom of the window.  (It's not clear to me whether the
+    // m_dirtyLineCount adjustment here is strictly necessary.  It isn't
+    // necessary so long as the cursor is inside the current window.)
+    const int firstReadLine = std::min<int>(firstVirtLine - m_scrolledCount,
+                                            m_dirtyLineCount - 1);
+    const int stopReadLine = std::max(windowRect.top() + windowRect.height(),
+                                      m_dirtyLineCount);
+    ASSERT(firstReadLine >= 0 && stopReadLine > firstReadLine);
+    largeConsoleRead(m_readBuffer,
+                     *m_consoleBuffer,
+                     SmallRect(0, firstReadLine,
+                               std::min<SHORT>(info.bufferSize().X,
+                                               MAX_CONSOLE_WIDTH),
+                               stopReadLine - firstReadLine),
+                     attributesMask());
+
+    // If we're scraping the buffer without freezing it, we have to query the
+    // buffer position data separately from the buffer content, so the two
+    // could easily be out-of-sync.  If they *are* out-of-sync, abort the
+    // scrape operation and restart it frozen.  (We may have updated the
+    // dirty-line high-water-mark, but that should be OK.)
+    if (tentative) {
+        const auto infoCheck = m_consoleBuffer->bufferInfo();
+        if (info.bufferSize() != infoCheck.bufferSize() ||
+                info.windowRect() != infoCheck.windowRect() ||
+                info.cursorPosition() != infoCheck.cursorPosition()) {
+            return false;
+        }
+        if (m_syncRow != -1 && m_syncRow != findSyncMarker()) {
+            return false;
+        }
+    }
+
+    if (shouldCreateSyncRow) {
+        ASSERT(!tentative);
+        createSyncMarker(newSyncRow);
+    }
+
+    // At this point, we're finished interacting (reading or writing) the
+    // console, and we just need to convert our collected data into terminal
+    // output.
+
+    scanForDirtyLines(windowRect);
+
+    // Note that it's possible for all the lines on the current window to
+    // be non-dirty.
+
+    // The line to stop scraping at, in virtual line coordinates.
+    const int64_t stopVirtLine =
+        std::min(m_dirtyLineCount, windowRect.top() + windowRect.height()) +
+            m_scrolledCount;
+
+    const bool showTerminalCursor =
+        consoleCursorVisible && windowRect.contains(cursor);
+    const int64_t cursorLine = !showTerminalCursor ? -1 : cursor.Y + m_scrolledCount;
+    const int cursorColumn = !showTerminalCursor ? -1 : cursor.X;
+
+    if (!showTerminalCursor) {
+        m_terminal->hideTerminalCursor();
+    }
+
+    bool sawModifiedLine = false;
+
+    const int w = m_readBuffer.rect().width();
+    for (int64_t line = firstVirtLine; line < stopVirtLine; ++line) {
+        const CHAR_INFO *curLine =
+            m_readBuffer.lineData(line - m_scrolledCount);
+        ConsoleLine &bufLine = m_bufferData[line % BUFFER_LINE_COUNT];
+        if (line > m_maxBufferedLine) {
+            m_maxBufferedLine = line;
+            sawModifiedLine = true;
+        }
+        if (sawModifiedLine) {
+            bufLine.setLine(curLine, w);
+        } else {
+            sawModifiedLine = bufLine.detectChangeAndSetLine(curLine, w);
+        }
+        if (sawModifiedLine) {
+            const int lineCursorColumn =
+                line == cursorLine ? cursorColumn : -1;
+            m_terminal->sendLine(line, curLine, w, lineCursorColumn);
+        }
+    }
+
+    m_scrapedLineCount = windowRect.top() + m_scrolledCount;
+
+    if (showTerminalCursor) {
+        m_terminal->showTerminalCursor(cursorColumn, cursorLine);
+    }
+
+    return true;
+}
+
+void Scraper::syncMarkerText(CHAR_INFO (&output)[SYNC_MARKER_LEN])
+{
+    // XXX: The marker text generated here could easily collide with ordinary
+    // console output.  Does it make sense to try to avoid the collision?
+    char str[SYNC_MARKER_LEN + 1];
+    winpty_snprintf(str, "S*Y*N*C*%08x", m_syncCounter);
+    for (int i = 0; i < SYNC_MARKER_LEN; ++i) {
+        output[i].Char.UnicodeChar = str[i];
+        output[i].Attributes = 7;
+    }
+}
+
+int Scraper::findSyncMarker()
+{
+    ASSERT(m_syncRow >= 0);
+    CHAR_INFO marker[SYNC_MARKER_LEN];
+    CHAR_INFO column[BUFFER_LINE_COUNT];
+    syncMarkerText(marker);
+    SmallRect rect(0, 0, 1, m_syncRow + SYNC_MARKER_LEN);
+    m_consoleBuffer->read(rect, column);
+    int i;
+    for (i = m_syncRow; i >= 0; --i) {
+        int j;
+        for (j = 0; j < SYNC_MARKER_LEN; ++j) {
+            if (column[i + j].Char.UnicodeChar != marker[j].Char.UnicodeChar)
+                break;
+        }
+        if (j == SYNC_MARKER_LEN)
+            return i;
+    }
+    return -1;
+}
+
+void Scraper::createSyncMarker(int row)
+{
+    ASSERT(row >= 1);
+
+    // Clear the lines around the marker to ensure that Windows 10's rewrapping
+    // does not affect the marker.
+    m_consoleBuffer->clearLines(row - 1, SYNC_MARKER_LEN + 1,
+                                m_consoleBuffer->bufferInfo());
+
+    // Write a new marker.
+    m_syncCounter++;
+    CHAR_INFO marker[SYNC_MARKER_LEN];
+    syncMarkerText(marker);
+    m_syncRow = row;
+    SmallRect markerRect(0, m_syncRow, 1, SYNC_MARKER_LEN);
+    m_consoleBuffer->write(markerRect, marker);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Scraper.h b/node_modules/node-pty/deps/winpty/src/agent/Scraper.h
new file mode 100644 (file)
index 0000000..9c10d80
--- /dev/null
@@ -0,0 +1,103 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_SCRAPER_H
+#define AGENT_SCRAPER_H
+
+#include <windows.h>
+
+#include <stdint.h>
+
+#include <memory>
+#include <vector>
+
+#include "ConsoleLine.h"
+#include "Coord.h"
+#include "LargeConsoleRead.h"
+#include "SmallRect.h"
+#include "Terminal.h"
+
+class ConsoleScreenBufferInfo;
+class Win32Console;
+class Win32ConsoleBuffer;
+
+// We must be able to issue a single ReadConsoleOutputW call of
+// MAX_CONSOLE_WIDTH characters, and a single read of approximately several
+// hundred fewer characters than BUFFER_LINE_COUNT.
+const int BUFFER_LINE_COUNT = 3000;
+const int MAX_CONSOLE_WIDTH = 2500;
+const int MAX_CONSOLE_HEIGHT = 2000;
+const int SYNC_MARKER_LEN = 16;
+const int SYNC_MARKER_MARGIN = 200;
+
+class Scraper {
+public:
+    Scraper(
+        Win32Console &console,
+        Win32ConsoleBuffer &buffer,
+        std::unique_ptr<Terminal> terminal,
+        Coord initialSize);
+    ~Scraper();
+    void resizeWindow(Win32ConsoleBuffer &buffer,
+                      Coord newSize,
+                      ConsoleScreenBufferInfo &finalInfoOut);
+    void scrapeBuffer(Win32ConsoleBuffer &buffer,
+                      ConsoleScreenBufferInfo &finalInfoOut);
+    Terminal &terminal() { return *m_terminal; }
+
+private:
+    void resetConsoleTracking(
+        Terminal::SendClearFlag sendClear, int64_t scrapedLineCount);
+    void markEntireWindowDirty(const SmallRect &windowRect);
+    void scanForDirtyLines(const SmallRect &windowRect);
+    void clearBufferLines(int firstRow, int count);
+    void resizeImpl(const ConsoleScreenBufferInfo &origInfo);
+    void syncConsoleContentAndSize(bool forceResize,
+                                   ConsoleScreenBufferInfo &finalInfoOut);
+    WORD attributesMask();
+    void directScrapeOutput(const ConsoleScreenBufferInfo &info,
+                            bool consoleCursorVisible);
+    bool scrollingScrapeOutput(const ConsoleScreenBufferInfo &info,
+                               bool consoleCursorVisible,
+                               bool tentative);
+    void syncMarkerText(CHAR_INFO (&output)[SYNC_MARKER_LEN]);
+    int findSyncMarker();
+    void createSyncMarker(int row);
+
+private:
+    Win32Console &m_console;
+    Win32ConsoleBuffer *m_consoleBuffer = nullptr;
+    std::unique_ptr<Terminal> m_terminal;
+
+    int m_syncRow = -1;
+    unsigned int m_syncCounter = 0;
+
+    bool m_directMode = false;
+    Coord m_ptySize;
+    int64_t m_scrapedLineCount = 0;
+    int64_t m_scrolledCount = 0;
+    int64_t m_maxBufferedLine = -1;
+    LargeConsoleReadBuffer m_readBuffer;
+    std::vector<ConsoleLine> m_bufferData;
+    int m_dirtyWindowTop = -1;
+    int m_dirtyLineCount = 0;
+};
+
+#endif // AGENT_SCRAPER_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/SimplePool.h b/node_modules/node-pty/deps/winpty/src/agent/SimplePool.h
new file mode 100644 (file)
index 0000000..41ff94a
--- /dev/null
@@ -0,0 +1,75 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef SIMPLE_POOL_H
+#define SIMPLE_POOL_H
+
+#include <stdlib.h>
+
+#include <vector>
+
+#include "../shared/WinptyAssert.h"
+
+template <typename T, size_t chunkSize>
+class SimplePool {
+public:
+    ~SimplePool();
+    T *alloc();
+    void clear();
+private:
+    struct Chunk {
+        size_t count;
+        T *data;
+    };
+    std::vector<Chunk> m_chunks;
+};
+
+template <typename T, size_t chunkSize>
+SimplePool<T, chunkSize>::~SimplePool() {
+    clear();
+}
+
+template <typename T, size_t chunkSize>
+void SimplePool<T, chunkSize>::clear() {
+    for (size_t ci = 0; ci < m_chunks.size(); ++ci) {
+        Chunk &chunk = m_chunks[ci];
+        for (size_t ti = 0; ti < chunk.count; ++ti) {
+            chunk.data[ti].~T();
+        }
+        free(chunk.data);
+    }
+    m_chunks.clear();
+}
+
+template <typename T, size_t chunkSize>
+T *SimplePool<T, chunkSize>::alloc() {
+    if (m_chunks.empty() || m_chunks.back().count == chunkSize) {
+        T *newData = reinterpret_cast<T*>(malloc(sizeof(T) * chunkSize));
+        ASSERT(newData != NULL);
+        Chunk newChunk = { 0, newData };
+        m_chunks.push_back(newChunk);
+    }
+    Chunk &chunk = m_chunks.back();
+    T *ret = &chunk.data[chunk.count++];
+    new (ret) T();
+    return ret;
+}
+
+#endif // SIMPLE_POOL_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/SmallRect.h b/node_modules/node-pty/deps/winpty/src/agent/SmallRect.h
new file mode 100644 (file)
index 0000000..bad0b88
--- /dev/null
@@ -0,0 +1,143 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef SMALLRECT_H
+#define SMALLRECT_H
+
+#include <windows.h>
+
+#include <algorithm>
+#include <string>
+
+#include "../shared/winpty_snprintf.h"
+#include "Coord.h"
+
+struct SmallRect : SMALL_RECT
+{
+    SmallRect()
+    {
+        Left = Right = Top = Bottom = 0;
+    }
+
+    SmallRect(SHORT x, SHORT y, SHORT width, SHORT height)
+    {
+        Left = x;
+        Top = y;
+        Right = x + width - 1;
+        Bottom = y + height - 1;
+    }
+
+    SmallRect(const COORD &topLeft, const COORD &size)
+    {
+        Left = topLeft.X;
+        Top = topLeft.Y;
+        Right = Left + size.X - 1;
+        Bottom = Top + size.Y - 1;
+    }
+
+    SmallRect(const SMALL_RECT &other)
+    {
+        *(SMALL_RECT*)this = other;
+    }
+
+    SmallRect(const SmallRect &other)
+    {
+        *(SMALL_RECT*)this = *(const SMALL_RECT*)&other;
+    }
+
+    SmallRect &operator=(const SmallRect &other)
+    {
+        *(SMALL_RECT*)this = *(const SMALL_RECT*)&other;
+        return *this;
+    }
+
+    bool contains(const SmallRect &other) const
+    {
+        return other.Left >= Left &&
+               other.Right <= Right &&
+               other.Top >= Top &&
+               other.Bottom <= Bottom;
+    }
+
+    bool contains(const Coord &other) const
+    {
+        return other.X >= Left &&
+               other.X <= Right &&
+               other.Y >= Top &&
+               other.Y <= Bottom;
+    }
+
+    SmallRect intersected(const SmallRect &other) const
+    {
+        int x1 = std::max(Left, other.Left);
+        int x2 = std::min(Right, other.Right);
+        int y1 = std::max(Top, other.Top);
+        int y2 = std::min(Bottom, other.Bottom);
+        return SmallRect(x1,
+                         y1,
+                         std::max(0, x2 - x1 + 1),
+                         std::max(0, y2 - y1 + 1));
+    }
+
+    SmallRect ensureLineIncluded(SHORT line) const
+    {
+        const SHORT h = height();
+        if (line < Top) {
+            return SmallRect(Left, line, width(), h);
+        } else if (line > Bottom) {
+            return SmallRect(Left, line - h + 1, width(), h);
+        } else {
+            return *this;
+        }
+    }
+
+    SHORT top() const               { return Top;                       }
+    SHORT left() const              { return Left;                      }
+    SHORT width() const             { return Right - Left + 1;          }
+    SHORT height() const            { return Bottom - Top + 1;          }
+    void setTop(SHORT top)          { Top = top;                        }
+    void setLeft(SHORT left)        { Left = left;                      }
+    void setWidth(SHORT width)      { Right = Left + width - 1;         }
+    void setHeight(SHORT height)    { Bottom = Top + height - 1;        }
+    Coord size() const              { return Coord(width(), height());  }
+
+    bool operator==(const SmallRect &other) const
+    {
+        return Left == other.Left &&
+               Right == other.Right &&
+               Top == other.Top &&
+               Bottom == other.Bottom;
+    }
+
+    bool operator!=(const SmallRect &other) const
+    {
+        return !(*this == other);
+    }
+
+    std::string toString() const
+    {
+        char ret[64];
+        winpty_snprintf(ret, "(x=%d,y=%d,w=%d,h=%d)",
+                        Left, Top, width(), height());
+        return std::string(ret);
+    }
+};
+
+#endif // SMALLRECT_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Terminal.cc b/node_modules/node-pty/deps/winpty/src/agent/Terminal.cc
new file mode 100644 (file)
index 0000000..afa0a36
--- /dev/null
@@ -0,0 +1,535 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "Terminal.h"
+
+#include <windows.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <string>
+
+#include "NamedPipe.h"
+#include "UnicodeEncoding.h"
+#include "../shared/DebugClient.h"
+#include "../shared/WinptyAssert.h"
+#include "../shared/winpty_snprintf.h"
+
+#define CSI "\x1b["
+
+// Work around the old MinGW, which lacks COMMON_LVB_LEADING_BYTE and
+// COMMON_LVB_TRAILING_BYTE.
+const int WINPTY_COMMON_LVB_LEADING_BYTE  = 0x100;
+const int WINPTY_COMMON_LVB_TRAILING_BYTE = 0x200;
+const int WINPTY_COMMON_LVB_REVERSE_VIDEO = 0x4000;
+const int WINPTY_COMMON_LVB_UNDERSCORE    = 0x8000;
+
+const int COLOR_ATTRIBUTE_MASK =
+        FOREGROUND_BLUE |
+        FOREGROUND_GREEN |
+        FOREGROUND_RED |
+        FOREGROUND_INTENSITY |
+        BACKGROUND_BLUE |
+        BACKGROUND_GREEN |
+        BACKGROUND_RED |
+        BACKGROUND_INTENSITY |
+        WINPTY_COMMON_LVB_REVERSE_VIDEO |
+        WINPTY_COMMON_LVB_UNDERSCORE;
+
+const int FLAG_RED    = 1;
+const int FLAG_GREEN  = 2;
+const int FLAG_BLUE   = 4;
+const int FLAG_BRIGHT = 8;
+
+const int BLACK  = 0;
+const int DKGRAY = BLACK | FLAG_BRIGHT;
+const int LTGRAY = FLAG_RED | FLAG_GREEN | FLAG_BLUE;
+const int WHITE  = LTGRAY | FLAG_BRIGHT;
+
+// SGR parameters (Select Graphic Rendition)
+const int SGR_FORE = 30;
+const int SGR_FORE_HI = 90;
+const int SGR_BACK = 40;
+const int SGR_BACK_HI = 100;
+
+namespace {
+
+static void outUInt(std::string &out, unsigned int n)
+{
+    char buf[32];
+    char *pbuf = &buf[32];
+    *(--pbuf) = '\0';
+    do {
+        *(--pbuf) = '0' + n % 10;
+        n /= 10;
+    } while (n != 0);
+    out.append(pbuf);
+}
+
+static void outputSetColorSgrParams(std::string &out, bool isFore, int color)
+{
+    out.push_back(';');
+    const int sgrBase = isFore ? SGR_FORE : SGR_BACK;
+    if (color & FLAG_BRIGHT) {
+        // Some terminals don't support the 9X/10X "intensive" color parameters
+        // (e.g. the Eclipse TM terminal as of this writing).  Those terminals
+        // will quietly ignore a 9X/10X code, and the other terminals will
+        // ignore a 3X/4X code if it's followed by a 9X/10X code.  Therefore,
+        // output a 3X/4X code as a fallback, then override it.
+        const int colorBase = color & ~FLAG_BRIGHT;
+        outUInt(out, sgrBase + colorBase);
+        out.push_back(';');
+        outUInt(out, sgrBase + (SGR_FORE_HI - SGR_FORE) + colorBase);
+    } else {
+        outUInt(out, sgrBase + color);
+    }
+}
+
+static void outputSetColor(std::string &out, int color)
+{
+    int fore = 0;
+    int back = 0;
+    if (color & FOREGROUND_RED)       fore |= FLAG_RED;
+    if (color & FOREGROUND_GREEN)     fore |= FLAG_GREEN;
+    if (color & FOREGROUND_BLUE)      fore |= FLAG_BLUE;
+    if (color & FOREGROUND_INTENSITY) fore |= FLAG_BRIGHT;
+    if (color & BACKGROUND_RED)       back |= FLAG_RED;
+    if (color & BACKGROUND_GREEN)     back |= FLAG_GREEN;
+    if (color & BACKGROUND_BLUE)      back |= FLAG_BLUE;
+    if (color & BACKGROUND_INTENSITY) back |= FLAG_BRIGHT;
+
+    if (color & WINPTY_COMMON_LVB_REVERSE_VIDEO) {
+        // n.b.: The COMMON_LVB_REVERSE_VIDEO flag also swaps
+        // FOREGROUND_INTENSITY and BACKGROUND_INTENSITY.  Tested on
+        // Windows 10 v14393.
+        std::swap(fore, back);
+    }
+
+    // Translate the fore/back colors into terminal escape codes using
+    // a heuristic that works OK with common white-on-black or
+    // black-on-white color schemes.  We don't know which color scheme
+    // the terminal is using.  It is ugly to force white-on-black text
+    // on a black-on-white terminal, and it's even ugly to force the
+    // matching scheme.  It's probably relevant that the default
+    // fore/back terminal colors frequently do not match any of the 16
+    // palette colors.
+
+    // Typical default terminal color schemes (according to palette,
+    // when possible):
+    //  - mintty:               LtGray-on-Black(A)
+    //  - putty:                LtGray-on-Black(A)
+    //  - xterm:                LtGray-on-Black(A)
+    //  - Konsole:              LtGray-on-Black(A)
+    //  - JediTerm/JetBrains:   Black-on-White(B)
+    //  - rxvt:                 Black-on-White(B)
+
+    // If the background is the default color (black), then it will
+    // map to Black(A) or White(B).  If we translate White to White,
+    // then a Black background and a White background in the console
+    // are both White with (B).  Therefore, we should translate White
+    // using SGR 7 (Invert).  The typical finished mapping table for
+    // background grayscale colors is:
+    //
+    //  (A) White => LtGray(fore)
+    //  (A) Black => Black(back)
+    //  (A) LtGray => LtGray
+    //  (A) DkGray => DkGray
+    //
+    //  (B) White => Black(fore)
+    //  (B) Black => White(back)
+    //  (B) LtGray => LtGray
+    //  (B) DkGray => DkGray
+    //
+
+    out.append(CSI "0");
+    if (back == BLACK) {
+        if (fore == LTGRAY) {
+            // The "default" foreground color.  Use the terminal's
+            // default colors.
+        } else if (fore == WHITE) {
+            // Sending the literal color white would behave poorly if
+            // the terminal were black-on-white.  Sending Bold is not
+            // guaranteed to alter the color, but it will make the text
+            // visually distinct, so do that instead.
+            out.append(";1");
+        } else if (fore == DKGRAY) {
+            // Set the foreground color to DkGray(90) with a fallback
+            // of LtGray(37) for terminals that don't handle the 9X SGR
+            // parameters (e.g. Eclipse's TM Terminal as of this
+            // writing).
+            out.append(";37;90");
+        } else {
+            outputSetColorSgrParams(out, true, fore);
+        }
+    } else if (back == WHITE) {
+        // Set the background color using Invert on the default
+        // foreground color, and set the foreground color by setting a
+        // background color.
+
+        // Use the terminal's inverted colors.
+        out.append(";7");
+        if (fore == LTGRAY || fore == BLACK) {
+            // We're likely mapping Console White to terminal LtGray or
+            // Black.  If they are the Console foreground color, then
+            // don't set a terminal foreground color to avoid creating
+            // invisible text.
+        } else {
+            outputSetColorSgrParams(out, false, fore);
+        }
+    } else {
+        // Set the foreground and background to match exactly that in
+        // the Windows console.
+        outputSetColorSgrParams(out, true, fore);
+        outputSetColorSgrParams(out, false, back);
+    }
+    if (fore == back) {
+        // The foreground and background colors are exactly equal, so
+        // attempt to hide the text using the Conceal SGR parameter,
+        // which some terminals support.
+        out.append(";8");
+    }
+    if (color & WINPTY_COMMON_LVB_UNDERSCORE) {
+        out.append(";4");
+    }
+    out.push_back('m');
+}
+
+static inline unsigned int fixSpecialCharacters(unsigned int ch)
+{
+    if (ch <= 0x1b) {
+        switch (ch) {
+            // The Windows Console has a popup window (e.g. that appears with
+            // F7) that is sometimes bordered with box-drawing characters.
+            // With the Japanese and Korean system locales (CP932 and CP949),
+            // the UnicodeChar values for the box-drawing characters are 1
+            // through 6.  Detect this and map the values to the correct
+            // Unicode values.
+            //
+            // N.B. In the English locale, the UnicodeChar values are correct,
+            // and they identify single-line characters rather than
+            // double-line.  In the Chinese Simplified and Traditional locales,
+            // the popups use ASCII characters instead.
+            case 1: return 0x2554; // BOX DRAWINGS DOUBLE DOWN AND RIGHT
+            case 2: return 0x2557; // BOX DRAWINGS DOUBLE DOWN AND LEFT
+            case 3: return 0x255A; // BOX DRAWINGS DOUBLE UP AND RIGHT
+            case 4: return 0x255D; // BOX DRAWINGS DOUBLE UP AND LEFT
+            case 5: return 0x2551; // BOX DRAWINGS DOUBLE VERTICAL
+            case 6: return 0x2550; // BOX DRAWINGS DOUBLE HORIZONTAL
+
+            // Convert an escape character to some other character.  This
+            // conversion only applies to console cells containing an escape
+            // character.  In newer versions of Windows 10 (e.g. 10.0.10586),
+            // the non-legacy console recognizes escape sequences in
+            // WriteConsole and interprets them without writing them to the
+            // cells of the screen buffer.  In that case, the conversion here
+            // does not apply.
+            case 0x1b: return '?';
+        }
+    }
+    return ch;
+}
+
+static inline bool isFullWidthCharacter(const CHAR_INFO *data, int width)
+{
+    if (width < 2) {
+        return false;
+    }
+    return
+        (data[0].Attributes & WINPTY_COMMON_LVB_LEADING_BYTE) &&
+        (data[1].Attributes & WINPTY_COMMON_LVB_TRAILING_BYTE) &&
+        data[0].Char.UnicodeChar == data[1].Char.UnicodeChar;
+}
+
+// Scan to find a single Unicode Scalar Value.  Full-width characters occupy
+// two console cells, and this code also tries to handle UTF-16 surrogate
+// pairs.
+//
+// Windows expands at least some wide characters outside the Basic
+// Multilingual Plane into four cells, such as U+20000:
+//   1. 0xD840, attr=0x107
+//   2. 0xD840, attr=0x207
+//   3. 0xDC00, attr=0x107
+//   4. 0xDC00, attr=0x207
+// Even in the Traditional Chinese locale on Windows 10, this text is rendered
+// as two boxes, but if those boxes are copied-and-pasted, the character is
+// copied correctly.
+static inline void scanUnicodeScalarValue(
+    const CHAR_INFO *data, int width,
+    int &outCellCount, unsigned int &outCharValue)
+{
+    ASSERT(width >= 1);
+
+    const int w1 = isFullWidthCharacter(data, width) ? 2 : 1;
+    const wchar_t c1 = data[0].Char.UnicodeChar;
+
+    if ((c1 & 0xF800) == 0xD800) {
+        // The first cell is either a leading or trailing surrogate pair.
+        if ((c1 & 0xFC00) != 0xD800 ||
+                width <= w1 ||
+                ((data[w1].Char.UnicodeChar & 0xFC00) != 0xDC00)) {
+            // Invalid surrogate pair
+            outCellCount = w1;
+            outCharValue = '?';
+        } else {
+            // Valid surrogate pair
+            outCellCount = w1 + (isFullWidthCharacter(&data[w1], width - w1) ? 2 : 1);
+            outCharValue = decodeSurrogatePair(c1, data[w1].Char.UnicodeChar);
+        }
+    } else {
+        outCellCount = w1;
+        outCharValue = c1;
+    }
+}
+
+} // anonymous namespace
+
+void Terminal::reset(SendClearFlag sendClearFirst, int64_t newLine)
+{
+    if (sendClearFirst == SendClear && !m_plainMode) {
+        // 0m   ==> reset SGR parameters
+        // 1;1H ==> move cursor to top-left position
+        // 2J   ==> clear the entire screen
+        m_output.write(CSI "0m" CSI "1;1H" CSI "2J");
+    }
+    m_remoteLine = newLine;
+    m_remoteColumn = 0;
+    m_lineData.clear();
+    m_cursorHidden = false;
+    m_remoteColor = -1;
+}
+
+void Terminal::sendLine(int64_t line, const CHAR_INFO *lineData, int width,
+                        int cursorColumn)
+{
+    ASSERT(width >= 1);
+
+    moveTerminalToLine(line);
+
+    // If possible, see if we can append to what we've already output for this
+    // line.
+    if (m_lineDataValid) {
+        ASSERT(m_lineData.size() == static_cast<size_t>(m_remoteColumn));
+        if (m_remoteColumn > 0) {
+            // In normal mode, if m_lineData.size() equals `width`, then we
+            // will have trouble outputing the "erase rest of line" command,
+            // which must be output before reaching the end of the line.  In
+            // plain mode, we don't output that command, so we're OK with a
+            // full line.
+            bool okWidth = false;
+            if (m_plainMode) {
+                okWidth = static_cast<size_t>(width) >= m_lineData.size();
+            } else {
+                okWidth = static_cast<size_t>(width) > m_lineData.size();
+            }
+            if (!okWidth ||
+                    memcmp(m_lineData.data(), lineData,
+                           sizeof(CHAR_INFO) * m_lineData.size()) != 0) {
+                m_lineDataValid = false;
+            }
+        }
+    }
+    if (!m_lineDataValid) {
+        // We can't reuse, so we must reset this line.
+        hideTerminalCursor();
+        if (m_plainMode) {
+            // We can't backtrack, so repeat this line.
+            m_output.write("\r\n");
+        } else {
+            m_output.write("\r");
+        }
+        m_lineDataValid = true;
+        m_lineData.clear();
+        m_remoteColumn = 0;
+    }
+
+    std::string &termLine = m_termLineWorkingBuffer;
+    termLine.clear();
+    size_t trimmedLineLength = 0;
+    int trimmedCellCount = m_lineData.size();
+    bool alreadyErasedLine = false;
+
+    int cellCount = 1;
+    for (int i = m_lineData.size(); i < width; i += cellCount) {
+        if (m_outputColor) {
+            int color = lineData[i].Attributes & COLOR_ATTRIBUTE_MASK;
+            if (color != m_remoteColor) {
+                outputSetColor(termLine, color);
+                trimmedLineLength = termLine.size();
+                m_remoteColor = color;
+
+                // All the cells just up to this color change will be output.
+                trimmedCellCount = i;
+            }
+        }
+        unsigned int ch;
+        scanUnicodeScalarValue(&lineData[i], width - i, cellCount, ch);
+        if (ch == ' ') {
+            // Tentatively add this space character.  We'll only output it if
+            // we see something interesting after it.
+            termLine.push_back(' ');
+        } else {
+            if (i + cellCount == width) {
+                // We'd like to erase the line after outputting all non-blank
+                // characters, but this doesn't work if the last cell in the
+                // line is non-blank.  At the point, the cursor is positioned
+                // just past the end of the line, but in many terminals,
+                // issuing a CSI 0K at that point also erases the last cell in
+                // the line.  Work around this behavior by issuing the erase
+                // one character early in that case.
+                if (!m_plainMode) {
+                    termLine.append(CSI "0K"); // Erase from cursor to EOL
+                }
+                alreadyErasedLine = true;
+            }
+            ch = fixSpecialCharacters(ch);
+            char enc[4];
+            int enclen = encodeUtf8(enc, ch);
+            if (enclen == 0) {
+                enc[0] = '?';
+                enclen = 1;
+            }
+            termLine.append(enc, enclen);
+            trimmedLineLength = termLine.size();
+
+            // All the cells up to and including this cell will be output.
+            trimmedCellCount = i + cellCount;
+        }
+    }
+
+    if (cursorColumn != -1 && trimmedCellCount > cursorColumn) {
+        // The line content would run past the cursor, so hide it before we
+        // output.
+        hideTerminalCursor();
+    }
+
+    m_output.write(termLine.data(), trimmedLineLength);
+    if (!alreadyErasedLine && !m_plainMode) {
+        m_output.write(CSI "0K"); // Erase from cursor to EOL
+    }
+
+    ASSERT(trimmedCellCount <= width);
+    m_lineData.insert(m_lineData.end(),
+                      &lineData[m_lineData.size()],
+                      &lineData[trimmedCellCount]);
+    m_remoteColumn = trimmedCellCount;
+}
+
+void Terminal::showTerminalCursor(int column, int64_t line)
+{
+    moveTerminalToLine(line);
+    if (!m_plainMode) {
+        if (m_remoteColumn != column) {
+            char buffer[32];
+            winpty_snprintf(buffer, CSI "%dG", column + 1);
+            m_output.write(buffer);
+            m_lineDataValid = (column == 0);
+            m_lineData.clear();
+            m_remoteColumn = column;
+        }
+        if (m_cursorHidden) {
+            m_output.write(CSI "?25h");
+            m_cursorHidden = false;
+        }
+    }
+}
+
+void Terminal::hideTerminalCursor()
+{
+    if (!m_plainMode) {
+        if (m_cursorHidden) {
+            return;
+        }
+        m_output.write(CSI "?25l");
+        m_cursorHidden = true;
+    }
+}
+
+void Terminal::moveTerminalToLine(int64_t line)
+{
+    if (line == m_remoteLine) {
+        return;
+    }
+
+    // Do not use CPL or CNL.  Konsole 2.5.4 does not support Cursor Previous
+    // Line (CPL) -- there are "Undecodable sequence" errors.  gnome-terminal
+    // 2.32.0 does handle it.  Cursor Next Line (CNL) does nothing if the
+    // cursor is on the last line already.
+
+    hideTerminalCursor();
+
+    if (line < m_remoteLine) {
+        if (m_plainMode) {
+            // We can't backtrack, so instead repeat the lines again.
+            m_output.write("\r\n");
+            m_remoteLine = line;
+        } else {
+            // Backtrack and overwrite previous lines.
+            // CUrsor Up (CUU)
+            char buffer[32];
+            winpty_snprintf(buffer, "\r" CSI "%uA",
+                static_cast<unsigned int>(m_remoteLine - line));
+            m_output.write(buffer);
+            m_remoteLine = line;
+        }
+    } else if (line > m_remoteLine) {
+        while (line > m_remoteLine) {
+            m_output.write("\r\n");
+            m_remoteLine++;
+        }
+    }
+
+    m_lineDataValid = true;
+    m_lineData.clear();
+    m_remoteColumn = 0;
+}
+
+void Terminal::enableMouseMode(bool enabled)
+{
+    if (m_mouseModeEnabled == enabled || m_plainMode) {
+        return;
+    }
+    m_mouseModeEnabled = enabled;
+    if (enabled) {
+        // Start by disabling UTF-8 coordinate mode (1005), just in case we
+        // have a terminal that does not support 1006/1015 modes, and 1005
+        // happens to be enabled.  The UTF-8 coordinates can't be unambiguously
+        // decoded.
+        //
+        // Enable basic mouse support first (1000), then try to switch to
+        // button-move mode (1002), then try full mouse-move mode (1003).
+        // Terminals that don't support a mode will be stuck at the highest
+        // mode they do support.
+        //
+        // Enable encoding mode 1015 first, then try to switch to 1006.  On
+        // some terminals, both modes will be enabled, but 1006 will have
+        // priority.  On other terminals, 1006 wins because it's listed last.
+        //
+        // See misc/MouseInputNotes.txt for details.
+        m_output.write(
+            CSI "?1005l"
+            CSI "?1000h" CSI "?1002h" CSI "?1003h" CSI "?1015h" CSI "?1006h");
+    } else {
+        // Resetting both encoding modes (1006 and 1015) is necessary, but
+        // apparently we only need to use reset on one of the 100[023] modes.
+        // Doing both doesn't hurt.
+        m_output.write(
+            CSI "?1006l" CSI "?1015l" CSI "?1003l" CSI "?1002l" CSI "?1000l");
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Terminal.h b/node_modules/node-pty/deps/winpty/src/agent/Terminal.h
new file mode 100644 (file)
index 0000000..058eb26
--- /dev/null
@@ -0,0 +1,69 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#ifndef TERMINAL_H
+#define TERMINAL_H
+
+#include <windows.h>
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+
+#include "Coord.h"
+
+class NamedPipe;
+
+class Terminal
+{
+public:
+    explicit Terminal(NamedPipe &output, bool plainMode, bool outputColor)
+        : m_output(output), m_plainMode(plainMode), m_outputColor(outputColor)
+    {
+    }
+
+    enum SendClearFlag { OmitClear, SendClear };
+    void reset(SendClearFlag sendClearFirst, int64_t newLine);
+    void sendLine(int64_t line, const CHAR_INFO *lineData, int width,
+                  int cursorColumn);
+    void showTerminalCursor(int column, int64_t line);
+    void hideTerminalCursor();
+
+private:
+    void moveTerminalToLine(int64_t line);
+
+public:
+    void enableMouseMode(bool enabled);
+
+private:
+    NamedPipe &m_output;
+    int64_t m_remoteLine = 0;
+    int m_remoteColumn = 0;
+    bool m_lineDataValid = true;
+    std::vector<CHAR_INFO> m_lineData;
+    bool m_cursorHidden = false;
+    int m_remoteColor = -1;
+    std::string m_termLineWorkingBuffer;
+    bool m_plainMode = false;
+    bool m_outputColor = true;
+    bool m_mouseModeEnabled = false;
+};
+
+#endif // TERMINAL_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/UnicodeEncoding.h b/node_modules/node-pty/deps/winpty/src/agent/UnicodeEncoding.h
new file mode 100644 (file)
index 0000000..6b0de3e
--- /dev/null
@@ -0,0 +1,157 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef UNICODE_ENCODING_H
+#define UNICODE_ENCODING_H
+
+#include <stdint.h>
+
+// Encode the Unicode codepoint with UTF-8.  The buffer must be at least 4
+// bytes in size.
+static inline int encodeUtf8(char *out, uint32_t code) {
+    if (code < 0x80) {
+        out[0] = code;
+        return 1;
+    } else if (code < 0x800) {
+        out[0] = ((code >> 6) & 0x1F) | 0xC0;
+        out[1] = ((code >> 0) & 0x3F) | 0x80;
+        return 2;
+    } else if (code < 0x10000) {
+        if (code >= 0xD800 && code <= 0xDFFF) {
+            // The code points 0xD800 to 0xDFFF are reserved for UTF-16
+            // surrogate pairs and do not have an encoding in UTF-8.
+            return 0;
+        }
+        out[0] = ((code >> 12) & 0x0F) | 0xE0;
+        out[1] = ((code >>  6) & 0x3F) | 0x80;
+        out[2] = ((code >>  0) & 0x3F) | 0x80;
+        return 3;
+    } else if (code < 0x110000) {
+        out[0] = ((code >> 18) & 0x07) | 0xF0;
+        out[1] = ((code >> 12) & 0x3F) | 0x80;
+        out[2] = ((code >>  6) & 0x3F) | 0x80;
+        out[3] = ((code >>  0) & 0x3F) | 0x80;
+        return 4;
+    } else {
+        // Encoding error
+        return 0;
+    }
+}
+
+// Encode the Unicode codepoint with UTF-16.  The buffer must be large enough
+// to hold the output -- either 1 or 2 elements.
+static inline int encodeUtf16(wchar_t *out, uint32_t code) {
+    if (code < 0x10000) {
+        if (code >= 0xD800 && code <= 0xDFFF) {
+            // The code points 0xD800 to 0xDFFF are reserved for UTF-16
+            // surrogate pairs and do not have an encoding in UTF-16.
+            return 0;
+        }
+        out[0] = code;
+        return 1;
+    } else if (code < 0x110000) {
+        code -= 0x10000;
+        out[0] = 0xD800 | (code >> 10);
+        out[1] = 0xDC00 | (code & 0x3FF);
+        return 2;
+    } else {
+        // Encoding error
+        return 0;
+    }
+}
+
+// Return the byte size of a UTF-8 character using the value of the first
+// byte.
+static inline int utf8CharLength(char firstByte) {
+    // This code would probably be faster if it used __builtin_clz.
+    if ((firstByte & 0x80) == 0) {
+        return 1;
+    } else if ((firstByte & 0xE0) == 0xC0) {
+        return 2;
+    } else if ((firstByte & 0xF0) == 0xE0) {
+        return 3;
+    } else if ((firstByte & 0xF8) == 0xF0) {
+        return 4;
+    } else {
+        // Malformed UTF-8.
+        return 0;
+    }
+}
+
+// The pointer must point to 1-4 bytes, as indicated by the first byte.
+// Returns -1 on decoding error.
+static inline uint32_t decodeUtf8(const char *in) {
+    const uint32_t kInvalid = static_cast<uint32_t>(-1);
+    switch (utf8CharLength(in[0])) {
+        case 1: {
+            return in[0];
+        }
+        case 2: {
+            if ((in[1] & 0xC0) != 0x80) {
+                return kInvalid;
+            }
+            uint32_t tmp = 0;
+            tmp = (in[0] & 0x1F) << 6;
+            tmp |= (in[1] & 0x3F);
+            return tmp <= 0x7F ? kInvalid : tmp;
+        }
+        case 3: {
+            if ((in[1] & 0xC0) != 0x80 ||
+                    (in[2] & 0xC0) != 0x80) {
+                return kInvalid;
+            }
+            uint32_t tmp = 0;
+            tmp = (in[0] & 0x0F) << 12;
+            tmp |= (in[1] & 0x3F) << 6;
+            tmp |= (in[2] & 0x3F);
+            if (tmp <= 0x07FF || (tmp >= 0xD800 && tmp <= 0xDFFF)) {
+                return kInvalid;
+            } else {
+                return tmp;
+            }
+        }
+        case 4: {
+            if ((in[1] & 0xC0) != 0x80 ||
+                    (in[2] & 0xC0) != 0x80 ||
+                    (in[3] & 0xC0) != 0x80) {
+                return kInvalid;
+            }
+            uint32_t tmp = 0;
+            tmp = (in[0] & 0x07) << 18;
+            tmp |= (in[1] & 0x3F) << 12;
+            tmp |= (in[2] & 0x3F) << 6;
+            tmp |= (in[3] & 0x3F);
+            if (tmp <= 0xFFFF || tmp > 0x10FFFF) {
+                return kInvalid;
+            } else {
+                return tmp;
+            }
+        }
+        default: {
+            return kInvalid;
+        }
+    }
+}
+
+static inline uint32_t decodeSurrogatePair(wchar_t ch1, wchar_t ch2) {
+    return ((ch1 - 0xD800) << 10) + (ch2 - 0xDC00) + 0x10000;
+}
+
+#endif // UNICODE_ENCODING_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/UnicodeEncodingTest.cc b/node_modules/node-pty/deps/winpty/src/agent/UnicodeEncodingTest.cc
new file mode 100644 (file)
index 0000000..cd4abeb
--- /dev/null
@@ -0,0 +1,189 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+// Encode every code-point using this module and verify that it matches the
+// encoding generated using Windows WideCharToMultiByte.
+
+#include "UnicodeEncoding.h"
+
+#include <windows.h>
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+
+static void correctnessByCode()
+{
+    char mbstr1[4];
+    char mbstr2[4];
+    wchar_t wch[2];
+    for (unsigned int code = 0; code < 0x110000; ++code) {
+
+        // Surrogate pair reserved region.
+        const bool isReserved = (code >= 0xD800 && code <= 0xDFFF);
+
+        int mblen1 = encodeUtf8(mbstr1, code);
+        if (isReserved ? mblen1 != 0 : mblen1 <= 0) {
+            printf("Error: 0x%04X: mblen1=%d\n", code, mblen1);
+            continue;
+        }
+
+        int wlen = encodeUtf16(wch, code);
+        if (isReserved ? wlen != 0 : wlen <= 0) {
+            printf("Error: 0x%04X: wlen=%d\n", code, wlen);
+            continue;
+        }
+
+        if (isReserved) {
+            continue;
+        }
+
+        if (mblen1 != utf8CharLength(mbstr1[0])) {
+            printf("Error: 0x%04X: mblen1=%d, utf8CharLength(mbstr1[0])=%d\n",
+                code, mblen1, utf8CharLength(mbstr1[0]));
+            continue;
+        }
+
+        if (code != decodeUtf8(mbstr1)) {
+            printf("Error: 0x%04X: decodeUtf8(mbstr1)=%u\n",
+                code, decodeUtf8(mbstr1));
+            continue;
+        }
+
+        int mblen2 = WideCharToMultiByte(CP_UTF8, 0, wch, wlen, mbstr2, 4, NULL, NULL);
+        if (mblen1 != mblen2) {
+            printf("Error: 0x%04X: mblen1=%d, mblen2=%d\n", code, mblen1, mblen2);
+            continue;
+        }
+
+        if (memcmp(mbstr1, mbstr2, mblen1) != 0) {
+            printf("Error: 0x%04x: encodings are different\n", code);
+            continue;
+        }
+    }
+}
+
+static const char *encodingStr(char (&output)[128], char (&buf)[4])
+{
+    sprintf(output, "Encoding %02X %02X %02X %02X",
+        static_cast<uint8_t>(buf[0]),
+        static_cast<uint8_t>(buf[1]),
+        static_cast<uint8_t>(buf[2]),
+        static_cast<uint8_t>(buf[3]));
+    return output;
+}
+
+// This test can take a couple of minutes to run.
+static void correctnessByUtf8Encoding()
+{
+    for (uint64_t encoding = 0; encoding <= 0xFFFFFFFF; ++encoding) {
+
+        char mb[4];
+        mb[0] = encoding;
+        mb[1] = encoding >> 8;
+        mb[2] = encoding >> 16;
+        mb[3] = encoding >> 24;
+
+        const int mblen = utf8CharLength(mb[0]);
+        if (mblen == 0) {
+            continue;
+        }
+
+        // Test this module.
+        const uint32_t code1 = decodeUtf8(mb);
+        wchar_t ws1[2] = {};
+        const int wslen1 = encodeUtf16(ws1, code1);
+
+        // Test using Windows.  We can't decode a codepoint directly; we have
+        // to do UTF8->UTF16, then decode the surrogate pair.
+        wchar_t ws2[2] = {};
+        const int wslen2 = MultiByteToWideChar(
+            CP_UTF8, MB_ERR_INVALID_CHARS, mb, mblen, ws2, 2);
+        const uint32_t code2 =
+            (wslen2 == 1 ? ws2[0] :
+             wslen2 == 2 ? decodeSurrogatePair(ws2[0], ws2[1]) :
+             static_cast<uint32_t>(-1));
+
+        // Verify that the two implementations match.
+        char prefix[128];
+        if (code1 != code2) {
+            printf("%s: code1=0x%04x code2=0x%04x\n",
+                encodingStr(prefix, mb),
+                code1, code2);
+            continue;
+        }
+        if (wslen1 != wslen2) {
+            printf("%s: wslen1=%d wslen2=%d\n",
+                encodingStr(prefix, mb),
+                wslen1, wslen2);
+            continue;
+        }
+        if (memcmp(ws1, ws2, wslen1 * sizeof(wchar_t)) != 0) {
+            printf("%s: ws1 != ws2\n", encodingStr(prefix, mb));
+            continue;
+        }
+    }
+}
+
+wchar_t g_wch_TEST[] = { 0xD840, 0xDC00 };
+char g_ch_TEST[4];
+wchar_t *volatile g_pwch = g_wch_TEST;
+char *volatile g_pch = g_ch_TEST;
+unsigned int volatile g_code = 0xA2000;
+
+static void performance()
+{
+    {
+        clock_t start = clock();
+        for (long long i = 0; i < 250000000LL; ++i) {
+            int mblen = WideCharToMultiByte(CP_UTF8, 0, g_pwch, 2, g_pch, 4, NULL, NULL);
+            assert(mblen == 4);
+        }
+        clock_t stop = clock();
+        printf("%.3fns per char\n", (double)(stop - start) / CLOCKS_PER_SEC * 4.0);
+    }
+
+    {
+        clock_t start = clock();
+        for (long long i = 0; i < 3000000000LL; ++i) {
+            int mblen = encodeUtf8(g_pch, g_code);
+            assert(mblen == 4);
+        }
+        clock_t stop = clock();
+        printf("%.3fns per char\n", (double)(stop - start) / CLOCKS_PER_SEC / 3.0);
+    }
+}
+
+int main()
+{
+    printf("Testing correctnessByCode...\n");
+    fflush(stdout);
+    correctnessByCode();
+
+    printf("Testing correctnessByUtf8Encoding... (may take a couple minutes)\n");
+    fflush(stdout);
+    correctnessByUtf8Encoding();
+
+    printf("Testing performance...\n");
+    fflush(stdout);
+    performance();
+
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Win32Console.cc b/node_modules/node-pty/deps/winpty/src/agent/Win32Console.cc
new file mode 100644 (file)
index 0000000..d53de02
--- /dev/null
@@ -0,0 +1,107 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "Win32Console.h"
+
+#include <windows.h>
+#include <wchar.h>
+
+#include <string>
+
+#include "../shared/DebugClient.h"
+#include "../shared/WinptyAssert.h"
+
+Win32Console::Win32Console() : m_titleWorkBuf(16)
+{
+    // The console window must be non-NULL.  It is used for two purposes:
+    //  (1) "Freezing" the console to detect the exact number of lines that
+    //      have scrolled.
+    //  (2) Killing processes attached to the console, by posting a WM_CLOSE
+    //      message to the console window.
+    m_hwnd = GetConsoleWindow();
+    ASSERT(m_hwnd != nullptr);
+}
+
+std::wstring Win32Console::title()
+{
+    while (true) {
+        // Calling GetConsoleTitleW is tricky, because its behavior changed
+        // from XP->Vista, then again from Win7->Win8.  The Vista+Win7 behavior
+        // is especially broken.
+        //
+        // The MSDN documentation documents nSize as the "size of the buffer
+        // pointed to by the lpConsoleTitle parameter, in characters" and the
+        // successful return value as "the length of the console window's
+        // title, in characters."
+        //
+        // On XP, the function returns the title length, AFTER truncation
+        // (excluding the NUL terminator).  If the title is blank, the API
+        // returns 0 and does not NUL-terminate the buffer.  To accommodate
+        // XP, the function must:
+        //  * Terminate the buffer itself.
+        //  * Double the size of the title buffer in a loop.
+        //
+        // On Vista and up, the function returns the non-truncated title
+        // length (excluding the NUL terminator).
+        //
+        // On Vista and Windows 7, there is a bug where the buffer size is
+        // interpreted as a byte count rather than a wchar_t count.  To
+        // work around this, we must pass GetConsoleTitleW a buffer that is
+        // twice as large as what is actually needed.
+        //
+        // See misc/*/Test_GetConsoleTitleW.cc for tests demonstrating Windows'
+        // behavior.
+
+        DWORD count = GetConsoleTitleW(m_titleWorkBuf.data(),
+                                       m_titleWorkBuf.size());
+        const size_t needed = (count + 1) * sizeof(wchar_t);
+        if (m_titleWorkBuf.size() < needed) {
+            m_titleWorkBuf.resize(needed);
+            continue;
+        }
+        m_titleWorkBuf[count] = L'\0';
+        return m_titleWorkBuf.data();
+    }
+}
+
+void Win32Console::setTitle(const std::wstring &title)
+{
+    if (!SetConsoleTitleW(title.c_str())) {
+        trace("SetConsoleTitleW failed");
+    }
+}
+
+void Win32Console::setFrozen(bool frozen) {
+    const int SC_CONSOLE_MARK = 0xFFF2;
+    const int SC_CONSOLE_SELECT_ALL = 0xFFF5;
+    if (frozen == m_frozen) {
+        // Do nothing.
+    } else if (frozen) {
+        // Enter selection mode by activating either Mark or SelectAll.
+        const int command = m_freezeUsesMark ? SC_CONSOLE_MARK
+                                             : SC_CONSOLE_SELECT_ALL;
+        SendMessage(m_hwnd, WM_SYSCOMMAND, command, 0);
+        m_frozen = true;
+    } else {
+        // Send Escape to cancel the selection.
+        SendMessage(m_hwnd, WM_CHAR, 27, 0x00010001);
+        m_frozen = false;
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Win32Console.h b/node_modules/node-pty/deps/winpty/src/agent/Win32Console.h
new file mode 100644 (file)
index 0000000..ed83877
--- /dev/null
@@ -0,0 +1,67 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_WIN32_CONSOLE_H
+#define AGENT_WIN32_CONSOLE_H
+
+#include <windows.h>
+
+#include <string>
+#include <vector>
+
+class Win32Console
+{
+public:
+    class FreezeGuard {
+    public:
+        FreezeGuard(Win32Console &console, bool frozen) :
+                m_console(console), m_previous(console.frozen()) {
+            m_console.setFrozen(frozen);
+        }
+        ~FreezeGuard() {
+            m_console.setFrozen(m_previous);
+        }
+        FreezeGuard(const FreezeGuard &other) = delete;
+        FreezeGuard &operator=(const FreezeGuard &other) = delete;
+    private:
+        Win32Console &m_console;
+        bool m_previous;
+    };
+
+    Win32Console();
+
+    HWND hwnd() { return m_hwnd; }
+    std::wstring title();
+    void setTitle(const std::wstring &title);
+    void setFreezeUsesMark(bool useMark) { m_freezeUsesMark = useMark; }
+    void setNewW10(bool isNewW10) { m_isNewW10 = isNewW10; }
+    bool isNewW10() { return m_isNewW10; }
+    void setFrozen(bool frozen=true);
+    bool frozen() { return m_frozen; }
+
+private:
+    HWND m_hwnd = nullptr;
+    bool m_frozen = false;
+    bool m_freezeUsesMark = false;
+    bool m_isNewW10 = false;
+    std::vector<wchar_t> m_titleWorkBuf;
+};
+
+#endif // AGENT_WIN32_CONSOLE_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.cc b/node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.cc
new file mode 100644 (file)
index 0000000..ed93f40
--- /dev/null
@@ -0,0 +1,193 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "Win32ConsoleBuffer.h"
+
+#include <windows.h>
+
+#include "../shared/DebugClient.h"
+#include "../shared/StringBuilder.h"
+#include "../shared/WinptyAssert.h"
+
+std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::openStdout() {
+    return std::unique_ptr<Win32ConsoleBuffer>(
+        new Win32ConsoleBuffer(GetStdHandle(STD_OUTPUT_HANDLE), false));
+}
+
+std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::openConout() {
+    const HANDLE conout = CreateFileW(L"CONOUT$",
+                                      GENERIC_READ | GENERIC_WRITE,
+                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                      NULL, OPEN_EXISTING, 0, NULL);
+    ASSERT(conout != INVALID_HANDLE_VALUE);
+    return std::unique_ptr<Win32ConsoleBuffer>(
+        new Win32ConsoleBuffer(conout, true));
+}
+
+std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::createErrorBuffer() {
+    SECURITY_ATTRIBUTES sa = {};
+    sa.nLength = sizeof(sa);
+    sa.bInheritHandle = TRUE;
+    const HANDLE conout =
+        CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
+                                  FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                  &sa,
+                                  CONSOLE_TEXTMODE_BUFFER,
+                                  nullptr);
+    ASSERT(conout != INVALID_HANDLE_VALUE);
+    return std::unique_ptr<Win32ConsoleBuffer>(
+        new Win32ConsoleBuffer(conout, true));
+}
+
+HANDLE Win32ConsoleBuffer::conout() {
+    return m_conout;
+}
+
+void Win32ConsoleBuffer::clearLines(
+        int row,
+        int count,
+        const ConsoleScreenBufferInfo &info) {
+    // TODO: error handling
+    const int width = info.bufferSize().X;
+    DWORD actual = 0;
+    if (!FillConsoleOutputCharacterW(
+            m_conout, L' ', width * count, Coord(0, row),
+            &actual) || static_cast<int>(actual) != width * count) {
+        trace("FillConsoleOutputCharacterW failed");
+    }
+    if (!FillConsoleOutputAttribute(
+            m_conout, kDefaultAttributes, width * count, Coord(0, row),
+            &actual) || static_cast<int>(actual) != width * count) {
+        trace("FillConsoleOutputAttribute failed");
+    }
+}
+
+void Win32ConsoleBuffer::clearAllLines(const ConsoleScreenBufferInfo &info) {
+    clearLines(0, info.bufferSize().Y, info);
+}
+
+ConsoleScreenBufferInfo Win32ConsoleBuffer::bufferInfo() {
+    // TODO: error handling
+    ConsoleScreenBufferInfo info;
+    if (!GetConsoleScreenBufferInfo(m_conout, &info)) {
+        trace("GetConsoleScreenBufferInfo failed");
+    }
+    return info;
+}
+
+Coord Win32ConsoleBuffer::bufferSize() {
+    return bufferInfo().bufferSize();
+}
+
+SmallRect Win32ConsoleBuffer::windowRect() {
+    return bufferInfo().windowRect();
+}
+
+bool Win32ConsoleBuffer::resizeBufferRange(const Coord &initialSize,
+                                           Coord &finalSize) {
+    if (SetConsoleScreenBufferSize(m_conout, initialSize)) {
+        finalSize = initialSize;
+        return true;
+    }
+    // The font might be too small to accommodate a very narrow console window.
+    // In that case, rather than simply give up, it's better to try wider
+    // buffer sizes until the call succeeds.
+    Coord size = initialSize;
+    while (size.X < 20) {
+        size.X++;
+        if (SetConsoleScreenBufferSize(m_conout, size)) {
+            finalSize = size;
+            trace("SetConsoleScreenBufferSize: initial size (%d,%d) failed, "
+                  "but wider size (%d,%d) succeeded",
+                  initialSize.X, initialSize.Y,
+                  finalSize.X, finalSize.Y);
+            return true;
+        }
+    }
+    trace("SetConsoleScreenBufferSize failed: "
+          "tried (%d,%d) through (%d,%d)",
+          initialSize.X, initialSize.Y,
+          size.X, size.Y);
+    return false;
+}
+
+void Win32ConsoleBuffer::resizeBuffer(const Coord &size) {
+    // TODO: error handling
+    if (!SetConsoleScreenBufferSize(m_conout, size)) {
+        trace("SetConsoleScreenBufferSize failed: size=(%d,%d)",
+              size.X, size.Y);
+    }
+}
+
+void Win32ConsoleBuffer::moveWindow(const SmallRect &rect) {
+    // TODO: error handling
+    if (!SetConsoleWindowInfo(m_conout, TRUE, &rect)) {
+        trace("SetConsoleWindowInfo failed");
+    }
+}
+
+Coord Win32ConsoleBuffer::cursorPosition() {
+    return bufferInfo().dwCursorPosition;
+}
+
+void Win32ConsoleBuffer::setCursorPosition(const Coord &coord) {
+    // TODO: error handling
+    if (!SetConsoleCursorPosition(m_conout, coord)) {
+        trace("SetConsoleCursorPosition failed");
+    }
+}
+
+void Win32ConsoleBuffer::read(const SmallRect &rect, CHAR_INFO *data) {
+    // TODO: error handling
+    SmallRect tmp(rect);
+    if (!ReadConsoleOutputW(m_conout, data, rect.size(), Coord(), &tmp) &&
+            isTracingEnabled()) {
+        StringBuilder sb(256);
+        auto outStruct = [&](const SMALL_RECT &sr) {
+            sb << "{L=" << sr.Left << ",T=" << sr.Top
+               << ",R=" << sr.Right << ",B=" << sr.Bottom << '}';
+        };
+        sb << "Win32ConsoleBuffer::read: ReadConsoleOutput failed: readRegion=";
+        outStruct(rect);
+        CONSOLE_SCREEN_BUFFER_INFO info = {};
+        if (GetConsoleScreenBufferInfo(m_conout, &info)) {
+            sb << ", dwSize=(" << info.dwSize.X << ',' << info.dwSize.Y
+               << "), srWindow=";
+            outStruct(info.srWindow);
+        } else {
+            sb << ", GetConsoleScreenBufferInfo also failed";
+        }
+        trace("%s", sb.c_str());
+    }
+}
+
+void Win32ConsoleBuffer::write(const SmallRect &rect, const CHAR_INFO *data) {
+    // TODO: error handling
+    SmallRect tmp(rect);
+    if (!WriteConsoleOutputW(m_conout, data, rect.size(), Coord(), &tmp)) {
+        trace("WriteConsoleOutput failed");
+    }
+}
+
+void Win32ConsoleBuffer::setTextAttribute(WORD attributes) {
+    if (!SetConsoleTextAttribute(m_conout, attributes)) {
+        trace("SetConsoleTextAttribute failed");
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.h b/node_modules/node-pty/deps/winpty/src/agent/Win32ConsoleBuffer.h
new file mode 100644 (file)
index 0000000..a68d8d3
--- /dev/null
@@ -0,0 +1,99 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef AGENT_WIN32_CONSOLE_BUFFER_H
+#define AGENT_WIN32_CONSOLE_BUFFER_H
+
+#include <windows.h>
+
+#include <string.h>
+
+#include <memory>
+
+#include "Coord.h"
+#include "SmallRect.h"
+
+class ConsoleScreenBufferInfo : public CONSOLE_SCREEN_BUFFER_INFO {
+public:
+    ConsoleScreenBufferInfo()
+    {
+        memset(this, 0, sizeof(*this));
+    }
+
+    Coord bufferSize() const        { return dwSize;    }
+    SmallRect windowRect() const    { return srWindow;  }
+    Coord cursorPosition() const    { return dwCursorPosition; }
+};
+
+class Win32ConsoleBuffer {
+private:
+    Win32ConsoleBuffer(HANDLE conout, bool owned) :
+        m_conout(conout), m_owned(owned)
+    {
+    }
+
+public:
+    static const int kDefaultAttributes = 7;
+
+    ~Win32ConsoleBuffer() {
+        if (m_owned) {
+            CloseHandle(m_conout);
+        }
+    }
+
+    static std::unique_ptr<Win32ConsoleBuffer> openStdout();
+    static std::unique_ptr<Win32ConsoleBuffer> openConout();
+    static std::unique_ptr<Win32ConsoleBuffer> createErrorBuffer();
+
+    Win32ConsoleBuffer(const Win32ConsoleBuffer &other) = delete;
+    Win32ConsoleBuffer &operator=(const Win32ConsoleBuffer &other) = delete;
+
+    HANDLE conout();
+    void clearLines(int row, int count, const ConsoleScreenBufferInfo &info);
+    void clearAllLines(const ConsoleScreenBufferInfo &info);
+
+    // Buffer and window sizes.
+    ConsoleScreenBufferInfo bufferInfo();
+    Coord bufferSize();
+    SmallRect windowRect();
+    void resizeBuffer(const Coord &size);
+    bool resizeBufferRange(const Coord &initialSize, Coord &finalSize);
+    bool resizeBufferRange(const Coord &initialSize) {
+        Coord dummy;
+        return resizeBufferRange(initialSize, dummy);
+    }
+    void moveWindow(const SmallRect &rect);
+
+    // Cursor.
+    Coord cursorPosition();
+    void setCursorPosition(const Coord &point);
+
+    // Screen content.
+    void read(const SmallRect &rect, CHAR_INFO *data);
+    void write(const SmallRect &rect, const CHAR_INFO *data);
+
+    void setTextAttribute(WORD attributes);
+
+private:
+    HANDLE m_conout = nullptr;
+    bool m_owned = false;
+};
+
+#endif // AGENT_WIN32_CONSOLE_BUFFER_H
diff --git a/node_modules/node-pty/deps/winpty/src/agent/main.cc b/node_modules/node-pty/deps/winpty/src/agent/main.cc
new file mode 100644 (file)
index 0000000..2420fde
--- /dev/null
@@ -0,0 +1,114 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+
+#include "../shared/StringUtil.h"
+#include "../shared/WindowsVersion.h"
+#include "../shared/WinptyAssert.h"
+#include "../shared/WinptyVersion.h"
+
+#include "Agent.h"
+#include "AgentCreateDesktop.h"
+#include "DebugShowInput.h"
+
+const char USAGE[] =
+"Usage: %ls controlPipeName flags mouseMode cols rows\n"
+"Usage: %ls controlPipeName --create-desktop\n"
+"\n"
+"Ordinarily, this program is launched by winpty.dll and is not directly\n"
+"useful to winpty users.  However, it also has options intended for\n"
+"debugging winpty.\n"
+"\n"
+"Usage: %ls [options]\n"
+"\n"
+"Options:\n"
+"  --show-input [--with-mouse] [--escape-input]\n"
+"                   Dump INPUT_RECORDs from the console input buffer\n"
+"                   --with-mouse: Include MOUSE_INPUT_RECORDs in the dump\n"
+"                       output\n"
+"                   --escape-input: Direct the new Windows 10 console to use\n"
+"                       escape sequences for input\n"
+"  --version        Print the winpty version\n";
+
+static uint64_t winpty_atoi64(const char *str) {
+    return strtoll(str, NULL, 10);
+}
+
+int main() {
+    dumpWindowsVersion();
+    dumpVersionToTrace();
+
+    // Technically, we should free the CommandLineToArgvW return value using
+    // a single call to LocalFree, but the call will never actually happen in
+    // the normal case.
+    int argc = 0;
+    wchar_t *cmdline = GetCommandLineW();
+    ASSERT(cmdline != nullptr && "GetCommandLineW returned NULL");
+    wchar_t **argv = CommandLineToArgvW(cmdline, &argc);
+    ASSERT(argv != nullptr && "CommandLineToArgvW returned NULL");
+
+    if (argc == 2 && !wcscmp(argv[1], L"--version")) {
+        dumpVersionToStdout();
+        return 0;
+    }
+
+    if (argc >= 2 && !wcscmp(argv[1], L"--show-input")) {
+        bool withMouse = false;
+        bool escapeInput = false;
+        for (int i = 2; i < argc; ++i) {
+            if (!wcscmp(argv[i], L"--with-mouse")) {
+                withMouse = true;
+            } else if (!wcscmp(argv[i], L"--escape-input")) {
+                escapeInput = true;
+            } else {
+                fprintf(stderr, "Unrecognized --show-input option: %ls\n",
+                    argv[i]);
+                return 1;
+            }
+        }
+        debugShowInput(withMouse, escapeInput);
+        return 0;
+    }
+
+    if (argc == 3 && !wcscmp(argv[2], L"--create-desktop")) {
+        handleCreateDesktop(argv[1]);
+        return 0;
+    }
+
+    if (argc != 6) {
+        fprintf(stderr, USAGE, argv[0], argv[0], argv[0]);
+        return 1;
+    }
+
+    Agent agent(argv[1],
+                winpty_atoi64(utf8FromWide(argv[2]).c_str()),
+                atoi(utf8FromWide(argv[3]).c_str()),
+                atoi(utf8FromWide(argv[4]).c_str()),
+                atoi(utf8FromWide(argv[5]).c_str()));
+    agent.run();
+
+    // The Agent destructor shouldn't return, but if it does, exit
+    // unsuccessfully.
+    return 1;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/agent/subdir.mk b/node_modules/node-pty/deps/winpty/src/agent/subdir.mk
new file mode 100644 (file)
index 0000000..1c7d37e
--- /dev/null
@@ -0,0 +1,61 @@
+# Copyright (c) 2011-2015 Ryan Prichard
+#
+# 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.
+
+ALL_TARGETS += build/winpty-agent.exe
+
+$(eval $(call def_mingw_target,agent,-DWINPTY_AGENT_ASSERT))
+
+AGENT_OBJECTS = \
+       build/agent/agent/Agent.o \
+       build/agent/agent/AgentCreateDesktop.o \
+       build/agent/agent/ConsoleFont.o \
+       build/agent/agent/ConsoleInput.o \
+       build/agent/agent/ConsoleInputReencoding.o \
+       build/agent/agent/ConsoleLine.o \
+       build/agent/agent/DebugShowInput.o \
+       build/agent/agent/DefaultInputMap.o \
+       build/agent/agent/EventLoop.o \
+       build/agent/agent/InputMap.o \
+       build/agent/agent/LargeConsoleRead.o \
+       build/agent/agent/NamedPipe.o \
+       build/agent/agent/Scraper.o \
+       build/agent/agent/Terminal.o \
+       build/agent/agent/Win32Console.o \
+       build/agent/agent/Win32ConsoleBuffer.o \
+       build/agent/agent/main.o \
+       build/agent/shared/BackgroundDesktop.o \
+       build/agent/shared/Buffer.o \
+       build/agent/shared/DebugClient.o \
+       build/agent/shared/GenRandom.o \
+       build/agent/shared/OwnedHandle.o \
+       build/agent/shared/StringUtil.o \
+       build/agent/shared/WindowsSecurity.o \
+       build/agent/shared/WindowsVersion.o \
+       build/agent/shared/WinptyAssert.o \
+       build/agent/shared/WinptyException.o \
+       build/agent/shared/WinptyVersion.o
+
+build/agent/shared/WinptyVersion.o : build/gen/GenVersion.h
+
+build/winpty-agent.exe : $(AGENT_OBJECTS)
+       $(info Linking $@)
+       @$(MINGW_CXX) $(MINGW_LDFLAGS) -o $@ $^
+
+-include $(AGENT_OBJECTS:.o=.d)
diff --git a/node_modules/node-pty/deps/winpty/src/configurations.gypi b/node_modules/node-pty/deps/winpty/src/configurations.gypi
new file mode 100644 (file)
index 0000000..e990a60
--- /dev/null
@@ -0,0 +1,60 @@
+# By default gyp/msbuild build for 32-bit Windows.  This gyp include file
+# defines configurations for both 32-bit and 64-bit Windows.  To use it, run:
+#
+#     C:\...\winpty\src>gyp -I configurations.gypi
+#
+# This command generates Visual Studio project files with a Release
+# configuration and two Platforms--Win32 and x64.  Both can be built:
+#
+#     C:\...\winpty\src>msbuild winpty.sln /p:Platform=Win32
+#     C:\...\winpty\src>msbuild winpty.sln /p:Platform=x64
+#
+# The output is placed in:
+#
+#     C:\...\winpty\src\Release\Win32
+#     C:\...\winpty\src\Release\x64
+#
+# Windows XP note: By default, the project files will use the default "toolset"
+# for the given MSVC version.  For MSVC 2013 and MSVC 2015, the default toolset
+# generates binaries that do not run on Windows XP.  To target Windows XP,
+# select the XP-specific toolset by passing
+# -D WINPTY_MSBUILD_TOOLSET={v120_xp,v140_xp} to gyp (v120_xp == MSVC 2013,
+# v140_xp == MSVC 2015).  Unfortunately, it isn't possible to have a single
+# project file with configurations for both XP and post-XP.  This seems to be a
+# limitation of the MSVC project file format.
+#
+# This file is not included by default, because I suspect it would interfere
+# with node-gyp, which has a different system for building 32-vs-64-bit
+# binaries.  It uses a common.gypi, and the project files it generates can only
+# build a single architecture, the output paths are not differentiated by
+# architecture.
+
+{
+    'variables': {
+        'WINPTY_MSBUILD_TOOLSET%': '',
+    },
+    'target_defaults': {
+        'default_configuration': 'Release_Win32',
+        'configurations': {
+            'Release_Win32': {
+                'msvs_configuration_platform': 'Win32',
+            },
+            'Release_x64': {
+                'msvs_configuration_platform': 'x64',
+            },
+        },
+        'msvs_configuration_attributes': {
+            'OutputDirectory': '$(SolutionDir)$(ConfigurationName)\\$(Platform)',
+            'IntermediateDirectory': '$(ConfigurationName)\\$(Platform)\\obj\\$(ProjectName)',
+        },
+        'msvs_settings': {
+            'VCLinkerTool': {
+                'SubSystem': '1', # /SUBSYSTEM:CONSOLE
+            },
+            'VCCLCompilerTool': {
+                'RuntimeLibrary': '0', # MultiThreaded (/MT)
+            },
+        },
+        'msbuild_toolset' : '<(WINPTY_MSBUILD_TOOLSET)',
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/debugserver/DebugServer.cc b/node_modules/node-pty/deps/winpty/src/debugserver/DebugServer.cc
new file mode 100644 (file)
index 0000000..353d31c
--- /dev/null
@@ -0,0 +1,117 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <windows.h>
+
+#include "../shared/WindowsSecurity.h"
+#include "../shared/WinptyException.h"
+
+const wchar_t *kPipeName = L"\\\\.\\pipe\\DebugServer";
+
+// A message may not be larger than this size.
+const int MSG_SIZE = 4096;
+
+static void usage(const char *program, int code) {
+    printf("Usage: %s [--everyone]\n"
+           "\n"
+           "Creates the named pipe %ls and reads messages.  Prints each\n"
+           "message to stdout.  By default, only the current user can send messages.\n"
+           "Pass --everyone to let anyone send a message.\n"
+           "\n"
+           "Use the WINPTY_DEBUG environment variable to enable winpty trace output.\n"
+           "(e.g. WINPTY_DEBUG=trace for the default trace output.)  Set WINPTYDBG=1\n"
+           "to enable trace with older winpty versions.\n",
+           program, kPipeName);
+    exit(code);
+}
+
+int main(int argc, char *argv[]) {
+    bool everyone = false;
+    for (int i = 1; i < argc; ++i) {
+        std::string arg = argv[i];
+        if (arg == "--everyone") {
+            everyone = true;
+        } else if (arg == "-h" || arg == "--help") {
+            usage(argv[0], 0);
+        } else {
+            usage(argv[0], 1);
+        }
+    }
+
+    SecurityDescriptor sd;
+    PSECURITY_ATTRIBUTES psa = nullptr;
+    SECURITY_ATTRIBUTES sa = {};
+    if (everyone) {
+        try {
+            sd = createPipeSecurityDescriptorOwnerFullControlEveryoneWrite();
+        } catch (const WinptyException &e) {
+            fprintf(stderr,
+                "error creating security descriptor: %ls\n", e.what());
+            exit(1);
+        }
+        sa.nLength = sizeof(sa);
+        sa.lpSecurityDescriptor = sd.get();
+        psa = &sa;
+    }
+
+    HANDLE serverPipe = CreateNamedPipeW(
+        kPipeName,
+        /*dwOpenMode=*/PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
+        /*dwPipeMode=*/PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE |
+            rejectRemoteClientsPipeFlag(),
+        /*nMaxInstances=*/1,
+        /*nOutBufferSize=*/MSG_SIZE,
+        /*nInBufferSize=*/MSG_SIZE,
+        /*nDefaultTimeOut=*/10 * 1000,
+        psa);
+
+    if (serverPipe == INVALID_HANDLE_VALUE) {
+        fprintf(stderr, "error: could not create %ls pipe: error %u\n",
+            kPipeName, static_cast<unsigned>(GetLastError()));
+        exit(1);
+    }
+
+    char msgBuffer[MSG_SIZE + 1];
+
+    while (true) {
+        if (!ConnectNamedPipe(serverPipe, nullptr)) {
+            fprintf(stderr, "error: ConnectNamedPipe failed\n");
+            fflush(stderr);
+            exit(1);
+        }
+        DWORD bytesRead = 0;
+        if (!ReadFile(serverPipe, msgBuffer, MSG_SIZE, &bytesRead, nullptr)) {
+            fprintf(stderr, "error: ReadFile on pipe failed\n");
+            fflush(stderr);
+            DisconnectNamedPipe(serverPipe);
+            continue;
+        }
+        msgBuffer[bytesRead] = '\n';
+        fwrite(msgBuffer, 1, bytesRead + 1, stdout);
+        fflush(stdout);
+
+        DWORD bytesWritten = 0;
+        WriteFile(serverPipe, "OK", 2, &bytesWritten, nullptr);
+        DisconnectNamedPipe(serverPipe);
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/debugserver/subdir.mk b/node_modules/node-pty/deps/winpty/src/debugserver/subdir.mk
new file mode 100644 (file)
index 0000000..beed1bd
--- /dev/null
@@ -0,0 +1,41 @@
+# Copyright (c) 2015 Ryan Prichard
+#
+# 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.
+
+ALL_TARGETS += build/winpty-debugserver.exe
+
+$(eval $(call def_mingw_target,debugserver,))
+
+DEBUGSERVER_OBJECTS = \
+       build/debugserver/debugserver/DebugServer.o \
+       build/debugserver/shared/DebugClient.o \
+       build/debugserver/shared/OwnedHandle.o \
+       build/debugserver/shared/StringUtil.o \
+       build/debugserver/shared/WindowsSecurity.o \
+       build/debugserver/shared/WindowsVersion.o \
+       build/debugserver/shared/WinptyAssert.o \
+       build/debugserver/shared/WinptyException.o
+
+build/debugserver/shared/WindowsVersion.o : build/gen/GenVersion.h
+
+build/winpty-debugserver.exe : $(DEBUGSERVER_OBJECTS)
+       $(info Linking $@)
+       @$(MINGW_CXX) $(MINGW_LDFLAGS) -o $@ $^
+
+-include $(DEBUGSERVER_OBJECTS:.o=.d)
diff --git a/node_modules/node-pty/deps/winpty/src/include/winpty.h b/node_modules/node-pty/deps/winpty/src/include/winpty.h
new file mode 100644 (file)
index 0000000..fdfe4bc
--- /dev/null
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2011-2016 Ryan Prichard
+ *
+ * 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.
+ */
+
+#ifndef WINPTY_H
+#define WINPTY_H
+
+#include <windows.h>
+
+#include "winpty_constants.h"
+
+/* On 32-bit Windows, winpty functions have the default __cdecl (not __stdcall)
+ * calling convention.  (64-bit Windows has only a single calling convention.)
+ * When compiled with __declspec(dllexport), with either MinGW or MSVC, the
+ * winpty functions are unadorned--no underscore prefix or '@nn' suffix--so
+ * GetProcAddress can be used easily. */
+#ifdef COMPILING_WINPTY_DLL
+#define WINPTY_API __declspec(dllexport)
+#else
+#define WINPTY_API __declspec(dllimport)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* The winpty API uses wide characters, instead of UTF-8, to avoid conversion
+ * complications related to surrogates.  Windows generally tolerates unpaired
+ * surrogates in text, which makes conversion to and from UTF-8 ambiguous and
+ * complicated.  (There are different UTF-8 variants that deal with UTF-16
+ * surrogates differently.) */
+
+
+
+/*****************************************************************************
+ * Error handling. */
+
+/* All the APIs have an optional winpty_error_t output parameter.  If a
+ * non-NULL argument is specified, then either the API writes NULL to the
+ * value (on success) or writes a newly allocated winpty_error_t object.  The
+ * object must be freed using winpty_error_free. */
+
+/* An error object. */
+typedef struct winpty_error_s winpty_error_t;
+typedef winpty_error_t *winpty_error_ptr_t;
+
+/* An error code -- one of WINPTY_ERROR_xxx. */
+typedef DWORD winpty_result_t;
+
+/* Gets the error code from the error object. */
+WINPTY_API winpty_result_t winpty_error_code(winpty_error_ptr_t err);
+
+/* Returns a textual representation of the error.  The string is freed when
+ * the error is freed. */
+WINPTY_API LPCWSTR winpty_error_msg(winpty_error_ptr_t err);
+
+/* Free the error object.  Every error returned from the winpty API must be
+ * freed. */
+WINPTY_API void winpty_error_free(winpty_error_ptr_t err);
+
+
+
+/*****************************************************************************
+ * Configuration of a new agent. */
+
+/* The winpty_config_t object is not thread-safe. */
+typedef struct winpty_config_s winpty_config_t;
+
+/* Allocate a winpty_config_t value.  Returns NULL on error.  There are no
+ * required settings -- the object may immediately be used.  agentFlags is a
+ * set of zero or more WINPTY_FLAG_xxx values.  An unrecognized flag results
+ * in an assertion failure. */
+WINPTY_API winpty_config_t *
+winpty_config_new(UINT64 agentFlags, winpty_error_ptr_t *err /*OPTIONAL*/);
+
+/* Free the cfg object after passing it to winpty_open. */
+WINPTY_API void winpty_config_free(winpty_config_t *cfg);
+
+WINPTY_API void
+winpty_config_set_initial_size(winpty_config_t *cfg, int cols, int rows);
+
+/* Set the mouse mode to one of the WINPTY_MOUSE_MODE_xxx constants. */
+WINPTY_API void
+winpty_config_set_mouse_mode(winpty_config_t *cfg, int mouseMode);
+
+/* Amount of time to wait for the agent to startup and to wait for any given
+ * agent RPC request.  Must be greater than 0.  Can be INFINITE. */
+WINPTY_API void
+winpty_config_set_agent_timeout(winpty_config_t *cfg, DWORD timeoutMs);
+
+
+
+/*****************************************************************************
+ * Start the agent. */
+
+/* The winpty_t object is thread-safe. */
+typedef struct winpty_s winpty_t;
+
+/* Starts the agent.  Returns NULL on error.  This process will connect to the
+ * agent over a control pipe, and the agent will open data pipes (e.g. CONIN
+ * and CONOUT). */
+WINPTY_API winpty_t *
+winpty_open(const winpty_config_t *cfg,
+            winpty_error_ptr_t *err /*OPTIONAL*/);
+
+/* A handle to the agent process.  This value is valid for the lifetime of the
+ * winpty_t object.  Do not close it. */
+WINPTY_API HANDLE winpty_agent_process(winpty_t *wp);
+
+
+
+/*****************************************************************************
+ * I/O pipes. */
+
+/* Returns the names of named pipes used for terminal I/O.  Each input or
+ * output direction uses a different half-duplex pipe.  The agent creates
+ * these pipes, and the client can connect to them using ordinary I/O methods.
+ * The strings are freed when the winpty_t object is freed.
+ *
+ * winpty_conerr_name returns NULL unless WINPTY_FLAG_CONERR is specified.
+ *
+ * N.B.: CreateFile does not block when connecting to a local server pipe.  If
+ * the server pipe does not exist or is already connected, then it fails
+ * instantly. */
+WINPTY_API LPCWSTR winpty_conin_name(winpty_t *wp);
+WINPTY_API LPCWSTR winpty_conout_name(winpty_t *wp);
+WINPTY_API LPCWSTR winpty_conerr_name(winpty_t *wp);
+
+
+
+/*****************************************************************************
+ * winpty agent RPC call: process creation. */
+
+/* The winpty_spawn_config_t object is not thread-safe. */
+typedef struct winpty_spawn_config_s winpty_spawn_config_t;
+
+/* winpty_spawn_config strings do not need to live as long as the config
+ * object.  They are copied.  Returns NULL on error.  spawnFlags is a set of
+ * zero or more WINPTY_SPAWN_FLAG_xxx values.  An unrecognized flag results in
+ * an assertion failure.
+ *
+ * env is a a pointer to an environment block like that passed to
+ * CreateProcess--a contiguous array of NUL-terminated "VAR=VAL" strings
+ * followed by a final NUL terminator.
+ *
+ * N.B.: If you want to gather all of the child's output, you may want the
+ * WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN flag.
+ */
+WINPTY_API winpty_spawn_config_t *
+winpty_spawn_config_new(UINT64 spawnFlags,
+                        LPCWSTR appname /*OPTIONAL*/,
+                        LPCWSTR cmdline /*OPTIONAL*/,
+                        LPCWSTR cwd /*OPTIONAL*/,
+                        LPCWSTR env /*OPTIONAL*/,
+                        winpty_error_ptr_t *err /*OPTIONAL*/);
+
+/* Free the cfg object after passing it to winpty_spawn. */
+WINPTY_API void winpty_spawn_config_free(winpty_spawn_config_t *cfg);
+
+/*
+ * Spawns the new process.
+ *
+ * The function initializes all output parameters to zero or NULL.
+ *
+ * On success, the function returns TRUE.  For each of process_handle and
+ * thread_handle that is non-NULL, the HANDLE returned from CreateProcess is
+ * duplicated from the agent and returned to the winpty client.  The client is
+ * responsible for closing these HANDLES.
+ *
+ * On failure, the function returns FALSE, and if err is non-NULL, then *err
+ * is set to an error object.
+ *
+ * If the agent's CreateProcess call failed, then *create_process_error is set
+ * to GetLastError(), and the WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED error
+ * is returned.
+ *
+ * winpty_spawn can only be called once per winpty_t object.  If it is called
+ * before the output data pipe(s) is/are connected, then collected output is
+ * buffered until the pipes are connected, rather than being discarded.
+ *
+ * N.B.: GetProcessId works even if the process has exited.  The PID is not
+ * recycled until the NT process object is freed.
+ * (https://blogs.msdn.microsoft.com/oldnewthing/20110107-00/?p=11803)
+ */
+WINPTY_API BOOL
+winpty_spawn(winpty_t *wp,
+             const winpty_spawn_config_t *cfg,
+             HANDLE *process_handle /*OPTIONAL*/,
+             HANDLE *thread_handle /*OPTIONAL*/,
+             DWORD *create_process_error /*OPTIONAL*/,
+             winpty_error_ptr_t *err /*OPTIONAL*/);
+
+
+
+/*****************************************************************************
+ * winpty agent RPC calls: everything else */
+
+/* Change the size of the Windows console window. */
+WINPTY_API BOOL
+winpty_set_size(winpty_t *wp, int cols, int rows,
+                winpty_error_ptr_t *err /*OPTIONAL*/);
+
+/* Gets a list of processes attached to the console. */
+WINPTY_API int
+winpty_get_console_process_list(winpty_t *wp, int *processList, const int processCount,
+                                winpty_error_ptr_t *err /*OPTIONAL*/);
+
+/* Frees the winpty_t object and the OS resources contained in it.  This
+ * call breaks the connection with the agent, which should then close its
+ * console, terminating the processes attached to it.
+ *
+ * This function must not be called if any other threads are using the
+ * winpty_t object.  Undefined behavior results. */
+WINPTY_API void winpty_free(winpty_t *wp);
+
+
+
+/****************************************************************************/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* WINPTY_H */
diff --git a/node_modules/node-pty/deps/winpty/src/include/winpty_constants.h b/node_modules/node-pty/deps/winpty/src/include/winpty_constants.h
new file mode 100644 (file)
index 0000000..11e34cf
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2016 Ryan Prichard
+ *
+ * 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.
+ */
+
+#ifndef WINPTY_CONSTANTS_H
+#define WINPTY_CONSTANTS_H
+
+/*
+ * You may want to include winpty.h instead, which includes this header.
+ *
+ * This file is split out from winpty.h so that the agent can access the
+ * winpty flags without also declaring the libwinpty APIs.
+ */
+
+/*****************************************************************************
+ * Error codes. */
+
+#define WINPTY_ERROR_SUCCESS                        0
+#define WINPTY_ERROR_OUT_OF_MEMORY                  1
+#define WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED    2
+#define WINPTY_ERROR_LOST_CONNECTION                3
+#define WINPTY_ERROR_AGENT_EXE_MISSING              4
+#define WINPTY_ERROR_UNSPECIFIED                    5
+#define WINPTY_ERROR_AGENT_DIED                     6
+#define WINPTY_ERROR_AGENT_TIMEOUT                  7
+#define WINPTY_ERROR_AGENT_CREATION_FAILED          8
+
+
+
+/*****************************************************************************
+ * Configuration of a new agent. */
+
+/* Create a new screen buffer (connected to the "conerr" terminal pipe) and
+ * pass it to child processes as the STDERR handle.  This flag also prevents
+ * the agent from reopening CONOUT$ when it polls -- regardless of whether the
+ * active screen buffer changes, winpty continues to monitor the original
+ * primary screen buffer. */
+#define WINPTY_FLAG_CONERR              0x1ull
+
+/* Don't output escape sequences. */
+#define WINPTY_FLAG_PLAIN_OUTPUT        0x2ull
+
+/* Do output color escape sequences.  These escapes are output by default, but
+ * are suppressed with WINPTY_FLAG_PLAIN_OUTPUT.  Use this flag to reenable
+ * them. */
+#define WINPTY_FLAG_COLOR_ESCAPES       0x4ull
+
+/* On XP and Vista, winpty needs to put the hidden console on a desktop in a
+ * service window station so that its polling does not interfere with other
+ * (visible) console windows.  To create this desktop, it must change the
+ * process' window station (i.e. SetProcessWindowStation) for the duration of
+ * the winpty_open call.  In theory, this change could interfere with the
+ * winpty client (e.g. other threads, spawning children), so winpty by default
+ * spawns a special agent process to create the hidden desktop.  Spawning
+ * processes on Windows is slow, though, so if
+ * WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION is set, winpty changes this
+ * process' window station instead.
+ * See https://github.com/rprichard/winpty/issues/58. */
+#define WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION 0x8ull
+
+#define WINPTY_FLAG_MASK (0ull \
+    | WINPTY_FLAG_CONERR \
+    | WINPTY_FLAG_PLAIN_OUTPUT \
+    | WINPTY_FLAG_COLOR_ESCAPES \
+    | WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION \
+)
+
+/* QuickEdit mode is initially disabled, and the agent does not send mouse
+ * mode sequences to the terminal.  If it receives mouse input, though, it
+ * still writes MOUSE_EVENT_RECORD values into CONIN. */
+#define WINPTY_MOUSE_MODE_NONE          0
+
+/* QuickEdit mode is initially enabled.  As CONIN enters or leaves mouse
+ * input mode (i.e. where ENABLE_MOUSE_INPUT is on and ENABLE_QUICK_EDIT_MODE
+ * is off), the agent enables or disables mouse input on the terminal.
+ *
+ * This is the default mode. */
+#define WINPTY_MOUSE_MODE_AUTO          1
+
+/* QuickEdit mode is initially disabled, and the agent enables the terminal's
+ * mouse input mode.  It does not disable terminal mouse mode (until exit). */
+#define WINPTY_MOUSE_MODE_FORCE         2
+
+
+
+/*****************************************************************************
+ * winpty agent RPC call: process creation. */
+
+/* If the spawn is marked "auto-shutdown", then the agent shuts down console
+ * output once the process exits.  The agent stops polling for new console
+ * output, and once all pending data has been written to the output pipe, the
+ * agent closes the pipe.  (At that point, the pipe may still have data in it,
+ * which the client may read.  Once all the data has been read, further reads
+ * return EOF.) */
+#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ull
+
+/* After the agent shuts down output, and after all output has been written
+ * into the pipe(s), exit the agent by closing the console.  If there any
+ * surviving processes still attached to the console, they are killed.
+ *
+ * Note: With this flag, an RPC call (e.g. winpty_set_size) issued after the
+ * agent exits will fail with an I/O or dead-agent error. */
+#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
+
+/* All the spawn flags. */
+#define WINPTY_SPAWN_FLAG_MASK (0ull \
+    | WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN \
+    | WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN \
+)
+
+
+
+#endif /* WINPTY_CONSTANTS_H */
diff --git a/node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.cc b/node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.cc
new file mode 100644 (file)
index 0000000..82d00b2
--- /dev/null
@@ -0,0 +1,75 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "AgentLocation.h"
+
+#include <windows.h>
+
+#include <string>
+
+#include "../shared/WinptyAssert.h"
+
+#include "LibWinptyException.h"
+
+#define AGENT_EXE L"winpty-agent.exe"
+
+static HMODULE getCurrentModule() {
+    HMODULE module;
+    if (!GetModuleHandleExW(
+                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
+                GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+                reinterpret_cast<LPCWSTR>(getCurrentModule),
+                &module)) {
+        ASSERT(false && "GetModuleHandleEx failed");
+    }
+    return module;
+}
+
+static std::wstring getModuleFileName(HMODULE module) {
+    const int bufsize = 4096;
+    wchar_t path[bufsize];
+    int size = GetModuleFileNameW(module, path, bufsize);
+    ASSERT(size != 0 && size != bufsize);
+    return std::wstring(path);
+}
+
+static std::wstring dirname(const std::wstring &path) {
+    std::wstring::size_type pos = path.find_last_of(L"\\/");
+    if (pos == std::wstring::npos) {
+        return L"";
+    } else {
+        return path.substr(0, pos);
+    }
+}
+
+static bool pathExists(const std::wstring &path) {
+    return GetFileAttributesW(path.c_str()) != 0xFFFFFFFF;
+}
+
+std::wstring findAgentProgram() {
+    std::wstring progDir = dirname(getModuleFileName(getCurrentModule()));
+    std::wstring ret = progDir + (L"\\" AGENT_EXE);
+    if (!pathExists(ret)) {
+        throw LibWinptyException(
+            WINPTY_ERROR_AGENT_EXE_MISSING,
+            (L"agent executable does not exist: '" + ret + L"'").c_str());
+    }
+    return ret;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.h b/node_modules/node-pty/deps/winpty/src/libwinpty/AgentLocation.h
new file mode 100644 (file)
index 0000000..a96b854
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef LIBWINPTY_AGENT_LOCATION_H
+#define LIBWINPTY_AGENT_LOCATION_H
+
+#include <string>
+
+std::wstring findAgentProgram();
+
+#endif // LIBWINPTY_AGENT_LOCATION_H
diff --git a/node_modules/node-pty/deps/winpty/src/libwinpty/LibWinptyException.h b/node_modules/node-pty/deps/winpty/src/libwinpty/LibWinptyException.h
new file mode 100644 (file)
index 0000000..2274798
--- /dev/null
@@ -0,0 +1,54 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef LIB_WINPTY_EXCEPTION_H
+#define LIB_WINPTY_EXCEPTION_H
+
+#include "../include/winpty.h"
+
+#include "../shared/WinptyException.h"
+
+#include <memory>
+#include <string>
+
+class LibWinptyException : public WinptyException {
+public:
+    LibWinptyException(winpty_result_t code, const wchar_t *what) :
+        m_code(code), m_what(std::make_shared<std::wstring>(what)) {}
+
+    winpty_result_t code() const WINPTY_NOEXCEPT {
+        return m_code;
+    }
+
+    const wchar_t *what() const WINPTY_NOEXCEPT override {
+        return m_what->c_str();
+    }
+
+    std::shared_ptr<std::wstring> whatSharedStr() const WINPTY_NOEXCEPT {
+        return m_what;
+    }
+
+private:
+    winpty_result_t m_code;
+    // Using a shared_ptr ensures that copying the object raises no exception.
+    std::shared_ptr<std::wstring> m_what;
+};
+
+#endif // LIB_WINPTY_EXCEPTION_H
diff --git a/node_modules/node-pty/deps/winpty/src/libwinpty/WinptyInternal.h b/node_modules/node-pty/deps/winpty/src/libwinpty/WinptyInternal.h
new file mode 100644 (file)
index 0000000..93e992d
--- /dev/null
@@ -0,0 +1,72 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef LIBWINPTY_WINPTY_INTERNAL_H
+#define LIBWINPTY_WINPTY_INTERNAL_H
+
+#include <memory>
+#include <string>
+
+#include "../include/winpty.h"
+
+#include "../shared/Mutex.h"
+#include "../shared/OwnedHandle.h"
+
+// The structures in this header are not intended to be accessed directly by
+// client programs.
+
+struct winpty_error_s {
+    winpty_result_t code;
+    const wchar_t *msgStatic;
+    // Use a pointer to a std::shared_ptr so that the struct remains simple
+    // enough to statically initialize, for the benefit of static error
+    // objects like kOutOfMemory.
+    std::shared_ptr<std::wstring> *msgDynamic;
+};
+
+struct winpty_config_s {
+    uint64_t flags = 0;
+    int cols = 80;
+    int rows = 25;
+    int mouseMode = WINPTY_MOUSE_MODE_AUTO;
+    DWORD timeoutMs = 30000;
+};
+
+struct winpty_s {
+    Mutex mutex;
+    OwnedHandle agentProcess;
+    OwnedHandle controlPipe;
+    DWORD agentTimeoutMs = 0;
+    OwnedHandle ioEvent;
+    std::wstring spawnDesktopName;
+    std::wstring coninPipeName;
+    std::wstring conoutPipeName;
+    std::wstring conerrPipeName;
+};
+
+struct winpty_spawn_config_s {
+    uint64_t winptyFlags = 0;
+    std::wstring appname;
+    std::wstring cmdline;
+    std::wstring cwd;
+    std::wstring env;
+};
+
+#endif // LIBWINPTY_WINPTY_INTERNAL_H
diff --git a/node_modules/node-pty/deps/winpty/src/libwinpty/subdir.mk b/node_modules/node-pty/deps/winpty/src/libwinpty/subdir.mk
new file mode 100644 (file)
index 0000000..ba32bad
--- /dev/null
@@ -0,0 +1,46 @@
+# Copyright (c) 2011-2015 Ryan Prichard
+#
+# 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.
+
+ALL_TARGETS += build/winpty.dll
+
+$(eval $(call def_mingw_target,libwinpty,-DCOMPILING_WINPTY_DLL))
+
+LIBWINPTY_OBJECTS = \
+       build/libwinpty/libwinpty/AgentLocation.o \
+       build/libwinpty/libwinpty/winpty.o \
+       build/libwinpty/shared/BackgroundDesktop.o \
+       build/libwinpty/shared/Buffer.o \
+       build/libwinpty/shared/DebugClient.o \
+       build/libwinpty/shared/GenRandom.o \
+       build/libwinpty/shared/OwnedHandle.o \
+       build/libwinpty/shared/StringUtil.o \
+       build/libwinpty/shared/WindowsSecurity.o \
+       build/libwinpty/shared/WindowsVersion.o \
+       build/libwinpty/shared/WinptyAssert.o \
+       build/libwinpty/shared/WinptyException.o \
+       build/libwinpty/shared/WinptyVersion.o
+
+build/libwinpty/shared/WinptyVersion.o : build/gen/GenVersion.h
+
+build/winpty.dll : $(LIBWINPTY_OBJECTS)
+       $(info Linking $@)
+       @$(MINGW_CXX) $(MINGW_LDFLAGS) -shared -o $@ $^ -Wl,--out-implib,build/winpty.lib
+
+-include $(LIBWINPTY_OBJECTS:.o=.d)
diff --git a/node_modules/node-pty/deps/winpty/src/libwinpty/winpty.cc b/node_modules/node-pty/deps/winpty/src/libwinpty/winpty.cc
new file mode 100644 (file)
index 0000000..3d97749
--- /dev/null
@@ -0,0 +1,970 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include <windows.h>
+
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <limits>
+#include <string>
+#include <vector>
+
+#include "../include/winpty.h"
+
+#include "../shared/AgentMsg.h"
+#include "../shared/BackgroundDesktop.h"
+#include "../shared/Buffer.h"
+#include "../shared/DebugClient.h"
+#include "../shared/GenRandom.h"
+#include "../shared/OwnedHandle.h"
+#include "../shared/StringBuilder.h"
+#include "../shared/StringUtil.h"
+#include "../shared/WindowsSecurity.h"
+#include "../shared/WindowsVersion.h"
+#include "../shared/WinptyAssert.h"
+#include "../shared/WinptyException.h"
+#include "../shared/WinptyVersion.h"
+
+#include "AgentLocation.h"
+#include "LibWinptyException.h"
+#include "WinptyInternal.h"
+
+
+
+/*****************************************************************************
+ * Error handling -- translate C++ exceptions to an optional error object
+ * output and log the result. */
+
+static const winpty_error_s kOutOfMemory = {
+    WINPTY_ERROR_OUT_OF_MEMORY,
+    L"Out of memory",
+    nullptr
+};
+
+static const winpty_error_s kBadRpcPacket = {
+    WINPTY_ERROR_UNSPECIFIED,
+    L"Bad RPC packet",
+    nullptr
+};
+
+static const winpty_error_s kUncaughtException = {
+    WINPTY_ERROR_UNSPECIFIED,
+    L"Uncaught C++ exception",
+    nullptr
+};
+
+/* Gets the error code from the error object. */
+WINPTY_API winpty_result_t winpty_error_code(winpty_error_ptr_t err) {
+    return err != nullptr ? err->code : WINPTY_ERROR_SUCCESS;
+}
+
+/* Returns a textual representation of the error.  The string is freed when
+ * the error is freed. */
+WINPTY_API LPCWSTR winpty_error_msg(winpty_error_ptr_t err) {
+    if (err != nullptr) {
+        if (err->msgStatic != nullptr) {
+            return err->msgStatic;
+        } else {
+            ASSERT(err->msgDynamic != nullptr);
+            std::wstring *msgPtr = err->msgDynamic->get();
+            ASSERT(msgPtr != nullptr);
+            return msgPtr->c_str();
+        }
+    } else {
+        return L"Success";
+    }
+}
+
+/* Free the error object.  Every error returned from the winpty API must be
+ * freed. */
+WINPTY_API void winpty_error_free(winpty_error_ptr_t err) {
+    if (err != nullptr && err->msgDynamic != nullptr) {
+        delete err->msgDynamic;
+        delete err;
+    }
+}
+
+static void translateException(winpty_error_ptr_t *&err) {
+    winpty_error_ptr_t ret = nullptr;
+    try {
+        try {
+            throw;
+        } catch (const ReadBuffer::DecodeError&) {
+            ret = const_cast<winpty_error_ptr_t>(&kBadRpcPacket);
+        } catch (const LibWinptyException &e) {
+            std::unique_ptr<winpty_error_t> obj(new winpty_error_t);
+            obj->code = e.code();
+            obj->msgStatic = nullptr;
+            obj->msgDynamic =
+                new std::shared_ptr<std::wstring>(e.whatSharedStr());
+            ret = obj.release();
+        } catch (const WinptyException &e) {
+            std::unique_ptr<winpty_error_t> obj(new winpty_error_t);
+            std::shared_ptr<std::wstring> msg(new std::wstring(e.what()));
+            obj->code = WINPTY_ERROR_UNSPECIFIED;
+            obj->msgStatic = nullptr;
+            obj->msgDynamic = new std::shared_ptr<std::wstring>(msg);
+            ret = obj.release();
+        }
+    } catch (const std::bad_alloc&) {
+        ret = const_cast<winpty_error_ptr_t>(&kOutOfMemory);
+    } catch (...) {
+        ret = const_cast<winpty_error_ptr_t>(&kUncaughtException);
+    }
+    trace("libwinpty error: code=%u msg='%s'",
+        static_cast<unsigned>(ret->code),
+        utf8FromWide(winpty_error_msg(ret)).c_str());
+    if (err != nullptr) {
+        *err = ret;
+    } else {
+        winpty_error_free(ret);
+    }
+}
+
+#define API_TRY \
+    if (err != nullptr) { *err = nullptr; } \
+    try
+
+#define API_CATCH(ret) \
+    catch (...) { translateException(err); return (ret); }
+
+
+
+/*****************************************************************************
+ * Configuration of a new agent. */
+
+WINPTY_API winpty_config_t *
+winpty_config_new(UINT64 flags, winpty_error_ptr_t *err /*OPTIONAL*/) {
+    API_TRY {
+        ASSERT((flags & WINPTY_FLAG_MASK) == flags);
+        std::unique_ptr<winpty_config_t> ret(new winpty_config_t);
+        ret->flags = flags;
+        return ret.release();
+    } API_CATCH(nullptr)
+}
+
+WINPTY_API void winpty_config_free(winpty_config_t *cfg) {
+    delete cfg;
+}
+
+WINPTY_API void
+winpty_config_set_initial_size(winpty_config_t *cfg, int cols, int rows) {
+    ASSERT(cfg != nullptr && cols > 0 && rows > 0);
+    cfg->cols = cols;
+    cfg->rows = rows;
+}
+
+WINPTY_API void
+winpty_config_set_mouse_mode(winpty_config_t *cfg, int mouseMode) {
+    ASSERT(cfg != nullptr &&
+        mouseMode >= WINPTY_MOUSE_MODE_NONE &&
+        mouseMode <= WINPTY_MOUSE_MODE_FORCE);
+    cfg->mouseMode = mouseMode;
+}
+
+WINPTY_API void
+winpty_config_set_agent_timeout(winpty_config_t *cfg, DWORD timeoutMs) {
+    ASSERT(cfg != nullptr && timeoutMs > 0);
+    cfg->timeoutMs = timeoutMs;
+}
+
+
+
+/*****************************************************************************
+ * Agent I/O. */
+
+namespace {
+
+// Once an I/O operation fails with ERROR_IO_PENDING, the caller *must* wait
+// for it to complete, even after calling CancelIo on it!  See
+// https://blogs.msdn.microsoft.com/oldnewthing/20110202-00/?p=11613.  This
+// class enforces that requirement.
+class PendingIo {
+    HANDLE m_file;
+    OVERLAPPED &m_over;
+    bool m_finished;
+public:
+    // The file handle and OVERLAPPED object must live as long as the PendingIo
+    // object.
+    PendingIo(HANDLE file, OVERLAPPED &over) :
+        m_file(file), m_over(over), m_finished(false) {}
+    ~PendingIo() {
+        if (!m_finished) {
+            // We're not usually that interested in CancelIo's return value.
+            // In any case, we must not throw an exception in this dtor.
+            CancelIo(m_file);
+            waitForCompletion();
+        }
+    }
+    std::tuple<BOOL, DWORD> waitForCompletion(DWORD &actual) WINPTY_NOEXCEPT {
+        m_finished = true;
+        const BOOL success =
+            GetOverlappedResult(m_file, &m_over, &actual, TRUE);
+        return std::make_tuple(success, GetLastError());
+    }
+    std::tuple<BOOL, DWORD> waitForCompletion() WINPTY_NOEXCEPT {
+        DWORD actual = 0;
+        return waitForCompletion(actual);
+    }
+};
+
+} // anonymous namespace
+
+static void handlePendingIo(winpty_t &wp, OVERLAPPED &over, BOOL &success,
+                            DWORD &lastError, DWORD &actual) {
+    if (!success && lastError == ERROR_IO_PENDING) {
+        PendingIo io(wp.controlPipe.get(), over);
+        const HANDLE waitHandles[2] = { wp.ioEvent.get(),
+                                        wp.agentProcess.get() };
+        DWORD waitRet = WaitForMultipleObjects(
+            2, waitHandles, FALSE, wp.agentTimeoutMs);
+        if (waitRet != WAIT_OBJECT_0) {
+            // The I/O is still pending.  Cancel it, close the I/O event, and
+            // throw an exception.
+            if (waitRet == WAIT_OBJECT_0 + 1) {
+                throw LibWinptyException(WINPTY_ERROR_AGENT_DIED, L"agent died");
+            } else if (waitRet == WAIT_TIMEOUT) {
+                throw LibWinptyException(WINPTY_ERROR_AGENT_TIMEOUT,
+                                      L"agent timed out");
+            } else if (waitRet == WAIT_FAILED) {
+                throwWindowsError(L"WaitForMultipleObjects failed");
+            } else {
+                ASSERT(false &&
+                    "unexpected WaitForMultipleObjects return value");
+            }
+        }
+        std::tie(success, lastError) = io.waitForCompletion(actual);
+    }
+}
+
+static void handlePendingIo(winpty_t &wp, OVERLAPPED &over, BOOL &success,
+                            DWORD &lastError) {
+    DWORD actual = 0;
+    handlePendingIo(wp, over, success, lastError, actual);
+}
+
+static void handleReadWriteErrors(winpty_t &wp, BOOL success, DWORD lastError,
+                                  const wchar_t *genericErrMsg) {
+    if (!success) {
+        // If the pipe connection is broken after it's been connected, then
+        // later I/O operations fail with ERROR_BROKEN_PIPE (reads) or
+        // ERROR_NO_DATA (writes).  With Wine, they may also fail with
+        // ERROR_PIPE_NOT_CONNECTED.  See this gist[1].
+        //
+        // [1] https://gist.github.com/rprichard/8dd8ca134b39534b7da2733994aa07ba
+        if (lastError == ERROR_BROKEN_PIPE || lastError == ERROR_NO_DATA ||
+                lastError == ERROR_PIPE_NOT_CONNECTED) {
+            throw LibWinptyException(WINPTY_ERROR_LOST_CONNECTION,
+                L"lost connection to agent");
+        } else {
+            throwWindowsError(genericErrMsg, lastError);
+        }
+    }
+}
+
+// Calls ConnectNamedPipe to wait until the agent connects to the control pipe.
+static void
+connectControlPipe(winpty_t &wp) {
+    OVERLAPPED over = {};
+    over.hEvent = wp.ioEvent.get();
+    BOOL success = ConnectNamedPipe(wp.controlPipe.get(), &over);
+    DWORD lastError = GetLastError();
+    handlePendingIo(wp, over, success, lastError);
+    if (!success && lastError == ERROR_PIPE_CONNECTED) {
+        success = TRUE;
+    }
+    if (!success) {
+        throwWindowsError(L"ConnectNamedPipe failed", lastError);
+    }
+}
+
+static void writeData(winpty_t &wp, const void *data, size_t amount) {
+    // Perform a single pipe write.
+    DWORD actual = 0;
+    OVERLAPPED over = {};
+    over.hEvent = wp.ioEvent.get();
+    BOOL success = WriteFile(wp.controlPipe.get(), data, amount,
+                             &actual, &over);
+    DWORD lastError = GetLastError();
+    if (!success) {
+        handlePendingIo(wp, over, success, lastError, actual);
+        handleReadWriteErrors(wp, success, lastError, L"WriteFile failed");
+        ASSERT(success);
+    }
+    // TODO: Can a partial write actually happen somehow?
+    ASSERT(actual == amount && "WriteFile wrote fewer bytes than requested");
+}
+
+static inline WriteBuffer newPacket() {
+    WriteBuffer packet;
+    packet.putRawValue<uint64_t>(0); // Reserve space for size.
+    return packet;
+}
+
+static void writePacket(winpty_t &wp, WriteBuffer &packet) {
+    const auto &buf = packet.buf();
+    packet.replaceRawValue<uint64_t>(0, buf.size());
+    writeData(wp, buf.data(), buf.size());
+}
+
+static size_t readData(winpty_t &wp, void *data, size_t amount) {
+    DWORD actual = 0;
+    OVERLAPPED over = {};
+    over.hEvent = wp.ioEvent.get();
+    BOOL success = ReadFile(wp.controlPipe.get(), data, amount,
+                            &actual, &over);
+    DWORD lastError = GetLastError();
+    if (!success) {
+        handlePendingIo(wp, over, success, lastError, actual);
+        handleReadWriteErrors(wp, success, lastError, L"ReadFile failed");
+    }
+    return actual;
+}
+
+static void readAll(winpty_t &wp, void *data, size_t amount) {
+    while (amount > 0) {
+        const size_t chunk = readData(wp, data, amount);
+        ASSERT(chunk <= amount && "readData result is larger than amount");
+        data = reinterpret_cast<char*>(data) + chunk;
+        amount -= chunk;
+    }
+}
+
+static uint64_t readUInt64(winpty_t &wp) {
+    uint64_t ret = 0;
+    readAll(wp, &ret, sizeof(ret));
+    return ret;
+}
+
+// Returns a reply packet's payload.
+static ReadBuffer readPacket(winpty_t &wp) {
+    const uint64_t packetSize = readUInt64(wp);
+    if (packetSize < sizeof(packetSize) || packetSize > SIZE_MAX) {
+        throwWinptyException(L"Agent RPC error: invalid packet size");
+    }
+    const size_t payloadSize = packetSize - sizeof(packetSize);
+    std::vector<char> bytes(payloadSize);
+    readAll(wp, bytes.data(), bytes.size());
+    return ReadBuffer(std::move(bytes));
+}
+
+static OwnedHandle createControlPipe(const std::wstring &name) {
+    const auto sd = createPipeSecurityDescriptorOwnerFullControl();
+    if (!sd) {
+        throwWinptyException(
+            L"could not create the control pipe's SECURITY_DESCRIPTOR");
+    }
+    SECURITY_ATTRIBUTES sa = {};
+    sa.nLength = sizeof(sa);
+    sa.lpSecurityDescriptor = sd.get();
+    HANDLE ret = CreateNamedPipeW(name.c_str(),
+        /*dwOpenMode=*/
+        PIPE_ACCESS_DUPLEX |
+            FILE_FLAG_FIRST_PIPE_INSTANCE |
+            FILE_FLAG_OVERLAPPED,
+        /*dwPipeMode=*/rejectRemoteClientsPipeFlag(),
+        /*nMaxInstances=*/1,
+        /*nOutBufferSize=*/8192,
+        /*nInBufferSize=*/256,
+        /*nDefaultTimeOut=*/30000,
+        &sa);
+    if (ret == INVALID_HANDLE_VALUE) {
+        throwWindowsError(L"CreateNamedPipeW failed");
+    }
+    return OwnedHandle(ret);
+}
+
+
+
+/*****************************************************************************
+ * Start the agent. */
+
+static OwnedHandle createEvent() {
+    // manual reset, initially unset
+    HANDLE h = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+    if (h == nullptr) {
+        throwWindowsError(L"CreateEventW failed");
+    }
+    return OwnedHandle(h);
+}
+
+// For debugging purposes, provide a way to keep the console on the main window
+// station, visible.
+static bool shouldShowConsoleWindow() {
+    char buf[32];
+    return GetEnvironmentVariableA("WINPTY_SHOW_CONSOLE", buf, sizeof(buf)) > 0;
+}
+
+static bool shouldCreateBackgroundDesktop(bool &createUsingAgent) {
+    // Prior to Windows 7, winpty's repeated selection-deselection loop
+    // prevented the user from interacting with their *visible* console
+    // windows, unless we placed the console onto a background desktop.
+    // The SetProcessWindowStation call interferes with the clipboard and
+    // isn't thread-safe, though[1].  The call should perhaps occur in a
+    // special agent subprocess.  Spawning a process in a background desktop
+    // also breaks ConEmu, but marking the process SW_HIDE seems to correct
+    // that[2].
+    //
+    // Windows 7 moved a lot of console handling out of csrss.exe and into
+    // a per-console conhost.exe process, which may explain why it isn't
+    // affected.
+    //
+    // This is a somewhat risky change, so there are low-level flags to
+    // assist in debugging if there are issues.
+    //
+    // [1] https://github.com/rprichard/winpty/issues/58
+    // [2] https://github.com/rprichard/winpty/issues/70
+    bool ret = !shouldShowConsoleWindow() && !isAtLeastWindows7();
+    const bool force = hasDebugFlag("force_desktop");
+    const bool force_spawn = hasDebugFlag("force_desktop_spawn");
+    const bool force_curproc = hasDebugFlag("force_desktop_curproc");
+    const bool suppress = hasDebugFlag("no_desktop");
+    if (force + force_spawn + force_curproc + suppress > 1) {
+        trace("error: Only one of force_desktop, force_desktop_spawn, "
+              "force_desktop_curproc, and no_desktop may be set");
+    } else if (force) {
+        ret = true;
+    } else if (force_spawn) {
+        ret = true;
+        createUsingAgent = true;
+    } else if (force_curproc) {
+        ret = true;
+        createUsingAgent = false;
+    } else if (suppress) {
+        ret = false;
+    }
+    return ret;
+}
+
+static bool shouldSpecifyHideFlag() {
+    const bool force = hasDebugFlag("force_sw_hide");
+    const bool suppress = hasDebugFlag("no_sw_hide");
+    bool ret = !shouldShowConsoleWindow();
+    if (force && suppress) {
+        trace("error: Both the force_sw_hide and no_sw_hide flags are set");
+    } else if (force) {
+        ret = true;
+    } else if (suppress) {
+        ret = false;
+    }
+    return ret;
+}
+
+static OwnedHandle startAgentProcess(
+        const std::wstring &desktop,
+        const std::wstring &controlPipeName,
+        const std::wstring &params,
+        DWORD creationFlags,
+        DWORD &agentPid) {
+    const std::wstring exePath = findAgentProgram();
+    const std::wstring cmdline =
+        (WStringBuilder(256)
+            << L"\"" << exePath << L"\" "
+            << controlPipeName << L' '
+            << params).str_moved();
+
+    auto cmdlineV = vectorWithNulFromString(cmdline);
+    auto desktopV = vectorWithNulFromString(desktop);
+
+    // Start the agent.
+    STARTUPINFOW sui = {};
+    sui.cb = sizeof(sui);
+    sui.lpDesktop = desktop.empty() ? nullptr : desktopV.data();
+
+    if (shouldSpecifyHideFlag()) {
+        sui.dwFlags |= STARTF_USESHOWWINDOW;
+        sui.wShowWindow = SW_HIDE;
+    }
+    PROCESS_INFORMATION pi = {};
+    const BOOL success =
+        CreateProcessW(exePath.c_str(),
+                       cmdlineV.data(),
+                       nullptr, nullptr,
+                       /*bInheritHandles=*/FALSE,
+                       /*dwCreationFlags=*/creationFlags,
+                       nullptr, nullptr,
+                       &sui, &pi);
+    if (!success) {
+        const DWORD lastError = GetLastError();
+        const auto errStr =
+            (WStringBuilder(256)
+                << L"winpty-agent CreateProcess failed: cmdline='" << cmdline
+                << L"' err=0x" << whexOfInt(lastError)).str_moved();
+        throw LibWinptyException(
+            WINPTY_ERROR_AGENT_CREATION_FAILED, errStr.c_str());
+    }
+    CloseHandle(pi.hThread);
+    TRACE("Created agent successfully, pid=%u, cmdline=%s",
+          static_cast<unsigned int>(pi.dwProcessId),
+          utf8FromWide(cmdline).c_str());
+    agentPid = pi.dwProcessId;
+    return OwnedHandle(pi.hProcess);
+}
+
+static void verifyPipeClientPid(HANDLE serverPipe, DWORD agentPid) {
+    const auto client = getNamedPipeClientProcessId(serverPipe);
+    const auto success = std::get<0>(client);
+    const auto lastError = std::get<2>(client);
+    if (success == GetNamedPipeClientProcessId_Result::Success) {
+        const auto clientPid = std::get<1>(client);
+        if (clientPid != agentPid) {
+            WStringBuilder errMsg;
+            errMsg << L"Security check failed: pipe client pid (" << clientPid
+                   << L") does not match agent pid (" << agentPid << L")";
+            throwWinptyException(errMsg.c_str());
+        }
+    } else if (success == GetNamedPipeClientProcessId_Result::UnsupportedOs) {
+        trace("Pipe client PID security check skipped: "
+            "GetNamedPipeClientProcessId unsupported on this OS version");
+    } else {
+        throwWindowsError(L"GetNamedPipeClientProcessId failed", lastError);
+    }
+}
+
+static std::unique_ptr<winpty_t>
+createAgentSession(const winpty_config_t *cfg,
+                   const std::wstring &desktop,
+                   const std::wstring &params,
+                   DWORD creationFlags) {
+    std::unique_ptr<winpty_t> wp(new winpty_t);
+    wp->agentTimeoutMs = cfg->timeoutMs;
+    wp->ioEvent = createEvent();
+
+    // Create control server pipe.
+    const auto pipeName =
+        L"\\\\.\\pipe\\winpty-control-" + GenRandom().uniqueName();
+    wp->controlPipe = createControlPipe(pipeName);
+
+    DWORD agentPid = 0;
+    wp->agentProcess = startAgentProcess(
+        desktop, pipeName, params, creationFlags, agentPid);
+    connectControlPipe(*wp.get());
+    verifyPipeClientPid(wp->controlPipe.get(), agentPid);
+
+    return std::move(wp);
+}
+
+namespace {
+
+class AgentDesktop {
+public:
+    virtual std::wstring name() = 0;
+    virtual ~AgentDesktop() {}
+};
+
+class AgentDesktopDirect : public AgentDesktop {
+public:
+    AgentDesktopDirect(BackgroundDesktop &&desktop) :
+        m_desktop(std::move(desktop))
+    {
+    }
+    std::wstring name() override { return m_desktop.desktopName(); }
+private:
+    BackgroundDesktop m_desktop;
+};
+
+class AgentDesktopIndirect : public AgentDesktop {
+public:
+    AgentDesktopIndirect(std::unique_ptr<winpty_t> &&wp,
+                         std::wstring &&desktopName) :
+        m_wp(std::move(wp)),
+        m_desktopName(std::move(desktopName))
+    {
+    }
+    std::wstring name() override { return m_desktopName; }
+private:
+    std::unique_ptr<winpty_t> m_wp;
+    std::wstring m_desktopName;
+};
+
+} // anonymous namespace
+
+std::unique_ptr<AgentDesktop>
+setupBackgroundDesktop(const winpty_config_t *cfg) {
+    bool useDesktopAgent =
+        !(cfg->flags & WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION);
+    const bool useDesktop = shouldCreateBackgroundDesktop(useDesktopAgent);
+
+    if (!useDesktop) {
+        return std::unique_ptr<AgentDesktop>();
+    }
+
+    if (useDesktopAgent) {
+        auto wp = createAgentSession(
+            cfg, std::wstring(), L"--create-desktop", DETACHED_PROCESS);
+
+        // Read the desktop name.
+        auto packet = readPacket(*wp.get());
+        auto desktopName = packet.getWString();
+        packet.assertEof();
+
+        if (desktopName.empty()) {
+            return std::unique_ptr<AgentDesktop>();
+        } else {
+            return std::unique_ptr<AgentDesktop>(
+                new AgentDesktopIndirect(std::move(wp),
+                                         std::move(desktopName)));
+        }
+    } else {
+        try {
+            BackgroundDesktop desktop;
+            return std::unique_ptr<AgentDesktop>(new AgentDesktopDirect(
+                std::move(desktop)));
+        } catch (const WinptyException &e) {
+            trace("Error: failed to create background desktop, "
+                  "using original desktop instead: %s",
+                  utf8FromWide(e.what()).c_str());
+            return std::unique_ptr<AgentDesktop>();
+        }
+    }
+}
+
+WINPTY_API winpty_t *
+winpty_open(const winpty_config_t *cfg,
+            winpty_error_ptr_t *err /*OPTIONAL*/) {
+    API_TRY {
+        ASSERT(cfg != nullptr);
+        dumpWindowsVersion();
+        dumpVersionToTrace();
+
+        // Setup a background desktop for the agent.
+        auto desktop = setupBackgroundDesktop(cfg);
+        const auto desktopName = desktop ? desktop->name() : std::wstring();
+
+        // Start the primary agent session.
+        const auto params =
+            (WStringBuilder(128)
+                << cfg->flags << L' '
+                << cfg->mouseMode << L' '
+                << cfg->cols << L' '
+                << cfg->rows).str_moved();
+        auto wp = createAgentSession(cfg, desktopName, params,
+                                     CREATE_NEW_CONSOLE);
+
+        // Close handles to the background desktop and restore the original
+        // window station.  This must wait until we know the agent is running
+        // -- if we close these handles too soon, then the desktop and
+        // windowstation will be destroyed before the agent can connect with
+        // them.
+        //
+        // If we used a separate agent process to create the desktop, we
+        // disconnect from that process here, allowing it to exit.
+        desktop.reset();
+
+        // If we ran the agent process on a background desktop, then when we
+        // spawn a child process from the agent, it will need to be explicitly
+        // placed back onto the original desktop.
+        if (!desktopName.empty()) {
+            wp->spawnDesktopName = getCurrentDesktopName();
+        }
+
+        // Get the CONIN/CONOUT pipe names.
+        auto packet = readPacket(*wp.get());
+        wp->coninPipeName = packet.getWString();
+        wp->conoutPipeName = packet.getWString();
+        if (cfg->flags & WINPTY_FLAG_CONERR) {
+            wp->conerrPipeName = packet.getWString();
+        }
+        packet.assertEof();
+
+        return wp.release();
+    } API_CATCH(nullptr)
+}
+
+WINPTY_API HANDLE winpty_agent_process(winpty_t *wp) {
+    ASSERT(wp != nullptr);
+    return wp->agentProcess.get();
+}
+
+
+
+/*****************************************************************************
+ * I/O pipes. */
+
+static const wchar_t *cstrFromWStringOrNull(const std::wstring &str) {
+    try {
+        return str.c_str();
+    } catch (const std::bad_alloc&) {
+        return nullptr;
+    }
+}
+
+WINPTY_API LPCWSTR winpty_conin_name(winpty_t *wp) {
+    ASSERT(wp != nullptr);
+    return cstrFromWStringOrNull(wp->coninPipeName);
+}
+
+WINPTY_API LPCWSTR winpty_conout_name(winpty_t *wp) {
+    ASSERT(wp != nullptr);
+    return cstrFromWStringOrNull(wp->conoutPipeName);
+}
+
+WINPTY_API LPCWSTR winpty_conerr_name(winpty_t *wp) {
+    ASSERT(wp != nullptr);
+    if (wp->conerrPipeName.empty()) {
+        return nullptr;
+    } else {
+        return cstrFromWStringOrNull(wp->conerrPipeName);
+    }
+}
+
+
+
+/*****************************************************************************
+ * winpty agent RPC calls. */
+
+namespace {
+
+// Close the control pipe if something goes wrong with the pipe communication,
+// which could leave the control pipe in an inconsistent state.
+class RpcOperation {
+public:
+    RpcOperation(winpty_t &wp) : m_wp(wp) {
+        if (m_wp.controlPipe.get() == nullptr) {
+            throwWinptyException(L"Agent shutdown due to RPC failure");
+        }
+    }
+    ~RpcOperation() {
+        if (!m_success) {
+            trace("~RpcOperation: Closing control pipe");
+            m_wp.controlPipe.dispose(true);
+        }
+    }
+    void success() { m_success = true; }
+private:
+    winpty_t &m_wp;
+    bool m_success = false;
+};
+
+} // anonymous namespace
+
+
+
+/*****************************************************************************
+ * winpty agent RPC call: process creation. */
+
+// Return a std::wstring containing every character of the environment block.
+// Typically, the block is non-empty, so the std::wstring returned ends with
+// two NUL terminators.  (These two terminators are counted in size(), so
+// calling c_str() produces a triply-terminated string.)
+static std::wstring wstringFromEnvBlock(const wchar_t *env) {
+    std::wstring envStr;
+    if (env != NULL) {
+        const wchar_t *p = env;
+        while (*p != L'\0') {
+            p += wcslen(p) + 1;
+        }
+        p++;
+        envStr.assign(env, p);
+
+        // Assuming the environment was non-empty, envStr now ends with two NUL
+        // terminators.
+        //
+        // If the environment were empty, though, then envStr would only be
+        // singly terminated, but the MSDN documentation thinks an env block is
+        // always doubly-terminated, so add an extra NUL just in case it
+        // matters.
+        const auto envStrSz = envStr.size();
+        if (envStrSz == 1) {
+            ASSERT(envStr[0] == L'\0');
+            envStr.push_back(L'\0');
+        } else {
+            ASSERT(envStrSz >= 3);
+            ASSERT(envStr[envStrSz - 3] != L'\0');
+            ASSERT(envStr[envStrSz - 2] == L'\0');
+            ASSERT(envStr[envStrSz - 1] == L'\0');
+        }
+    }
+    return envStr;
+}
+
+WINPTY_API winpty_spawn_config_t *
+winpty_spawn_config_new(UINT64 winptyFlags,
+                        LPCWSTR appname /*OPTIONAL*/,
+                        LPCWSTR cmdline /*OPTIONAL*/,
+                        LPCWSTR cwd /*OPTIONAL*/,
+                        LPCWSTR env /*OPTIONAL*/,
+                        winpty_error_ptr_t *err /*OPTIONAL*/) {
+    API_TRY {
+        ASSERT((winptyFlags & WINPTY_SPAWN_FLAG_MASK) == winptyFlags);
+        std::unique_ptr<winpty_spawn_config_t> cfg(new winpty_spawn_config_t);
+        cfg->winptyFlags = winptyFlags;
+        if (appname != nullptr) { cfg->appname = appname; }
+        if (cmdline != nullptr) { cfg->cmdline = cmdline; }
+        if (cwd != nullptr) { cfg->cwd = cwd; }
+        if (env != nullptr) { cfg->env = wstringFromEnvBlock(env); }
+        return cfg.release();
+    } API_CATCH(nullptr)
+}
+
+WINPTY_API void winpty_spawn_config_free(winpty_spawn_config_t *cfg) {
+    delete cfg;
+}
+
+// It's safe to truncate a handle from 64-bits to 32-bits, or to sign-extend it
+// back to 64-bits.  See the MSDN article, "Interprocess Communication Between
+// 32-bit and 64-bit Applications".
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203.aspx
+static inline HANDLE handleFromInt64(int64_t i) {
+    return reinterpret_cast<HANDLE>(static_cast<intptr_t>(i));
+}
+
+// Given a process and a handle in that process, duplicate the handle into the
+// current process and close it in the originating process.
+static inline OwnedHandle stealHandle(HANDLE process, HANDLE handle) {
+    HANDLE result = nullptr;
+    if (!DuplicateHandle(process, handle,
+            GetCurrentProcess(),
+            &result, 0, FALSE,
+            DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
+        throwWindowsError(L"DuplicateHandle of process handle");
+    }
+    return OwnedHandle(result);
+}
+
+WINPTY_API BOOL
+winpty_spawn(winpty_t *wp,
+             const winpty_spawn_config_t *cfg,
+             HANDLE *process_handle /*OPTIONAL*/,
+             HANDLE *thread_handle /*OPTIONAL*/,
+             DWORD *create_process_error /*OPTIONAL*/,
+             winpty_error_ptr_t *err /*OPTIONAL*/) {
+    API_TRY {
+        ASSERT(wp != nullptr && cfg != nullptr);
+
+        if (process_handle != nullptr) { *process_handle = nullptr; }
+        if (thread_handle != nullptr) { *thread_handle = nullptr; }
+        if (create_process_error != nullptr) { *create_process_error = 0; }
+
+        LockGuard<Mutex> lock(wp->mutex);
+        RpcOperation rpc(*wp);
+
+        // Send spawn request.
+        auto packet = newPacket();
+        packet.putInt32(AgentMsg::StartProcess);
+        packet.putInt64(cfg->winptyFlags);
+        packet.putInt32(process_handle != nullptr);
+        packet.putInt32(thread_handle != nullptr);
+        packet.putWString(cfg->appname);
+        packet.putWString(cfg->cmdline);
+        packet.putWString(cfg->cwd);
+        packet.putWString(cfg->env);
+        packet.putWString(wp->spawnDesktopName);
+        writePacket(*wp, packet);
+
+        // Receive reply.
+        auto reply = readPacket(*wp);
+        const auto result = static_cast<StartProcessResult>(reply.getInt32());
+        if (result == StartProcessResult::CreateProcessFailed) {
+            const DWORD lastError = reply.getInt32();
+            reply.assertEof();
+            if (create_process_error != nullptr) {
+                *create_process_error = lastError;
+            }
+            rpc.success();
+            throw LibWinptyException(WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED,
+                L"CreateProcess failed");
+        } else if (result == StartProcessResult::ProcessCreated) {
+            const HANDLE remoteProcess = handleFromInt64(reply.getInt64());
+            const HANDLE remoteThread = handleFromInt64(reply.getInt64());
+            reply.assertEof();
+            OwnedHandle localProcess;
+            OwnedHandle localThread;
+            if (remoteProcess != nullptr) {
+                localProcess =
+                    stealHandle(wp->agentProcess.get(), remoteProcess);
+            }
+            if (remoteThread != nullptr) {
+                localThread =
+                    stealHandle(wp->agentProcess.get(), remoteThread);
+            }
+            if (process_handle != nullptr) {
+                *process_handle = localProcess.release();
+            }
+            if (thread_handle != nullptr) {
+                *thread_handle = localThread.release();
+            }
+            rpc.success();
+        } else {
+            throwWinptyException(
+                L"Agent RPC error: invalid StartProcessResult");
+        }
+        return TRUE;
+    } API_CATCH(FALSE)
+}
+
+
+
+/*****************************************************************************
+ * winpty agent RPC calls: everything else */
+
+WINPTY_API BOOL
+winpty_set_size(winpty_t *wp, int cols, int rows,
+                winpty_error_ptr_t *err /*OPTIONAL*/) {
+    API_TRY {
+        ASSERT(wp != nullptr && cols > 0 && rows > 0);
+        LockGuard<Mutex> lock(wp->mutex);
+        RpcOperation rpc(*wp);
+        auto packet = newPacket();
+        packet.putInt32(AgentMsg::SetSize);
+        packet.putInt32(cols);
+        packet.putInt32(rows);
+        writePacket(*wp, packet);
+        readPacket(*wp).assertEof();
+        rpc.success();
+        return TRUE;
+    } API_CATCH(FALSE)
+}
+
+WINPTY_API int
+winpty_get_console_process_list(winpty_t *wp, int *processList, const int processCount,
+                                winpty_error_ptr_t *err /*OPTIONAL*/) {
+    API_TRY {
+        ASSERT(wp != nullptr);
+        ASSERT(processList != nullptr);
+        LockGuard<Mutex> lock(wp->mutex);
+        RpcOperation rpc(*wp);
+        auto packet = newPacket();
+        packet.putInt32(AgentMsg::GetConsoleProcessList);
+        writePacket(*wp, packet);
+        auto reply = readPacket(*wp);
+
+        auto actualProcessCount = reply.getInt32();
+
+        if (actualProcessCount <= processCount) {
+            for (auto i = 0; i < actualProcessCount; i++) {
+                processList[i] = reply.getInt32();
+            }
+        }
+
+        reply.assertEof();
+        rpc.success();
+        return actualProcessCount;
+    } API_CATCH(0)
+}
+
+WINPTY_API void winpty_free(winpty_t *wp) {
+    // At least in principle, CloseHandle can fail, so this deletion can
+    // fail.  It won't throw an exception, but maybe there's an error that
+    // should be propagated?
+    delete wp;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/AgentMsg.h b/node_modules/node-pty/deps/winpty/src/shared/AgentMsg.h
new file mode 100644 (file)
index 0000000..ab60c6b
--- /dev/null
@@ -0,0 +1,38 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_AGENT_MSG_H
+#define WINPTY_SHARED_AGENT_MSG_H
+
+struct AgentMsg
+{
+    enum Type {
+        StartProcess,
+        SetSize,
+        GetConsoleProcessList,
+    };
+};
+
+enum class StartProcessResult {
+    CreateProcessFailed,
+    ProcessCreated,
+};
+
+#endif // WINPTY_SHARED_AGENT_MSG_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.cc b/node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.cc
new file mode 100644 (file)
index 0000000..1bea7e5
--- /dev/null
@@ -0,0 +1,122 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "BackgroundDesktop.h"
+
+#include <memory>
+
+#include "DebugClient.h"
+#include "StringUtil.h"
+#include "WinptyException.h"
+
+namespace {
+
+static std::wstring getObjectName(HANDLE object) {
+    BOOL success;
+    DWORD lengthNeeded = 0;
+    GetUserObjectInformationW(object, UOI_NAME,
+                              nullptr, 0,
+                              &lengthNeeded);
+    ASSERT(lengthNeeded % sizeof(wchar_t) == 0);
+    std::unique_ptr<wchar_t[]> tmp(
+        new wchar_t[lengthNeeded / sizeof(wchar_t)]);
+    success = GetUserObjectInformationW(object, UOI_NAME,
+                                        tmp.get(), lengthNeeded,
+                                        nullptr);
+    if (!success) {
+        throwWindowsError(L"GetUserObjectInformationW failed");
+    }
+    return std::wstring(tmp.get());
+}
+
+static std::wstring getDesktopName(HWINSTA winsta, HDESK desk) {
+    return getObjectName(winsta) + L"\\" + getObjectName(desk);
+}
+
+} // anonymous namespace
+
+// Get a non-interactive window station for the agent.
+// TODO: review security w.r.t. windowstation and desktop.
+BackgroundDesktop::BackgroundDesktop() {
+    try {
+        m_originalStation = GetProcessWindowStation();
+        if (m_originalStation == nullptr) {
+            throwWindowsError(
+                L"BackgroundDesktop ctor: "
+                L"GetProcessWindowStation returned NULL");
+        }
+        m_newStation =
+            CreateWindowStationW(nullptr, 0, WINSTA_ALL_ACCESS, nullptr);
+        if (m_newStation == nullptr) {
+            throwWindowsError(
+                L"BackgroundDesktop ctor: CreateWindowStationW returned NULL");
+        }
+        if (!SetProcessWindowStation(m_newStation)) {
+            throwWindowsError(
+                L"BackgroundDesktop ctor: SetProcessWindowStation failed");
+        }
+        m_newDesktop = CreateDesktopW(
+            L"Default", nullptr, nullptr, 0, GENERIC_ALL, nullptr);
+        if (m_newDesktop == nullptr) {
+            throwWindowsError(
+                L"BackgroundDesktop ctor: CreateDesktopW failed");
+        }
+        m_newDesktopName = getDesktopName(m_newStation, m_newDesktop);
+        TRACE("Created background desktop: %s",
+            utf8FromWide(m_newDesktopName).c_str());
+    } catch (...) {
+        dispose();
+        throw;
+    }
+}
+
+void BackgroundDesktop::dispose() WINPTY_NOEXCEPT {
+    if (m_originalStation != nullptr) {
+        SetProcessWindowStation(m_originalStation);
+        m_originalStation = nullptr;
+    }
+    if (m_newDesktop != nullptr) {
+        CloseDesktop(m_newDesktop);
+        m_newDesktop = nullptr;
+    }
+    if (m_newStation != nullptr) {
+        CloseWindowStation(m_newStation);
+        m_newStation = nullptr;
+    }
+}
+
+std::wstring getCurrentDesktopName() {
+    // MSDN says that the handles returned by GetProcessWindowStation and
+    // GetThreadDesktop do not need to be passed to CloseWindowStation and
+    // CloseDesktop, respectively.
+    const HWINSTA winsta = GetProcessWindowStation();
+    if (winsta == nullptr) {
+        throwWindowsError(
+            L"getCurrentDesktopName: "
+            L"GetProcessWindowStation returned NULL");
+    }
+    const HDESK desk = GetThreadDesktop(GetCurrentThreadId());
+    if (desk == nullptr) {
+        throwWindowsError(
+            L"getCurrentDesktopName: "
+            L"GetThreadDesktop returned NULL");
+    }
+    return getDesktopName(winsta, desk);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.h b/node_modules/node-pty/deps/winpty/src/shared/BackgroundDesktop.h
new file mode 100644 (file)
index 0000000..c692e57
--- /dev/null
@@ -0,0 +1,73 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_BACKGROUND_DESKTOP_H
+#define WINPTY_SHARED_BACKGROUND_DESKTOP_H
+
+#include <windows.h>
+
+#include <string>
+
+#include "WinptyException.h"
+
+class BackgroundDesktop {
+public:
+    BackgroundDesktop();
+    ~BackgroundDesktop() { dispose(); }
+    void dispose() WINPTY_NOEXCEPT;
+    const std::wstring &desktopName() const { return m_newDesktopName; }
+
+    BackgroundDesktop(const BackgroundDesktop &other) = delete;
+    BackgroundDesktop &operator=(const BackgroundDesktop &other) = delete;
+
+    // We can't default the move constructor and assignment operator with
+    // MSVC 2013.  We *could* if we required at least MSVC 2015 to build.
+
+    BackgroundDesktop(BackgroundDesktop &&other) :
+            m_originalStation(other.m_originalStation),
+            m_newStation(other.m_newStation),
+            m_newDesktop(other.m_newDesktop),
+            m_newDesktopName(std::move(other.m_newDesktopName)) {
+        other.m_originalStation = nullptr;
+        other.m_newStation = nullptr;
+        other.m_newDesktop = nullptr;
+    }
+    BackgroundDesktop &operator=(BackgroundDesktop &&other) {
+        dispose();
+        m_originalStation = other.m_originalStation;
+        m_newStation = other.m_newStation;
+        m_newDesktop = other.m_newDesktop;
+        m_newDesktopName = std::move(other.m_newDesktopName);
+        other.m_originalStation = nullptr;
+        other.m_newStation = nullptr;
+        other.m_newDesktop = nullptr;
+        return *this;
+    }
+
+private:
+    HWINSTA m_originalStation = nullptr;
+    HWINSTA m_newStation = nullptr;
+    HDESK m_newDesktop = nullptr;
+    std::wstring m_newDesktopName;
+};
+
+std::wstring getCurrentDesktopName();
+
+#endif // WINPTY_SHARED_BACKGROUND_DESKTOP_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/Buffer.cc b/node_modules/node-pty/deps/winpty/src/shared/Buffer.cc
new file mode 100644 (file)
index 0000000..158a629
--- /dev/null
@@ -0,0 +1,103 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "Buffer.h"
+
+#include <stdint.h>
+
+#include "DebugClient.h"
+#include "WinptyAssert.h"
+
+// Define the READ_BUFFER_CHECK() macro.  It *must* evaluate its condition,
+// exactly once.
+#define READ_BUFFER_CHECK(cond)                                 \
+    do {                                                        \
+        if (!(cond)) {                                          \
+            trace("decode error: %s", #cond);                   \
+            throw DecodeError();                                \
+        }                                                       \
+    } while (false)
+
+enum class Piece : uint8_t { Int32, Int64, WString };
+
+void WriteBuffer::putRawData(const void *data, size_t len) {
+    const auto p = reinterpret_cast<const char*>(data);
+    m_buf.insert(m_buf.end(), p, p + len);
+}
+
+void WriteBuffer::replaceRawData(size_t pos, const void *data, size_t len) {
+    ASSERT(pos <= m_buf.size() && len <= m_buf.size() - pos);
+    const auto p = reinterpret_cast<const char*>(data);
+    std::copy(p, p + len, &m_buf[pos]);
+}
+
+void WriteBuffer::putInt32(int32_t i) {
+    putRawValue(Piece::Int32);
+    putRawValue(i);
+}
+
+void WriteBuffer::putInt64(int64_t i) {
+    putRawValue(Piece::Int64);
+    putRawValue(i);
+}
+
+// len is in characters, excluding NUL, i.e. the number of wchar_t elements
+void WriteBuffer::putWString(const wchar_t *str, size_t len) {
+    putRawValue(Piece::WString);
+    putRawValue(static_cast<uint64_t>(len));
+    putRawData(str, sizeof(wchar_t) * len);
+}
+
+void ReadBuffer::getRawData(void *data, size_t len) {
+    ASSERT(m_off <= m_buf.size());
+    READ_BUFFER_CHECK(len <= m_buf.size() - m_off);
+    const char *const inp = &m_buf[m_off];
+    std::copy(inp, inp + len, reinterpret_cast<char*>(data));
+    m_off += len;
+}
+
+int32_t ReadBuffer::getInt32() {
+    READ_BUFFER_CHECK(getRawValue<Piece>() == Piece::Int32);
+    return getRawValue<int32_t>();
+}
+
+int64_t ReadBuffer::getInt64() {
+    READ_BUFFER_CHECK(getRawValue<Piece>() == Piece::Int64);
+    return getRawValue<int64_t>();
+}
+
+std::wstring ReadBuffer::getWString() {
+    READ_BUFFER_CHECK(getRawValue<Piece>() == Piece::WString);
+    const uint64_t charLen = getRawValue<uint64_t>();
+    READ_BUFFER_CHECK(charLen <= SIZE_MAX / sizeof(wchar_t));
+    // To be strictly conforming, we can't use the convenient wstring
+    // constructor, because the string in m_buf mightn't be aligned.
+    std::wstring ret;
+    if (charLen > 0) {
+        const size_t byteLen = charLen * sizeof(wchar_t);
+        ret.resize(charLen);
+        getRawData(&ret[0], byteLen);
+    }
+    return ret;
+}
+
+void ReadBuffer::assertEof() {
+    READ_BUFFER_CHECK(m_off == m_buf.size());
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/Buffer.h b/node_modules/node-pty/deps/winpty/src/shared/Buffer.h
new file mode 100644 (file)
index 0000000..c2dd382
--- /dev/null
@@ -0,0 +1,102 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_BUFFER_H
+#define WINPTY_SHARED_BUFFER_H
+
+#include <stdint.h>
+#include <string.h>
+
+#include <algorithm>
+#include <utility>
+#include <vector>
+#include <string>
+
+#include "WinptyException.h"
+
+class WriteBuffer {
+private:
+    std::vector<char> m_buf;
+
+public:
+    WriteBuffer() {}
+
+    template <typename T> void putRawValue(const T &t) {
+        putRawData(&t, sizeof(t));
+    }
+    template <typename T> void replaceRawValue(size_t pos, const T &t) {
+        replaceRawData(pos, &t, sizeof(t));
+    }
+
+    void putRawData(const void *data, size_t len);
+    void replaceRawData(size_t pos, const void *data, size_t len);
+    void putInt32(int32_t i);
+    void putInt64(int64_t i);
+    void putWString(const wchar_t *str, size_t len);
+    void putWString(const wchar_t *str)         { putWString(str, wcslen(str)); }
+    void putWString(const std::wstring &str)    { putWString(str.data(), str.size()); }
+    std::vector<char> &buf()                    { return m_buf; }
+
+    // MSVC 2013 does not generate these automatically, so help it out.
+    WriteBuffer(WriteBuffer &&other) : m_buf(std::move(other.m_buf)) {}
+    WriteBuffer &operator=(WriteBuffer &&other) {
+        m_buf = std::move(other.m_buf);
+        return *this;
+    }
+};
+
+class ReadBuffer {
+public:
+    class DecodeError : public WinptyException {
+        virtual const wchar_t *what() const WINPTY_NOEXCEPT override {
+            return L"DecodeError: RPC message decoding error";
+        }
+    };
+
+private:
+    std::vector<char> m_buf;
+    size_t m_off = 0;
+
+public:
+    explicit ReadBuffer(std::vector<char> &&buf) : m_buf(std::move(buf)) {}
+
+    template <typename T> T getRawValue() {
+        T ret = {};
+        getRawData(&ret, sizeof(ret));
+        return ret;
+    }
+
+    void getRawData(void *data, size_t len);
+    int32_t getInt32();
+    int64_t getInt64();
+    std::wstring getWString();
+    void assertEof();
+
+    // MSVC 2013 does not generate these automatically, so help it out.
+    ReadBuffer(ReadBuffer &&other) :
+        m_buf(std::move(other.m_buf)), m_off(other.m_off) {}
+    ReadBuffer &operator=(ReadBuffer &&other) {
+        m_buf = std::move(other.m_buf);
+        m_off = other.m_off;
+        return *this;
+    }
+};
+
+#endif // WINPTY_SHARED_BUFFER_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/DebugClient.cc b/node_modules/node-pty/deps/winpty/src/shared/DebugClient.cc
new file mode 100644 (file)
index 0000000..bafe0c8
--- /dev/null
@@ -0,0 +1,187 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#include "DebugClient.h"
+
+#include <windows.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <algorithm>
+#include <string>
+
+#include "winpty_snprintf.h"
+
+const wchar_t *const kPipeName = L"\\\\.\\pipe\\DebugServer";
+
+void *volatile g_debugConfig;
+
+namespace {
+
+// It would be easy to accidentally trample on the Windows LastError value
+// by adding logging/debugging code.  Ensure that can't happen by saving and
+// restoring the value.  This saving and restoring doesn't happen along the
+// fast path.
+class PreserveLastError {
+public:
+    PreserveLastError() : m_lastError(GetLastError()) {}
+    ~PreserveLastError() { SetLastError(m_lastError); }
+private:
+    DWORD m_lastError;
+};
+
+} // anonymous namespace
+
+static void sendToDebugServer(const char *message)
+{
+    HANDLE tracePipe = INVALID_HANDLE_VALUE;
+
+    do {
+        // The default impersonation level is SECURITY_IMPERSONATION, which allows
+        // a sufficiently authorized named pipe server to impersonate the client.
+        // There's no need for impersonation in this debugging system, so reduce
+        // the impersonation level to SECURITY_IDENTIFICATION, which allows a
+        // server to merely identify us.
+        tracePipe = CreateFileW(
+            kPipeName,
+            GENERIC_READ | GENERIC_WRITE,
+            0, NULL, OPEN_EXISTING,
+            SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
+            NULL);
+    } while (tracePipe == INVALID_HANDLE_VALUE &&
+             GetLastError() == ERROR_PIPE_BUSY &&
+             WaitNamedPipeW(kPipeName, NMPWAIT_WAIT_FOREVER));
+
+    if (tracePipe != INVALID_HANDLE_VALUE) {
+        DWORD newMode = PIPE_READMODE_MESSAGE;
+        SetNamedPipeHandleState(tracePipe, &newMode, NULL, NULL);
+        char response[16];
+        DWORD actual = 0;
+        TransactNamedPipe(tracePipe,
+            const_cast<char*>(message), strlen(message),
+            response, sizeof(response), &actual, NULL);
+        CloseHandle(tracePipe);
+    }
+}
+
+// Get the current UTC time as milliseconds from the epoch (ignoring leap
+// seconds).  Use the Unix epoch for consistency with DebugClient.py.  There
+// are 134774 days between 1601-01-01 (the Win32 epoch) and 1970-01-01 (the
+// Unix epoch).
+static long long unixTimeMillis()
+{
+    FILETIME fileTime;
+    GetSystemTimeAsFileTime(&fileTime);
+    long long msTime = (((long long)fileTime.dwHighDateTime << 32) +
+                       fileTime.dwLowDateTime) / 10000;
+    return msTime - 134774LL * 24 * 3600 * 1000;
+}
+
+static const char *getDebugConfig()
+{
+    if (g_debugConfig == NULL) {
+        PreserveLastError preserve;
+        const int bufSize = 256;
+        char buf[bufSize];
+        DWORD actualSize =
+            GetEnvironmentVariableA("WINPTY_DEBUG", buf, bufSize);
+        if (actualSize == 0 || actualSize >= static_cast<DWORD>(bufSize)) {
+            buf[0] = '\0';
+        }
+        const size_t len = strlen(buf) + 1;
+        char *newConfig = new char[len];
+        std::copy(buf, buf + len, newConfig);
+        void *oldValue = InterlockedCompareExchangePointer(
+            &g_debugConfig, newConfig, NULL);
+        if (oldValue != NULL) {
+            delete [] newConfig;
+        }
+    }
+    return static_cast<const char*>(g_debugConfig);
+}
+
+bool isTracingEnabled()
+{
+    static bool disabled, enabled;
+    if (disabled) {
+        return false;
+    } else if (enabled) {
+        return true;
+    } else {
+        // Recognize WINPTY_DEBUG=1 for backwards compatibility.
+        PreserveLastError preserve;
+        bool value = hasDebugFlag("trace") || hasDebugFlag("1");
+        disabled = !value;
+        enabled = value;
+        return value;
+    }
+}
+
+bool hasDebugFlag(const char *flag)
+{
+    if (strchr(flag, ',') != NULL) {
+        trace("INTERNAL ERROR: hasDebugFlag flag has comma: '%s'", flag);
+        abort();
+    }
+    const char *const configCStr = getDebugConfig();
+    if (configCStr[0] == '\0') {
+        return false;
+    }
+    PreserveLastError preserve;
+    std::string config(configCStr);
+    std::string flagStr(flag);
+    config = "," + config + ",";
+    flagStr = "," + flagStr + ",";
+    return config.find(flagStr) != std::string::npos;
+}
+
+void trace(const char *format, ...)
+{
+    if (!isTracingEnabled())
+        return;
+
+    PreserveLastError preserve;
+    char message[1024];
+
+    va_list ap;
+    va_start(ap, format);
+    winpty_vsnprintf(message, format, ap);
+    message[sizeof(message) - 1] = '\0';
+    va_end(ap);
+
+    const int currentTime = (int)(unixTimeMillis() % (100000 * 1000));
+
+    char moduleName[1024];
+    moduleName[0] = '\0';
+    GetModuleFileNameA(NULL, moduleName, sizeof(moduleName));
+    const char *baseName = strrchr(moduleName, '\\');
+    baseName = (baseName != NULL) ? baseName + 1 : moduleName;
+
+    char fullMessage[1024];
+    winpty_snprintf(fullMessage,
+             "[%05d.%03d %s,p%04d,t%04d]: %s",
+             currentTime / 1000, currentTime % 1000,
+             baseName, (int)GetCurrentProcessId(), (int)GetCurrentThreadId(),
+             message);
+    fullMessage[sizeof(fullMessage) - 1] = '\0';
+
+    sendToDebugServer(fullMessage);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/DebugClient.h b/node_modules/node-pty/deps/winpty/src/shared/DebugClient.h
new file mode 100644 (file)
index 0000000..b126071
--- /dev/null
@@ -0,0 +1,38 @@
+// Copyright (c) 2011-2012 Ryan Prichard
+//
+// 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.
+
+#ifndef DEBUGCLIENT_H
+#define DEBUGCLIENT_H
+
+#include "winpty_snprintf.h"
+
+bool isTracingEnabled();
+bool hasDebugFlag(const char *flag);
+void trace(const char *format, ...) WINPTY_SNPRINTF_FORMAT(1, 2);
+
+// This macro calls trace without evaluating the arguments.
+#define TRACE(format, ...)                          \
+    do {                                            \
+        if (isTracingEnabled()) {                   \
+            trace((format), ## __VA_ARGS__);        \
+        }                                           \
+    } while (false)
+
+#endif // DEBUGCLIENT_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/GenRandom.cc b/node_modules/node-pty/deps/winpty/src/shared/GenRandom.cc
new file mode 100644 (file)
index 0000000..6d79206
--- /dev/null
@@ -0,0 +1,138 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "GenRandom.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#include "DebugClient.h"
+#include "StringBuilder.h"
+
+static volatile LONG g_pipeCounter;
+
+GenRandom::GenRandom() : m_advapi32(L"advapi32.dll") {
+    // First try to use the pseudo-documented RtlGenRandom function from
+    // advapi32.dll.  Creating a CryptoAPI context is slow, and RtlGenRandom
+    // avoids the overhead.  It's documented in this blog post[1] and on
+    // MSDN[2] with a disclaimer about future breakage.  This technique is
+    // apparently built-in into the MSVC CRT, though, for the rand_s function,
+    // so perhaps it is stable enough.
+    //
+    // [1] http://blogs.msdn.com/b/michael_howard/archive/2005/01/14/353379.aspx
+    // [2] https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694(v=vs.85).aspx
+    //
+    // Both RtlGenRandom and the Crypto API functions exist in XP and up.
+    m_rtlGenRandom = reinterpret_cast<RtlGenRandom_t*>(
+        m_advapi32.proc("SystemFunction036"));
+    // The OsModule class logs an error message if the proc is nullptr.
+    if (m_rtlGenRandom != nullptr) {
+        return;
+    }
+
+    // Fall back to the crypto API.
+    m_cryptProvIsValid =
+        CryptAcquireContext(&m_cryptProv, nullptr, nullptr,
+                            PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) != 0;
+    if (!m_cryptProvIsValid) {
+        trace("GenRandom: CryptAcquireContext failed: %u",
+            static_cast<unsigned>(GetLastError()));
+    }
+}
+
+GenRandom::~GenRandom() {
+    if (m_cryptProvIsValid) {
+        CryptReleaseContext(m_cryptProv, 0);
+    }
+}
+
+// Returns false if the context is invalid or the generation fails.
+bool GenRandom::fillBuffer(void *buffer, size_t size) {
+    memset(buffer, 0, size);
+    bool success = false;
+    if (m_rtlGenRandom != nullptr) {
+        success = m_rtlGenRandom(buffer, size) != 0;
+        if (!success) {
+            trace("GenRandom: RtlGenRandom/SystemFunction036 failed: %u",
+                static_cast<unsigned>(GetLastError()));
+        }
+    } else if (m_cryptProvIsValid) {
+        success =
+            CryptGenRandom(m_cryptProv, size,
+                           reinterpret_cast<BYTE*>(buffer)) != 0;
+        if (!success) {
+            trace("GenRandom: CryptGenRandom failed, size=%d, lasterror=%u",
+                static_cast<int>(size),
+                static_cast<unsigned>(GetLastError()));
+        }
+    }
+    return success;
+}
+
+// Returns an empty string if either of CryptAcquireContext or CryptGenRandom
+// fail.
+std::string GenRandom::randomBytes(size_t numBytes) {
+    std::string ret(numBytes, '\0');
+    if (!fillBuffer(&ret[0], numBytes)) {
+        return std::string();
+    }
+    return ret;
+}
+
+std::wstring GenRandom::randomHexString(size_t numBytes) {
+    const std::string bytes = randomBytes(numBytes);
+    std::wstring ret(bytes.size() * 2, L'\0');
+    for (size_t i = 0; i < bytes.size(); ++i) {
+        static const wchar_t hex[] = L"0123456789abcdef";
+        ret[i * 2]     = hex[static_cast<uint8_t>(bytes[i]) >> 4];
+        ret[i * 2 + 1] = hex[static_cast<uint8_t>(bytes[i]) & 0xF];
+    }
+    return ret;
+}
+
+// Returns a 64-bit value representing the number of 100-nanosecond intervals
+// since January 1, 1601.
+static uint64_t systemTimeAsUInt64() {
+    FILETIME monotonicTime = {};
+    GetSystemTimeAsFileTime(&monotonicTime);
+    return (static_cast<uint64_t>(monotonicTime.dwHighDateTime) << 32) |
+            static_cast<uint64_t>(monotonicTime.dwLowDateTime);
+}
+
+// Generates a unique and hard-to-guess case-insensitive string suitable for
+// use in a pipe filename or a Windows object name.
+std::wstring GenRandom::uniqueName() {
+    // First include enough information to avoid collisions assuming
+    // cooperative software.  This code assumes that a process won't die and
+    // be replaced with a recycled PID within a single GetSystemTimeAsFileTime
+    // interval.
+    WStringBuilder sb(64);
+    sb << GetCurrentProcessId()
+       << L'-' << InterlockedIncrement(&g_pipeCounter)
+       << L'-' << whexOfInt(systemTimeAsUInt64());
+    // It isn't clear to me how the crypto APIs would fail.  It *probably*
+    // doesn't matter that much anyway?  In principle, a predictable pipe name
+    // is subject to a local denial-of-service attack.
+    auto random = randomHexString(16);
+    if (!random.empty()) {
+        sb << L'-' << random;
+    }
+    return sb.str_moved();
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/GenRandom.h b/node_modules/node-pty/deps/winpty/src/shared/GenRandom.h
new file mode 100644 (file)
index 0000000..746cb1e
--- /dev/null
@@ -0,0 +1,55 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_GEN_RANDOM_H
+#define WINPTY_GEN_RANDOM_H
+
+// The original MinGW requires that we include wincrypt.h.  With MinGW-w64 and
+// MSVC, including windows.h is sufficient.
+#include <windows.h>
+#include <wincrypt.h>
+
+#include <string>
+
+#include "OsModule.h"
+
+class GenRandom {
+    typedef BOOLEAN WINAPI RtlGenRandom_t(PVOID, ULONG);
+
+    OsModule m_advapi32;
+    RtlGenRandom_t *m_rtlGenRandom = nullptr;
+    bool m_cryptProvIsValid = false;
+    HCRYPTPROV m_cryptProv = 0;
+
+public:
+    GenRandom();
+    ~GenRandom();
+    bool fillBuffer(void *buffer, size_t size);
+    std::string randomBytes(size_t numBytes);
+    std::wstring randomHexString(size_t numBytes);
+    std::wstring uniqueName();
+
+    // Return true if the crypto context was successfully initialized.
+    bool valid() const {
+        return m_rtlGenRandom != nullptr || m_cryptProvIsValid;
+    }
+};
+
+#endif // WINPTY_GEN_RANDOM_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/GetCommitHash.bat b/node_modules/node-pty/deps/winpty/src/shared/GetCommitHash.bat
new file mode 100644 (file)
index 0000000..a9f8e9c
--- /dev/null
@@ -0,0 +1,13 @@
+@echo off
+
+REM -- Echo the git commit hash.  If git isn't available for some reason,
+REM -- output nothing instead.
+
+git rev-parse HEAD >NUL 2>NUL && (
+    git rev-parse HEAD
+) || (
+    echo none
+)
+
+REM -- Set ERRORLEVEL to 0 using this cryptic syntax.
+(call )
diff --git a/node_modules/node-pty/deps/winpty/src/shared/Mutex.h b/node_modules/node-pty/deps/winpty/src/shared/Mutex.h
new file mode 100644 (file)
index 0000000..9821536
--- /dev/null
@@ -0,0 +1,54 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+// Recent 4.x MinGW and MinGW-w64 gcc compilers lack std::mutex and
+// std::lock_guard.  I have a 5.2.0 MinGW-w64 compiler packaged through MSYS2
+// that *is* new enough, but that's one compiler against several deficient
+// ones.  Wrap CRITICAL_SECTION instead.
+
+#ifndef WINPTY_SHARED_MUTEX_H
+#define WINPTY_SHARED_MUTEX_H
+
+#include <windows.h>
+
+class Mutex {
+    CRITICAL_SECTION m_mutex;
+public:
+    Mutex()         { InitializeCriticalSection(&m_mutex);  }
+    ~Mutex()        { DeleteCriticalSection(&m_mutex);      }
+    void lock()     { EnterCriticalSection(&m_mutex);       }
+    void unlock()   { LeaveCriticalSection(&m_mutex);       }
+
+    Mutex(const Mutex &other) = delete;
+    Mutex &operator=(const Mutex &other) = delete;
+};
+
+template <typename T>
+class LockGuard {
+    T &m_lock;
+public:
+    LockGuard(T &lock) : m_lock(lock)  { m_lock.lock();    }
+    ~LockGuard()                       { m_lock.unlock();  }
+
+    LockGuard(const LockGuard &other) = delete;
+    LockGuard &operator=(const LockGuard &other) = delete;
+};
+
+#endif // WINPTY_SHARED_MUTEX_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/OsModule.h b/node_modules/node-pty/deps/winpty/src/shared/OsModule.h
new file mode 100644 (file)
index 0000000..9713fa2
--- /dev/null
@@ -0,0 +1,63 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_OS_MODULE_H
+#define WINPTY_SHARED_OS_MODULE_H
+
+#include <windows.h>
+
+#include <string>
+
+#include "DebugClient.h"
+#include "WinptyAssert.h"
+#include "WinptyException.h"
+
+class OsModule {
+    HMODULE m_module;
+public:
+    enum class LoadErrorBehavior { Abort, Throw };
+    OsModule(const wchar_t *fileName,
+            LoadErrorBehavior behavior=LoadErrorBehavior::Abort) {
+        m_module = LoadLibraryW(fileName);
+        if (behavior == LoadErrorBehavior::Abort) {
+            ASSERT(m_module != NULL);
+        } else {
+            if (m_module == nullptr) {
+                const auto err = GetLastError();
+                throwWindowsError(
+                    (L"LoadLibraryW error: " + std::wstring(fileName)).c_str(),
+                    err);
+            }
+        }
+    }
+    ~OsModule() {
+        FreeLibrary(m_module);
+    }
+    HMODULE handle() const { return m_module; }
+    FARPROC proc(const char *funcName) {
+        FARPROC ret = GetProcAddress(m_module, funcName);
+        if (ret == NULL) {
+            trace("GetProcAddress: %s is missing", funcName);
+        }
+        return ret;
+    }
+};
+
+#endif // WINPTY_SHARED_OS_MODULE_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.cc b/node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.cc
new file mode 100644 (file)
index 0000000..7b17353
--- /dev/null
@@ -0,0 +1,36 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "OwnedHandle.h"
+
+#include "DebugClient.h"
+#include "WinptyException.h"
+
+void OwnedHandle::dispose(bool nothrow) {
+    if (m_h != nullptr && m_h != INVALID_HANDLE_VALUE) {
+        if (!CloseHandle(m_h)) {
+            trace("CloseHandle(%p) failed", m_h);
+            if (!nothrow) {
+                throwWindowsError(L"CloseHandle failed");
+            }
+        }
+    }
+    m_h = nullptr;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.h b/node_modules/node-pty/deps/winpty/src/shared/OwnedHandle.h
new file mode 100644 (file)
index 0000000..70a8d61
--- /dev/null
@@ -0,0 +1,45 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_OWNED_HANDLE_H
+#define WINPTY_SHARED_OWNED_HANDLE_H
+
+#include <windows.h>
+
+class OwnedHandle {
+    HANDLE m_h;
+public:
+    OwnedHandle() : m_h(nullptr) {}
+    explicit OwnedHandle(HANDLE h) : m_h(h) {}
+    ~OwnedHandle() { dispose(true); }
+    void dispose(bool nothrow=false);
+    HANDLE get() const { return m_h; }
+    HANDLE release() { HANDLE ret = m_h; m_h = nullptr; return ret; }
+    OwnedHandle(const OwnedHandle &other) = delete;
+    OwnedHandle(OwnedHandle &&other) : m_h(other.release()) {}
+    OwnedHandle &operator=(const OwnedHandle &other) = delete;
+    OwnedHandle &operator=(OwnedHandle &&other) {
+        dispose();
+        m_h = other.release();
+        return *this;
+    }
+};
+
+#endif // WINPTY_SHARED_OWNED_HANDLE_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/PrecompiledHeader.h b/node_modules/node-pty/deps/winpty/src/shared/PrecompiledHeader.h
new file mode 100644 (file)
index 0000000..7d9b8f8
--- /dev/null
@@ -0,0 +1,43 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_PRECOMPILED_HEADER_H
+#define WINPTY_PRECOMPILED_HEADER_H
+
+#include <windows.h>
+
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+
+#include <array>
+#include <limits>
+#include <memory>
+#include <new>
+#include <string>
+#include <tuple>
+#include <type_traits>
+#include <utility>
+#include <vector>
+
+#endif // WINPTY_PRECOMPILED_HEADER_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/StringBuilder.h b/node_modules/node-pty/deps/winpty/src/shared/StringBuilder.h
new file mode 100644 (file)
index 0000000..f3155bd
--- /dev/null
@@ -0,0 +1,227 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+// Efficient integer->string conversion and string concatenation.  The
+// hexadecimal conversion may optionally have leading zeros.  Other ways to
+// convert integers to strings in C++ suffer these drawbacks:
+//
+//  * std::stringstream: Inefficient, even more so than stdio.
+//
+//  * std::to_string: No hexadecimal output, tends to use heap allocation, not
+//    supported on Cygwin.
+//
+//  * stdio routines: Requires parsing a format string (inefficient).  The
+//    caller *must* know how large the content is for correctness.  The
+//    string-printf functions are extremely inconsistent on Windows.  In
+//    particular, 64-bit integers, wide strings, and return values are
+//    problem areas.
+//
+// StringBuilderTest.cc is a standalone program that tests this header.
+
+#ifndef WINPTY_STRING_BUILDER_H
+#define WINPTY_STRING_BUILDER_H
+
+#include <array>
+#include <string>
+#include <type_traits>
+
+#ifdef STRING_BUILDER_TESTING
+#include <assert.h>
+#define STRING_BUILDER_CHECK(cond) assert(cond)
+#else
+#define STRING_BUILDER_CHECK(cond)
+#endif // STRING_BUILDER_TESTING
+
+#include "WinptyAssert.h"
+
+template <typename C, size_t sz>
+struct ValueString {
+    std::array<C, sz> m_array;
+    size_t m_offset;
+    size_t m_size;
+
+    const C *c_str() const { return m_array.data() + m_offset; }
+    const C *data() const { return m_array.data() + m_offset; }
+    size_t size() const { return m_size; }
+    std::basic_string<C> str() const {
+        return std::basic_string<C>(data(), m_size);
+    }
+};
+
+#ifdef _MSC_VER
+// Disable an MSVC /SDL error that forbids unsigned negation.  Signed negation
+// invokes undefined behavior for INTxx_MIN, so unsigned negation is simpler to
+// reason about.  (We assume twos-complement in any case.)
+#define STRING_BUILDER_ALLOW_UNSIGNED_NEGATE(x) \
+    (                                           \
+        __pragma(warning(push))                 \
+        __pragma(warning(disable:4146))         \
+        (x)                                     \
+        __pragma(warning(pop))                  \
+    )
+#else
+#define STRING_BUILDER_ALLOW_UNSIGNED_NEGATE(x) (x)
+#endif
+
+// Formats an integer as decimal without leading zeros.
+template <typename C, typename I>
+ValueString<C, sizeof(I) * 3 + 1 + 1> gdecOfInt(const I value) {
+    typedef typename std::make_unsigned<I>::type U;
+    auto unsValue = static_cast<U>(value);
+    const bool isNegative = (value < 0);
+    if (isNegative) {
+        unsValue = STRING_BUILDER_ALLOW_UNSIGNED_NEGATE(-unsValue);
+    }
+    decltype(gdecOfInt<C, I>(value)) out;
+    auto &arr = out.m_array;
+    C *const endp = arr.data() + arr.size();
+    C *outp = endp;
+    *(--outp) = '\0';
+    STRING_BUILDER_CHECK(outp >= arr.data());
+    do {
+        const int digit = unsValue % 10;
+        unsValue /= 10;
+        *(--outp) = '0' + digit;
+        STRING_BUILDER_CHECK(outp >= arr.data());
+    } while (unsValue != 0);
+    if (isNegative) {
+        *(--outp) = '-';
+        STRING_BUILDER_CHECK(outp >= arr.data());
+    }
+    out.m_offset = outp - arr.data();
+    out.m_size = endp - outp - 1;
+    return out;
+}
+
+template <typename I> decltype(gdecOfInt<char, I>(0)) decOfInt(I i) {
+    return gdecOfInt<char>(i);
+}
+
+template <typename I> decltype(gdecOfInt<wchar_t, I>(0)) wdecOfInt(I i) {
+    return gdecOfInt<wchar_t>(i);
+}
+
+// Formats an integer as hexadecimal, with or without leading zeros.
+template <typename C, bool leadingZeros=false, typename I>
+ValueString<C, sizeof(I) * 2 + 1> ghexOfInt(const I value) {
+    typedef typename std::make_unsigned<I>::type U;
+    const auto unsValue = static_cast<U>(value);
+    static const C hex[16] = {'0','1','2','3','4','5','6','7',
+                              '8','9','a','b','c','d','e','f'};
+    decltype(ghexOfInt<C, leadingZeros, I>(value)) out;
+    auto &arr = out.m_array;
+    C *outp = arr.data();
+    int inIndex = 0;
+    int shift = sizeof(I) * 8 - 4;
+    const int len = sizeof(I) * 2;
+    if (!leadingZeros) {
+        for (; inIndex < len - 1; ++inIndex, shift -= 4) {
+            STRING_BUILDER_CHECK(shift >= 0 && shift < sizeof(unsValue) * 8);
+            const int digit = (unsValue >> shift) & 0xF;
+            if (digit != 0) {
+                break;
+            }
+        }
+    }
+    for (; inIndex < len; ++inIndex, shift -= 4) {
+        const int digit = (unsValue >> shift) & 0xF;
+        *(outp++) = hex[digit];
+        STRING_BUILDER_CHECK(outp <= arr.data() + arr.size());
+    }
+    *(outp++) = '\0';
+    STRING_BUILDER_CHECK(outp <= arr.data() + arr.size());
+    out.m_offset = 0;
+    out.m_size = outp - arr.data() - 1;
+    return out;
+}
+
+template <bool leadingZeros=false, typename I>
+decltype(ghexOfInt<char, leadingZeros, I>(0)) hexOfInt(I i) {
+    return ghexOfInt<char, leadingZeros, I>(i);
+}
+
+template <bool leadingZeros=false, typename I>
+decltype(ghexOfInt<wchar_t, leadingZeros, I>(0)) whexOfInt(I i) {
+    return ghexOfInt<wchar_t, leadingZeros, I>(i);
+}
+
+template <typename C>
+class GStringBuilder {
+public:
+    typedef std::basic_string<C> StringType;
+
+    GStringBuilder() {}
+    GStringBuilder(size_t capacity) {
+        m_out.reserve(capacity);
+    }
+
+    GStringBuilder &operator<<(C ch) { m_out.push_back(ch); return *this; }
+    GStringBuilder &operator<<(const C *str) { m_out.append(str); return *this; }
+    GStringBuilder &operator<<(const StringType &str) { m_out.append(str); return *this; }
+
+    template <size_t sz>
+    GStringBuilder &operator<<(const ValueString<C, sz> &str) {
+        m_out.append(str.data(), str.size());
+        return *this;
+    }
+
+private:
+    // Forbid output of char/wchar_t for GStringBuilder if the type doesn't
+    // exactly match the builder element type.  The code still allows
+    // signed char and unsigned char, but I'm a little worried about what
+    // happens if a user tries to output int8_t or uint8_t.
+    template <typename P>
+    typename std::enable_if<
+        (std::is_same<P, char>::value || std::is_same<P, wchar_t>::value) &&
+        !std::is_same<C, P>::value, GStringBuilder&>::type
+    operator<<(P ch) {
+        ASSERT(false && "Method was not supposed to be reachable.");
+        return *this;
+    }
+
+public:
+    GStringBuilder &operator<<(short i)              { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(unsigned short i)     { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(int i)                { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(unsigned int i)       { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(long i)               { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(unsigned long i)      { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(long long i)          { return *this << gdecOfInt<C>(i); }
+    GStringBuilder &operator<<(unsigned long long i) { return *this << gdecOfInt<C>(i); }
+
+    GStringBuilder &operator<<(const void *p) {
+        m_out.push_back(static_cast<C>('0'));
+        m_out.push_back(static_cast<C>('x'));
+        *this << ghexOfInt<C>(reinterpret_cast<uintptr_t>(p));
+        return *this;
+    }
+
+    StringType str() { return m_out; }
+    StringType str_moved() { return std::move(m_out); }
+    const C *c_str() const { return m_out.c_str(); }
+
+private:
+    StringType m_out;
+};
+
+typedef GStringBuilder<char> StringBuilder;
+typedef GStringBuilder<wchar_t> WStringBuilder;
+
+#endif // WINPTY_STRING_BUILDER_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/StringBuilderTest.cc b/node_modules/node-pty/deps/winpty/src/shared/StringBuilderTest.cc
new file mode 100644 (file)
index 0000000..e6c2d31
--- /dev/null
@@ -0,0 +1,114 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#define STRING_BUILDER_TESTING
+
+#include "StringBuilder.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include <iomanip>
+#include <sstream>
+
+void display(const std::string &str) { fprintf(stderr, "%s", str.c_str()); }
+void display(const std::wstring &str) { fprintf(stderr, "%ls", str.c_str()); }
+
+#define CHECK_EQ(x, y) \
+    do {                                                    \
+        const auto xval = (x);                              \
+        const auto yval = (y);                              \
+        if (xval != yval) {                                 \
+            fprintf(stderr, "error: %s:%d: %s != %s: ",     \
+                __FILE__, __LINE__, #x, #y);                \
+            display(xval);                                  \
+            fprintf(stderr, " != ");                        \
+            display(yval);                                  \
+            fprintf(stderr, "\n");                          \
+        }                                                   \
+    } while(0)
+
+template <typename C, typename I>
+std::basic_string<C> decOfIntSS(const I value) {
+    // std::to_string and std::to_wstring are missing in Cygwin as of this
+    // writing (early 2016).
+    std::basic_stringstream<C> ss;
+    ss << +value; // We must promote char to print it as an integer.
+    return ss.str();
+}
+
+
+template <typename C, bool leadingZeros=false, typename I>
+std::basic_string<C> hexOfIntSS(const I value) {
+    typedef typename std::make_unsigned<I>::type U;
+    const unsigned long long u64Value = value & static_cast<U>(~0);
+    std::basic_stringstream<C> ss;
+    if (leadingZeros) {
+        ss << std::setfill(static_cast<C>('0')) << std::setw(sizeof(I) * 2);
+    }
+    ss << std::hex << u64Value;
+    return ss.str();
+}
+
+template <typename I>
+void testValue(I value) {
+    CHECK_EQ(decOfInt(value).str(), (decOfIntSS<char>(value)));
+    CHECK_EQ(wdecOfInt(value).str(), (decOfIntSS<wchar_t>(value)));
+    CHECK_EQ((hexOfInt<false>(value).str()), (hexOfIntSS<char, false>(value)));
+    CHECK_EQ((hexOfInt<true>(value).str()), (hexOfIntSS<char, true>(value)));
+    CHECK_EQ((whexOfInt<false>(value).str()), (hexOfIntSS<wchar_t, false>(value)));
+    CHECK_EQ((whexOfInt<true>(value).str()), (hexOfIntSS<wchar_t, true>(value)));
+}
+
+template <typename I>
+void testType() {
+    typedef typename std::make_unsigned<I>::type U;
+    const U quarter = static_cast<U>(1) << (sizeof(U) * 8 - 2);
+    for (unsigned quarterIndex = 0; quarterIndex < 4; ++quarterIndex) {
+        for (int offset = -18; offset <= 18; ++offset) {
+            const I value = quarter * quarterIndex + static_cast<U>(offset);
+            testValue(value);
+        }
+    }
+    testValue(static_cast<I>(42));
+    testValue(static_cast<I>(123456));
+    testValue(static_cast<I>(0xdeadfacecafebeefull));
+}
+
+int main() {
+    testType<char>();
+
+    testType<signed char>();
+    testType<signed short>();
+    testType<signed int>();
+    testType<signed long>();
+    testType<signed long long>();
+
+    testType<unsigned char>();
+    testType<unsigned short>();
+    testType<unsigned int>();
+    testType<unsigned long>();
+    testType<unsigned long long>();
+
+    StringBuilder() << static_cast<const void*>("TEST");
+    WStringBuilder() << static_cast<const void*>("TEST");
+
+    fprintf(stderr, "All tests completed!\n");
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/StringUtil.cc b/node_modules/node-pty/deps/winpty/src/shared/StringUtil.cc
new file mode 100644 (file)
index 0000000..3a85a3e
--- /dev/null
@@ -0,0 +1,55 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "StringUtil.h"
+
+#include <windows.h>
+
+#include "WinptyAssert.h"
+
+// Workaround.  MinGW (from mingw.org) does not have wcsnlen.  MinGW-w64 *does*
+// have wcsnlen, but use this function for consistency.
+size_t winpty_wcsnlen(const wchar_t *s, size_t maxlen) {
+    ASSERT(s != NULL);
+    for (size_t i = 0; i < maxlen; ++i) {
+        if (s[i] == L'\0') {
+            return i;
+        }
+    }
+    return maxlen;
+}
+
+std::string utf8FromWide(const std::wstring &input) {
+    int mblen = WideCharToMultiByte(
+        CP_UTF8, 0,
+        input.data(), input.size(),
+        NULL, 0, NULL, NULL);
+    if (mblen <= 0) {
+        return std::string();
+    }
+    std::vector<char> tmp(mblen);
+    int mblen2 = WideCharToMultiByte(
+        CP_UTF8, 0,
+        input.data(), input.size(),
+        tmp.data(), tmp.size(),
+        NULL, NULL);
+    ASSERT(mblen2 == mblen);
+    return std::string(tmp.data(), tmp.size());
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/StringUtil.h b/node_modules/node-pty/deps/winpty/src/shared/StringUtil.h
new file mode 100644 (file)
index 0000000..e4bf3c9
--- /dev/null
@@ -0,0 +1,80 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_STRING_UTIL_H
+#define WINPTY_SHARED_STRING_UTIL_H
+
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+
+#include <algorithm>
+#include <string>
+#include <vector>
+
+#include "WinptyAssert.h"
+
+size_t winpty_wcsnlen(const wchar_t *s, size_t maxlen);
+std::string utf8FromWide(const std::wstring &input);
+
+// Return a vector containing each character in the string.
+template <typename T>
+std::vector<T> vectorFromString(const std::basic_string<T> &str) {
+    return std::vector<T>(str.begin(), str.end());
+}
+
+// Return a vector containing each character in the string, followed by a
+// NUL terminator.
+template <typename T>
+std::vector<T> vectorWithNulFromString(const std::basic_string<T> &str) {
+    std::vector<T> ret;
+    ret.reserve(str.size() + 1);
+    ret.insert(ret.begin(), str.begin(), str.end());
+    ret.push_back('\0');
+    return ret;
+}
+
+// A safer(?) version of wcsncpy that is accepted by MSVC's /SDL mode.
+template <size_t N>
+wchar_t *winpty_wcsncpy(wchar_t (&d)[N], const wchar_t *s) {
+    ASSERT(s != nullptr);
+    size_t i = 0;
+    for (; i < N; ++i) {
+        if (s[i] == L'\0') {
+            break;
+        }
+        d[i] = s[i];
+    }
+    for (; i < N; ++i) {
+        d[i] = L'\0';
+    }
+    return d;
+}
+
+// Like wcsncpy, but ensure that the destination buffer is NUL-terminated.
+template <size_t N>
+wchar_t *winpty_wcsncpy_nul(wchar_t (&d)[N], const wchar_t *s) {
+    static_assert(N > 0, "array cannot be 0-size");
+    winpty_wcsncpy(d, s);
+    d[N - 1] = L'\0';
+    return d;
+}
+
+#endif // WINPTY_SHARED_STRING_UTIL_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/TimeMeasurement.h b/node_modules/node-pty/deps/winpty/src/shared/TimeMeasurement.h
new file mode 100644 (file)
index 0000000..716a027
--- /dev/null
@@ -0,0 +1,63 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+// Convenience header library for using the high-resolution performance counter
+// to measure how long some process takes.
+
+#ifndef TIME_MEASUREMENT_H
+#define TIME_MEASUREMENT_H
+
+#include <windows.h>
+#include <assert.h>
+#include <stdint.h>
+
+class TimeMeasurement {
+public:
+    TimeMeasurement() {
+        static double freq = static_cast<double>(getFrequency());
+        m_freq = freq;
+        m_start = value();
+    }
+
+    double elapsed() {
+        uint64_t elapsedTicks = value() - m_start;
+        return static_cast<double>(elapsedTicks) / m_freq;
+    }
+
+private:
+    uint64_t getFrequency() {
+        LARGE_INTEGER freq;
+        BOOL success = QueryPerformanceFrequency(&freq);
+        assert(success && "QueryPerformanceFrequency failed");
+        return freq.QuadPart;
+    }
+
+    uint64_t value() {
+        LARGE_INTEGER ret;
+        BOOL success = QueryPerformanceCounter(&ret);
+        assert(success && "QueryPerformanceCounter failed");
+        return ret.QuadPart;
+    }
+
+    uint64_t m_start;
+    double m_freq;
+};
+
+#endif // TIME_MEASUREMENT_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/UnixCtrlChars.h b/node_modules/node-pty/deps/winpty/src/shared/UnixCtrlChars.h
new file mode 100644 (file)
index 0000000..39dfa62
--- /dev/null
@@ -0,0 +1,45 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef UNIX_CTRL_CHARS_H
+#define UNIX_CTRL_CHARS_H
+
+inline char decodeUnixCtrlChar(char ch) {
+    const char ctrlKeys[] = {
+        /* 0x00 */ '@', /* 0x01 */ 'A', /* 0x02 */ 'B', /* 0x03 */ 'C',
+        /* 0x04 */ 'D', /* 0x05 */ 'E', /* 0x06 */ 'F', /* 0x07 */ 'G',
+        /* 0x08 */ 'H', /* 0x09 */ 'I', /* 0x0A */ 'J', /* 0x0B */ 'K',
+        /* 0x0C */ 'L', /* 0x0D */ 'M', /* 0x0E */ 'N', /* 0x0F */ 'O',
+        /* 0x10 */ 'P', /* 0x11 */ 'Q', /* 0x12 */ 'R', /* 0x13 */ 'S',
+        /* 0x14 */ 'T', /* 0x15 */ 'U', /* 0x16 */ 'V', /* 0x17 */ 'W',
+        /* 0x18 */ 'X', /* 0x19 */ 'Y', /* 0x1A */ 'Z', /* 0x1B */ '[',
+        /* 0x1C */ '\\', /* 0x1D */ ']', /* 0x1E */ '^', /* 0x1F */ '_',
+    };
+    unsigned char uch = ch;
+    if (uch < 32) {
+        return ctrlKeys[uch];
+    } else if (uch == 127) {
+        return '?';
+    } else {
+        return '\0';
+    }
+}
+
+#endif // UNIX_CTRL_CHARS_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/UpdateGenVersion.bat b/node_modules/node-pty/deps/winpty/src/shared/UpdateGenVersion.bat
new file mode 100644 (file)
index 0000000..ea2a7d6
--- /dev/null
@@ -0,0 +1,20 @@
+@echo off
+
+rem -- Echo the git commit hash.  If git isn't available for some reason,
+rem -- output nothing instead.
+
+mkdir ..\gen 2>nul
+
+set /p VERSION=<..\..\VERSION.txt
+set COMMIT=%1
+
+echo // AUTO-GENERATED BY %0 %*>..\gen\GenVersion.h
+echo const char GenVersion_Version[] = "%VERSION%";>>..\gen\GenVersion.h
+echo const char GenVersion_Commit[] = "%COMMIT%";>>..\gen\GenVersion.h
+
+rem -- The winpty.gyp file expects the script to output the include directory,
+rem -- relative to src.
+echo gen
+
+rem -- Set ERRORLEVEL to 0 using this cryptic syntax.
+(call )
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.cc b/node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.cc
new file mode 100644 (file)
index 0000000..711a863
--- /dev/null
@@ -0,0 +1,460 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "WindowsSecurity.h"
+
+#include <array>
+
+#include "DebugClient.h"
+#include "OsModule.h"
+#include "OwnedHandle.h"
+#include "StringBuilder.h"
+#include "WindowsVersion.h"
+#include "WinptyAssert.h"
+#include "WinptyException.h"
+
+namespace {
+
+struct LocalFreer {
+    void operator()(void *ptr) {
+        if (ptr != nullptr) {
+            LocalFree(reinterpret_cast<HLOCAL>(ptr));
+        }
+    }
+};
+
+typedef std::unique_ptr<void, LocalFreer> PointerLocal;
+
+template <typename T>
+SecurityItem<T> localItem(typename T::type v) {
+    typedef typename T::type P;
+    struct Impl : SecurityItem<T>::Impl {
+        P m_v;
+        Impl(P v) : m_v(v) {}
+        virtual ~Impl() {
+            LocalFree(reinterpret_cast<HLOCAL>(m_v));
+        }
+    };
+    return SecurityItem<T>(v, std::unique_ptr<Impl>(new Impl { v }));
+}
+
+Sid allocatedSid(PSID v) {
+    struct Impl : Sid::Impl {
+        PSID m_v;
+        Impl(PSID v) : m_v(v) {}
+        virtual ~Impl() {
+            if (m_v != nullptr) {
+                FreeSid(m_v);
+            }
+        }
+    };
+    return Sid(v, std::unique_ptr<Impl>(new Impl { v }));
+}
+
+} // anonymous namespace
+
+// Returns a handle to the thread's effective security token.  If the thread
+// is impersonating another user, its token is returned, and otherwise, the
+// process' security token is opened.  The handle is opened with TOKEN_QUERY.
+static OwnedHandle openSecurityTokenForQuery() {
+    HANDLE token = nullptr;
+    // It is unclear to me whether OpenAsSelf matters for winpty, or what the
+    // most appropriate value is.
+    if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY,
+                         /*OpenAsSelf=*/FALSE, &token)) {
+        if (GetLastError() != ERROR_NO_TOKEN) {
+            throwWindowsError(L"OpenThreadToken failed");
+        }
+        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
+            throwWindowsError(L"OpenProcessToken failed");
+        }
+    }
+    ASSERT(token != nullptr &&
+        "OpenThreadToken/OpenProcessToken token is NULL");
+    return OwnedHandle(token);
+}
+
+// Returns the TokenOwner of the thread's effective security token.
+Sid getOwnerSid() {
+    struct Impl : Sid::Impl {
+        std::unique_ptr<char[]> buffer;
+    };
+
+    OwnedHandle token = openSecurityTokenForQuery();
+    DWORD actual = 0;
+    BOOL success;
+    success = GetTokenInformation(token.get(), TokenOwner,
+        nullptr, 0, &actual);
+    if (success) {
+        throwWinptyException(L"getOwnerSid: GetTokenInformation: "
+            L"expected ERROR_INSUFFICIENT_BUFFER");
+    } else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
+        throwWindowsError(L"getOwnerSid: GetTokenInformation: "
+            L"expected ERROR_INSUFFICIENT_BUFFER");
+    }
+    std::unique_ptr<Impl> impl(new Impl);
+    impl->buffer = std::unique_ptr<char[]>(new char[actual]);
+    success = GetTokenInformation(token.get(), TokenOwner,
+                                  impl->buffer.get(), actual, &actual);
+    if (!success) {
+        throwWindowsError(L"getOwnerSid: GetTokenInformation");
+    }
+    TOKEN_OWNER tmp;
+    ASSERT(actual >= sizeof(tmp));
+    std::copy(
+        impl->buffer.get(),
+        impl->buffer.get() + sizeof(tmp),
+        reinterpret_cast<char*>(&tmp));
+    return Sid(tmp.Owner, std::move(impl));
+}
+
+Sid wellKnownSid(
+        const wchar_t *debuggingName,
+        SID_IDENTIFIER_AUTHORITY authority,
+        BYTE authorityCount,
+        DWORD subAuthority0/*=0*/,
+        DWORD subAuthority1/*=0*/) {
+    PSID psid = nullptr;
+    if (!AllocateAndInitializeSid(&authority, authorityCount,
+            subAuthority0,
+            subAuthority1,
+            0, 0, 0, 0, 0, 0,
+            &psid)) {
+        const auto err = GetLastError();
+        const auto msg =
+            std::wstring(L"wellKnownSid: error getting ") +
+            debuggingName + L" SID";
+        throwWindowsError(msg.c_str(), err);
+    }
+    return allocatedSid(psid);
+}
+
+Sid builtinAdminsSid() {
+    // S-1-5-32-544
+    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };
+    return wellKnownSid(L"BUILTIN\\Administrators group",
+            authority, 2,
+            SECURITY_BUILTIN_DOMAIN_RID,    // 32
+            DOMAIN_ALIAS_RID_ADMINS);       // 544
+}
+
+Sid localSystemSid() {
+    // S-1-5-18
+    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };
+    return wellKnownSid(L"LocalSystem account",
+            authority, 1,
+            SECURITY_LOCAL_SYSTEM_RID);     // 18
+}
+
+Sid everyoneSid() {
+    // S-1-1-0
+    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_WORLD_SID_AUTHORITY };
+    return wellKnownSid(L"Everyone account",
+            authority, 1,
+            SECURITY_WORLD_RID);            // 0
+}
+
+static SecurityDescriptor finishSecurityDescriptor(
+        size_t daclEntryCount,
+        EXPLICIT_ACCESSW *daclEntries,
+        Acl &outAcl) {
+    {
+        PACL aclRaw = nullptr;
+        DWORD aclError =
+            SetEntriesInAclW(daclEntryCount,
+                             daclEntries,
+                             nullptr, &aclRaw);
+        if (aclError != ERROR_SUCCESS) {
+            WStringBuilder sb(64);
+            sb << L"finishSecurityDescriptor: "
+               << L"SetEntriesInAcl failed: " << aclError;
+            throwWinptyException(sb.c_str());
+        }
+        outAcl = localItem<AclTag>(aclRaw);
+    }
+
+    const PSECURITY_DESCRIPTOR sdRaw =
+        reinterpret_cast<PSECURITY_DESCRIPTOR>(
+            LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH));
+    if (sdRaw == nullptr) {
+        throwWinptyException(L"finishSecurityDescriptor: LocalAlloc failed");
+    }
+    SecurityDescriptor sd = localItem<SecurityDescriptorTag>(sdRaw);
+    if (!InitializeSecurityDescriptor(sdRaw, SECURITY_DESCRIPTOR_REVISION)) {
+        throwWindowsError(
+            L"finishSecurityDescriptor: InitializeSecurityDescriptor");
+    }
+    if (!SetSecurityDescriptorDacl(sdRaw, TRUE, outAcl.get(), FALSE)) {
+        throwWindowsError(
+            L"finishSecurityDescriptor: SetSecurityDescriptorDacl");
+    }
+
+    return std::move(sd);
+}
+
+// Create a security descriptor that grants full control to the local system
+// account, built-in administrators, and the owner.
+SecurityDescriptor
+createPipeSecurityDescriptorOwnerFullControl() {
+
+    struct Impl : SecurityDescriptor::Impl {
+        Sid localSystem;
+        Sid builtinAdmins;
+        Sid owner;
+        std::array<EXPLICIT_ACCESSW, 3> daclEntries = {};
+        Acl dacl;
+        SecurityDescriptor value;
+    };
+
+    std::unique_ptr<Impl> impl(new Impl);
+    impl->localSystem = localSystemSid();
+    impl->builtinAdmins = builtinAdminsSid();
+    impl->owner = getOwnerSid();
+
+    for (auto &ea : impl->daclEntries) {
+        ea.grfAccessPermissions = GENERIC_ALL;
+        ea.grfAccessMode = SET_ACCESS;
+        ea.grfInheritance = NO_INHERITANCE;
+        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
+    }
+    impl->daclEntries[0].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->localSystem.get());
+    impl->daclEntries[1].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->builtinAdmins.get());
+    impl->daclEntries[2].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->owner.get());
+
+    impl->value = finishSecurityDescriptor(
+        impl->daclEntries.size(),
+        impl->daclEntries.data(),
+        impl->dacl);
+
+    const auto retValue = impl->value.get();
+    return SecurityDescriptor(retValue, std::move(impl));
+}
+
+SecurityDescriptor
+createPipeSecurityDescriptorOwnerFullControlEveryoneWrite() {
+
+    struct Impl : SecurityDescriptor::Impl {
+        Sid localSystem;
+        Sid builtinAdmins;
+        Sid owner;
+        Sid everyone;
+        std::array<EXPLICIT_ACCESSW, 4> daclEntries = {};
+        Acl dacl;
+        SecurityDescriptor value;
+    };
+
+    std::unique_ptr<Impl> impl(new Impl);
+    impl->localSystem = localSystemSid();
+    impl->builtinAdmins = builtinAdminsSid();
+    impl->owner = getOwnerSid();
+    impl->everyone = everyoneSid();
+
+    for (auto &ea : impl->daclEntries) {
+        ea.grfAccessPermissions = GENERIC_ALL;
+        ea.grfAccessMode = SET_ACCESS;
+        ea.grfInheritance = NO_INHERITANCE;
+        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
+    }
+    impl->daclEntries[0].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->localSystem.get());
+    impl->daclEntries[1].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->builtinAdmins.get());
+    impl->daclEntries[2].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->owner.get());
+    impl->daclEntries[3].Trustee.ptstrName =
+        reinterpret_cast<LPWSTR>(impl->everyone.get());
+    // Avoid using FILE_GENERIC_WRITE because it includes FILE_APPEND_DATA,
+    // which is equal to FILE_CREATE_PIPE_INSTANCE.  Instead, include all the
+    // flags that comprise FILE_GENERIC_WRITE, except for the one.
+    impl->daclEntries[3].grfAccessPermissions =
+        FILE_GENERIC_READ |
+        FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | FILE_WRITE_EA |
+        STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
+
+    impl->value = finishSecurityDescriptor(
+        impl->daclEntries.size(),
+        impl->daclEntries.data(),
+        impl->dacl);
+
+    const auto retValue = impl->value.get();
+    return SecurityDescriptor(retValue, std::move(impl));
+}
+
+SecurityDescriptor getObjectSecurityDescriptor(HANDLE handle) {
+    PACL dacl = nullptr;
+    PSECURITY_DESCRIPTOR sd = nullptr;
+    const DWORD errCode = GetSecurityInfo(handle, SE_KERNEL_OBJECT,
+        OWNER_SECURITY_INFORMATION |
+            GROUP_SECURITY_INFORMATION |
+            DACL_SECURITY_INFORMATION,
+        nullptr, nullptr, &dacl, nullptr, &sd);
+    if (errCode != ERROR_SUCCESS) {
+        throwWindowsError(L"GetSecurityInfo failed");
+    }
+    return localItem<SecurityDescriptorTag>(sd);
+}
+
+// The (SID/SD)<->string conversion APIs are useful for testing/debugging, so
+// create convenient accessor functions for them.  They're too slow for
+// ordinary use.  The APIs exist in XP and up, but the MinGW headers only
+// declare the SID<->string APIs, not the SD APIs.  MinGW also gets the
+// prototype wrong for ConvertStringSidToSidW (LPWSTR instead of LPCWSTR) and
+// requires WINVER to be defined.  MSVC and MinGW-w64 get everything right, but
+// for consistency, use LoadLibrary/GetProcAddress for all four APIs.
+
+typedef BOOL WINAPI ConvertStringSidToSidW_t(
+    LPCWSTR StringSid,
+    PSID *Sid);
+
+typedef BOOL WINAPI ConvertSidToStringSidW_t(
+    PSID Sid,
+    LPWSTR *StringSid);
+
+typedef BOOL WINAPI ConvertStringSecurityDescriptorToSecurityDescriptorW_t(
+    LPCWSTR StringSecurityDescriptor,
+    DWORD StringSDRevision,
+    PSECURITY_DESCRIPTOR *SecurityDescriptor,
+    PULONG SecurityDescriptorSize);
+
+typedef BOOL WINAPI ConvertSecurityDescriptorToStringSecurityDescriptorW_t(
+    PSECURITY_DESCRIPTOR SecurityDescriptor,
+    DWORD RequestedStringSDRevision,
+    SECURITY_INFORMATION SecurityInformation,
+    LPWSTR *StringSecurityDescriptor,
+    PULONG StringSecurityDescriptorLen);
+
+#define GET_MODULE_PROC(mod, funcName)                                      \
+    const auto p##funcName =                                                \
+        reinterpret_cast<funcName##_t*>(                                    \
+            mod.proc(#funcName));                                           \
+    if (p##funcName == nullptr) {                                           \
+        throwWinptyException(                                               \
+            L"" L ## #funcName L" API is missing from ADVAPI32.DLL");     \
+    }
+
+const DWORD kSDDL_REVISION_1 = 1;
+
+std::wstring sidToString(PSID sid) {
+    OsModule advapi32(L"advapi32.dll");
+    GET_MODULE_PROC(advapi32, ConvertSidToStringSidW);
+    wchar_t *sidString = NULL;
+    BOOL success = pConvertSidToStringSidW(sid, &sidString);
+    if (!success) {
+        throwWindowsError(L"ConvertSidToStringSidW failed");
+    }
+    PointerLocal freer(sidString);
+    return std::wstring(sidString);
+}
+
+Sid stringToSid(const std::wstring &str) {
+    // Cast the string from const wchar_t* to LPWSTR because the function is
+    // incorrectly prototyped in the MinGW sddl.h header.  The API does not
+    // modify the string -- it is correctly prototyped as taking LPCWSTR in
+    // MinGW-w64, MSVC, and MSDN.
+    OsModule advapi32(L"advapi32.dll");
+    GET_MODULE_PROC(advapi32, ConvertStringSidToSidW);
+    PSID psid = nullptr;
+    BOOL success = pConvertStringSidToSidW(const_cast<LPWSTR>(str.c_str()),
+                                           &psid);
+    if (!success) {
+        const auto err = GetLastError();
+        throwWindowsError(
+            (std::wstring(L"ConvertStringSidToSidW failed on \"") +
+                str + L'"').c_str(),
+            err);
+    }
+    return localItem<SidTag>(psid);
+}
+
+SecurityDescriptor stringToSd(const std::wstring &str) {
+    OsModule advapi32(L"advapi32.dll");
+    GET_MODULE_PROC(advapi32, ConvertStringSecurityDescriptorToSecurityDescriptorW);
+    PSECURITY_DESCRIPTOR desc = nullptr;
+    if (!pConvertStringSecurityDescriptorToSecurityDescriptorW(
+            str.c_str(), kSDDL_REVISION_1, &desc, nullptr)) {
+        const auto err = GetLastError();
+        throwWindowsError(
+            (std::wstring(L"ConvertStringSecurityDescriptorToSecurityDescriptorW failed on \"") +
+                str + L'"').c_str(),
+            err);
+    }
+    return localItem<SecurityDescriptorTag>(desc);
+}
+
+std::wstring sdToString(PSECURITY_DESCRIPTOR sd) {
+    OsModule advapi32(L"advapi32.dll");
+    GET_MODULE_PROC(advapi32, ConvertSecurityDescriptorToStringSecurityDescriptorW);
+    wchar_t *sdString = nullptr;
+    if (!pConvertSecurityDescriptorToStringSecurityDescriptorW(
+            sd,
+            kSDDL_REVISION_1,
+            OWNER_SECURITY_INFORMATION |
+                GROUP_SECURITY_INFORMATION |
+                DACL_SECURITY_INFORMATION,
+            &sdString,
+            nullptr)) {
+        throwWindowsError(
+            L"ConvertSecurityDescriptorToStringSecurityDescriptor failed");
+    }
+    PointerLocal freer(sdString);
+    return std::wstring(sdString);
+}
+
+// Vista added a useful flag to CreateNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
+// that rejects remote connections.  Return this flag on Vista, or return 0
+// otherwise.
+DWORD rejectRemoteClientsPipeFlag() {
+    if (isAtLeastWindowsVista()) {
+        // MinGW lacks this flag; MinGW-w64 has it.
+        const DWORD kPIPE_REJECT_REMOTE_CLIENTS = 8;
+        return kPIPE_REJECT_REMOTE_CLIENTS;
+    } else {
+        trace("Omitting PIPE_REJECT_REMOTE_CLIENTS on pre-Vista OS");
+        return 0;
+    }
+}
+
+typedef BOOL WINAPI GetNamedPipeClientProcessId_t(
+    HANDLE Pipe,
+    PULONG ClientProcessId);
+
+std::tuple<GetNamedPipeClientProcessId_Result, DWORD, DWORD>
+getNamedPipeClientProcessId(HANDLE serverPipe) {
+    OsModule kernel32(L"kernel32.dll");
+    const auto pGetNamedPipeClientProcessId =
+        reinterpret_cast<GetNamedPipeClientProcessId_t*>(
+            kernel32.proc("GetNamedPipeClientProcessId"));
+    if (pGetNamedPipeClientProcessId == nullptr) {
+        return std::make_tuple(
+            GetNamedPipeClientProcessId_Result::UnsupportedOs, 0, 0);
+    }
+    ULONG pid = 0;
+    if (!pGetNamedPipeClientProcessId(serverPipe, &pid)) {
+        return std::make_tuple(
+            GetNamedPipeClientProcessId_Result::Failure, 0, GetLastError());
+    }
+    return std::make_tuple(
+        GetNamedPipeClientProcessId_Result::Success,
+        static_cast<DWORD>(pid),
+        0);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.h b/node_modules/node-pty/deps/winpty/src/shared/WindowsSecurity.h
new file mode 100644 (file)
index 0000000..5f9d53a
--- /dev/null
@@ -0,0 +1,104 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_WINDOWS_SECURITY_H
+#define WINPTY_WINDOWS_SECURITY_H
+
+#include <windows.h>
+#include <aclapi.h>
+
+#include <memory>
+#include <string>
+#include <tuple>
+#include <utility>
+
+// PSID and PSECURITY_DESCRIPTOR are both pointers to void, but we want
+// Sid and SecurityDescriptor to be different types.
+struct SidTag                   {   typedef PSID type;                  };
+struct AclTag                   {   typedef PACL type;                  };
+struct SecurityDescriptorTag    {   typedef PSECURITY_DESCRIPTOR type;  };
+
+template <typename T>
+class SecurityItem {
+public:
+    struct Impl {
+        virtual ~Impl() {}
+    };
+
+private:
+    typedef typename T::type P;
+    P m_v;
+    std::unique_ptr<Impl> m_pimpl;
+
+public:
+    P get() const { return m_v; }
+    operator bool() const { return m_v != nullptr; }
+
+    SecurityItem() : m_v(nullptr) {}
+    SecurityItem(P v, std::unique_ptr<Impl> &&pimpl) :
+            m_v(v), m_pimpl(std::move(pimpl)) {}
+    SecurityItem(SecurityItem &&other) :
+            m_v(other.m_v), m_pimpl(std::move(other.m_pimpl)) {
+        other.m_v = nullptr;
+    }
+    SecurityItem &operator=(SecurityItem &&other) {
+        m_v = other.m_v;
+        other.m_v = nullptr;
+        m_pimpl = std::move(other.m_pimpl);
+        return *this;
+    }
+};
+
+typedef SecurityItem<SidTag> Sid;
+typedef SecurityItem<AclTag> Acl;
+typedef SecurityItem<SecurityDescriptorTag> SecurityDescriptor;
+
+Sid getOwnerSid();
+Sid wellKnownSid(
+    const wchar_t *debuggingName,
+    SID_IDENTIFIER_AUTHORITY authority,
+    BYTE authorityCount,
+    DWORD subAuthority0=0,
+    DWORD subAuthority1=0);
+Sid builtinAdminsSid();
+Sid localSystemSid();
+Sid everyoneSid();
+
+SecurityDescriptor createPipeSecurityDescriptorOwnerFullControl();
+SecurityDescriptor createPipeSecurityDescriptorOwnerFullControlEveryoneWrite();
+SecurityDescriptor getObjectSecurityDescriptor(HANDLE handle);
+
+std::wstring sidToString(PSID sid);
+Sid stringToSid(const std::wstring &str);
+SecurityDescriptor stringToSd(const std::wstring &str);
+std::wstring sdToString(PSECURITY_DESCRIPTOR sd);
+
+DWORD rejectRemoteClientsPipeFlag();
+
+enum class GetNamedPipeClientProcessId_Result {
+    Success,
+    Failure,
+    UnsupportedOs,
+};
+
+std::tuple<GetNamedPipeClientProcessId_Result, DWORD, DWORD>
+getNamedPipeClientProcessId(HANDLE serverPipe);
+
+#endif // WINPTY_WINDOWS_SECURITY_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.cc b/node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.cc
new file mode 100644 (file)
index 0000000..d89b00d
--- /dev/null
@@ -0,0 +1,252 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "WindowsVersion.h"
+
+#include <windows.h>
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <tuple>
+
+#include "DebugClient.h"
+#include "OsModule.h"
+#include "StringBuilder.h"
+#include "StringUtil.h"
+#include "WinptyAssert.h"
+#include "WinptyException.h"
+
+namespace {
+
+typedef std::tuple<DWORD, DWORD> Version;
+
+// This function can only return a version up to 6.2 unless the executable is
+// manifested for a newer version of Windows.  See the MSDN documentation for
+// GetVersionEx.
+OSVERSIONINFOEX getWindowsVersionInfo() {
+    // Allow use of deprecated functions (i.e. GetVersionEx).  We need to use
+    // GetVersionEx for the old MinGW toolchain and with MSVC when it targets XP.
+    // Having two code paths makes code harder to test, and it's not obvious how
+    // to detect the presence of a new enough SDK.  (Including ntverp.h and
+    // examining VER_PRODUCTBUILD apparently works, but even then, MinGW-w64 and
+    // MSVC seem to use different version numbers.)
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4996)
+#endif
+    OSVERSIONINFOEX info = {};
+    info.dwOSVersionInfoSize = sizeof(info);
+    const auto success = GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&info));
+    ASSERT(success && "GetVersionEx failed");
+    return info;
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+}
+
+Version getWindowsVersion() {
+    const auto info = getWindowsVersionInfo();
+    return Version(info.dwMajorVersion, info.dwMinorVersion);
+}
+
+struct ModuleNotFound : WinptyException {
+    virtual const wchar_t *what() const WINPTY_NOEXCEPT override {
+        return L"ModuleNotFound";
+    }
+};
+
+// Throws WinptyException on error.
+std::wstring getSystemDirectory() {
+    wchar_t systemDirectory[MAX_PATH];
+    const UINT size = GetSystemDirectoryW(systemDirectory, MAX_PATH);
+    if (size == 0) {
+        throwWindowsError(L"GetSystemDirectory failed");
+    } else if (size >= MAX_PATH) {
+        throwWinptyException(
+            L"GetSystemDirectory: path is longer than MAX_PATH");
+    }
+    return systemDirectory;
+}
+
+#define GET_VERSION_DLL_API(name) \
+    const auto p ## name =                                  \
+        reinterpret_cast<decltype(name)*>(                  \
+            versionDll.proc(#name));                        \
+    if (p ## name == nullptr) {                             \
+        throwWinptyException(L ## #name L" is missing");    \
+    }
+
+// Throws WinptyException on error.
+VS_FIXEDFILEINFO getFixedFileInfo(const std::wstring &path) {
+    // version.dll is not a conventional KnownDll, so if we link to it, there's
+    // a danger of accidentally loading a malicious DLL.  In a more typical
+    // application, perhaps we'd guard against this security issue by
+    // controlling which directories this code runs in (e.g. *not* the
+    // "Downloads" directory), but that's harder for the winpty library.
+    OsModule versionDll(
+        (getSystemDirectory() + L"\\version.dll").c_str(),
+        OsModule::LoadErrorBehavior::Throw);
+    GET_VERSION_DLL_API(GetFileVersionInfoSizeW);
+    GET_VERSION_DLL_API(GetFileVersionInfoW);
+    GET_VERSION_DLL_API(VerQueryValueW);
+    DWORD size = pGetFileVersionInfoSizeW(path.c_str(), nullptr);
+    if (!size) {
+        // I see ERROR_FILE_NOT_FOUND on Win7 and
+        // ERROR_RESOURCE_DATA_NOT_FOUND on WinXP.
+        if (GetLastError() == ERROR_FILE_NOT_FOUND ||
+                GetLastError() == ERROR_RESOURCE_DATA_NOT_FOUND) {
+            throw ModuleNotFound();
+        } else {
+            throwWindowsError(
+                (L"GetFileVersionInfoSizeW failed on " + path).c_str());
+        }
+    }
+    std::unique_ptr<char[]> versionBuffer(new char[size]);
+    if (!pGetFileVersionInfoW(path.c_str(), 0, size, versionBuffer.get())) {
+        throwWindowsError((L"GetFileVersionInfoW failed on " + path).c_str());
+    }
+    VS_FIXEDFILEINFO *versionInfo = nullptr;
+    UINT versionInfoSize = 0;
+    if (!pVerQueryValueW(
+                versionBuffer.get(), L"\\",
+                reinterpret_cast<void**>(&versionInfo), &versionInfoSize) ||
+            versionInfo == nullptr ||
+            versionInfoSize != sizeof(VS_FIXEDFILEINFO) ||
+            versionInfo->dwSignature != 0xFEEF04BD) {
+        throwWinptyException((L"VerQueryValueW failed on " + path).c_str());
+    }
+    return *versionInfo;
+}
+
+uint64_t productVersionFromInfo(const VS_FIXEDFILEINFO &info) {
+    return (static_cast<uint64_t>(info.dwProductVersionMS) << 32) |
+           (static_cast<uint64_t>(info.dwProductVersionLS));
+}
+
+uint64_t fileVersionFromInfo(const VS_FIXEDFILEINFO &info) {
+    return (static_cast<uint64_t>(info.dwFileVersionMS) << 32) |
+           (static_cast<uint64_t>(info.dwFileVersionLS));
+}
+
+std::string versionToString(uint64_t version) {
+    StringBuilder b(32);
+    b << ((uint16_t)(version >> 48));
+    b << '.';
+    b << ((uint16_t)(version >> 32));
+    b << '.';
+    b << ((uint16_t)(version >> 16));
+    b << '.';
+    b << ((uint16_t)(version >> 0));
+    return b.str_moved();
+}
+
+} // anonymous namespace
+
+// Returns true for Windows Vista (or Windows Server 2008) or newer.
+bool isAtLeastWindowsVista() {
+    return getWindowsVersion() >= Version(6, 0);
+}
+
+// Returns true for Windows 7 (or Windows Server 2008 R2) or newer.
+bool isAtLeastWindows7() {
+    return getWindowsVersion() >= Version(6, 1);
+}
+
+// Returns true for Windows 8 (or Windows Server 2012) or newer.
+bool isAtLeastWindows8() {
+    return getWindowsVersion() >= Version(6, 2);
+}
+
+#define WINPTY_IA32     1
+#define WINPTY_X64      2
+
+#if defined(_M_IX86) || defined(__i386__)
+#define WINPTY_ARCH WINPTY_IA32
+#elif defined(_M_X64) || defined(__x86_64__)
+#define WINPTY_ARCH WINPTY_X64
+#endif
+
+typedef BOOL WINAPI IsWow64Process_t(HANDLE hProcess, PBOOL Wow64Process);
+
+void dumpWindowsVersion() {
+    if (!isTracingEnabled()) {
+        return;
+    }
+    const auto info = getWindowsVersionInfo();
+    StringBuilder b;
+    b << info.dwMajorVersion << '.' << info.dwMinorVersion
+      << '.' << info.dwBuildNumber << ' '
+      << "SP" << info.wServicePackMajor << '.' << info.wServicePackMinor
+      << ' ';
+    switch (info.wProductType) {
+        case VER_NT_WORKSTATION:        b << "Client"; break;
+        case VER_NT_DOMAIN_CONTROLLER:  b << "DomainController"; break;
+        case VER_NT_SERVER:             b << "Server"; break;
+        default:
+            b << "product=" << info.wProductType; break;
+    }
+    b << ' ';
+#if WINPTY_ARCH == WINPTY_IA32
+    b << "IA32";
+    OsModule kernel32(L"kernel32.dll");
+    IsWow64Process_t *pIsWow64Process =
+        reinterpret_cast<IsWow64Process_t*>(
+            kernel32.proc("IsWow64Process"));
+    if (pIsWow64Process != nullptr) {
+        BOOL result = false;
+        const BOOL success = pIsWow64Process(GetCurrentProcess(), &result);
+        if (!success) {
+            b << " WOW64:error";
+        } else if (success && result) {
+            b << " WOW64";
+        }
+    } else {
+        b << " WOW64:missingapi";
+    }
+#elif WINPTY_ARCH == WINPTY_X64
+    b << "X64";
+#endif
+    const auto dllVersion = [](const wchar_t *dllPath) -> std::string {
+        try {
+            const auto info = getFixedFileInfo(dllPath);
+            StringBuilder fb(64);
+            fb << utf8FromWide(dllPath) << ':';
+            fb << "F:" << versionToString(fileVersionFromInfo(info)) << '/'
+               << "P:" << versionToString(productVersionFromInfo(info));
+            return fb.str_moved();
+        } catch (const ModuleNotFound&) {
+            return utf8FromWide(dllPath) + ":none";
+        } catch (const WinptyException &e) {
+            trace("Error getting %s version: %s",
+                utf8FromWide(dllPath).c_str(), utf8FromWide(e.what()).c_str());
+            return utf8FromWide(dllPath) + ":error";
+        }
+    };
+    b << ' ' << dllVersion(L"kernel32.dll");
+    // ConEmu provides a DLL that hooks many Windows APIs, especially console
+    // APIs.  Its existence and version number could be useful in debugging.
+#if WINPTY_ARCH == WINPTY_IA32
+    b << ' ' << dllVersion(L"ConEmuHk.dll");
+#elif WINPTY_ARCH == WINPTY_X64
+    b << ' ' << dllVersion(L"ConEmuHk64.dll");
+#endif
+    trace("Windows version: %s", b.c_str());
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.h b/node_modules/node-pty/deps/winpty/src/shared/WindowsVersion.h
new file mode 100644 (file)
index 0000000..a807984
--- /dev/null
@@ -0,0 +1,29 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SHARED_WINDOWS_VERSION_H
+#define WINPTY_SHARED_WINDOWS_VERSION_H
+
+bool isAtLeastWindowsVista();
+bool isAtLeastWindows7();
+bool isAtLeastWindows8();
+void dumpWindowsVersion();
+
+#endif // WINPTY_SHARED_WINDOWS_VERSION_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.cc b/node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.cc
new file mode 100644 (file)
index 0000000..1ff0de4
--- /dev/null
@@ -0,0 +1,55 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#include "WinptyAssert.h"
+
+#include <windows.h>
+#include <stdlib.h>
+
+#include "DebugClient.h"
+
+void assertTrace(const char *file, int line, const char *cond) {
+    trace("Assertion failed: %s, file %s, line %d",
+          cond, file, line);
+}
+
+#ifdef WINPTY_AGENT_ASSERT
+
+void agentShutdown() {
+    HWND hwnd = GetConsoleWindow();
+    if (hwnd != NULL) {
+        PostMessage(hwnd, WM_CLOSE, 0, 0);
+        Sleep(30000);
+        trace("Agent shutdown: WM_CLOSE did not end agent process");
+    } else {
+        trace("Agent shutdown: GetConsoleWindow() is NULL");
+    }
+    // abort() prints a message to the console, and if it is frozen, then the
+    // process would hang, so instead use exit().  (We shouldn't ever get here,
+    // though, because the WM_CLOSE message should have ended this process.)
+    exit(1);
+}
+
+void agentAssertFail(const char *file, int line, const char *cond) {
+    assertTrace(file, line, cond);
+    agentShutdown();
+}
+
+#endif
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.h b/node_modules/node-pty/deps/winpty/src/shared/WinptyAssert.h
new file mode 100644 (file)
index 0000000..b2b8b5e
--- /dev/null
@@ -0,0 +1,64 @@
+// Copyright (c) 2011-2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_ASSERT_H
+#define WINPTY_ASSERT_H
+
+#ifdef WINPTY_AGENT_ASSERT
+
+void agentShutdown();
+void agentAssertFail(const char *file, int line, const char *cond);
+
+// Calling the standard assert() function does not work in the agent because
+// the error message would be printed to the console, and the only way the
+// user can see the console is via a working agent!  Moreover, the console may
+// be frozen, so attempting to write to it would block forever.  This custom
+// assert function instead sends the message to the DebugServer, then attempts
+// to close the console, then quietly exits.
+#define ASSERT(cond) \
+    do {                                                    \
+        if (!(cond)) {                                      \
+            agentAssertFail(__FILE__, __LINE__, #cond);     \
+        }                                                   \
+    } while(0)
+
+#else
+
+void assertTrace(const char *file, int line, const char *cond);
+
+// In the other targets, log the assert failure to the debugserver, then fail
+// using the ordinary assert mechanism.  In case assert is compiled out, fail
+// using abort.  The amount of code inlined is unfortunate, but asserts aren't
+// used much outside the agent.
+#include <assert.h>
+#include <stdlib.h>
+#define ASSERT_CONDITION(cond) (false && (cond))
+#define ASSERT(cond) \
+    do {                                            \
+        if (!(cond)) {                              \
+            assertTrace(__FILE__, __LINE__, #cond); \
+            assert(ASSERT_CONDITION(#cond));        \
+            abort();                                \
+        }                                           \
+    } while(0)
+
+#endif
+
+#endif // WINPTY_ASSERT_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WinptyException.cc b/node_modules/node-pty/deps/winpty/src/shared/WinptyException.cc
new file mode 100644 (file)
index 0000000..d0d4882
--- /dev/null
@@ -0,0 +1,57 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#include "WinptyException.h"
+
+#include <memory>
+#include <string>
+
+#include "StringBuilder.h"
+
+namespace {
+
+class ExceptionImpl : public WinptyException {
+public:
+    ExceptionImpl(const wchar_t *what) :
+        m_what(std::make_shared<std::wstring>(what)) {}
+    virtual const wchar_t *what() const WINPTY_NOEXCEPT override {
+        return m_what->c_str();
+    }
+private:
+    // Using a shared_ptr ensures that copying the object raises no exception.
+    std::shared_ptr<std::wstring> m_what;
+};
+
+} // anonymous namespace
+
+void throwWinptyException(const wchar_t *what) {
+    throw ExceptionImpl(what);
+}
+
+void throwWindowsError(const wchar_t *prefix, DWORD errorCode) {
+    WStringBuilder sb(64);
+    if (prefix != nullptr) {
+        sb << prefix << L": ";
+    }
+    // It might make sense to use FormatMessage here, but IIRC, its API is hard
+    // to figure out.
+    sb << L"Windows error " << errorCode;
+    throwWinptyException(sb.c_str());
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WinptyException.h b/node_modules/node-pty/deps/winpty/src/shared/WinptyException.h
new file mode 100644 (file)
index 0000000..ec35336
--- /dev/null
@@ -0,0 +1,43 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_EXCEPTION_H
+#define WINPTY_EXCEPTION_H
+
+#include <windows.h>
+
+#if defined(__GNUC__)
+#define WINPTY_NOEXCEPT noexcept
+#elif defined(_MSC_VER) && _MSC_VER >= 1900
+#define WINPTY_NOEXCEPT noexcept
+#else
+#define WINPTY_NOEXCEPT
+#endif
+
+class WinptyException {
+public:
+    virtual const wchar_t *what() const WINPTY_NOEXCEPT = 0;
+    virtual ~WinptyException() {}
+};
+
+void throwWinptyException(const wchar_t *what);
+void throwWindowsError(const wchar_t *prefix, DWORD error=GetLastError());
+
+#endif // WINPTY_EXCEPTION_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.cc b/node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.cc
new file mode 100644 (file)
index 0000000..76bb8a5
--- /dev/null
@@ -0,0 +1,42 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "WinptyVersion.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include "DebugClient.h"
+
+// This header is auto-generated by either the Makefile (Unix) or
+// UpdateGenVersion.bat (gyp).  It is placed in a 'gen' directory, which is
+// added to the search path.
+#include "GenVersion.h"
+
+void dumpVersionToStdout() {
+    printf("winpty version %s\n", GenVersion_Version);
+    printf("commit %s\n", GenVersion_Commit);
+}
+
+void dumpVersionToTrace() {
+    trace("winpty version %s (commit %s)",
+        GenVersion_Version,
+        GenVersion_Commit);
+}
diff --git a/node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.h b/node_modules/node-pty/deps/winpty/src/shared/WinptyVersion.h
new file mode 100644 (file)
index 0000000..e6224d7
--- /dev/null
@@ -0,0 +1,27 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_VERSION_H
+#define WINPTY_VERSION_H
+
+void dumpVersionToStdout();
+void dumpVersionToTrace();
+
+#endif // WINPTY_VERSION_H
diff --git a/node_modules/node-pty/deps/winpty/src/shared/winpty_snprintf.h b/node_modules/node-pty/deps/winpty/src/shared/winpty_snprintf.h
new file mode 100644 (file)
index 0000000..e716f24
--- /dev/null
@@ -0,0 +1,99 @@
+// Copyright (c) 2016 Ryan Prichard
+//
+// 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.
+
+#ifndef WINPTY_SNPRINTF_H
+#define WINPTY_SNPRINTF_H
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "WinptyAssert.h"
+
+#if defined(__CYGWIN__) || defined(__MSYS__)
+#define WINPTY_SNPRINTF_FORMAT(fmtarg, vararg) \
+    __attribute__((format(printf, (fmtarg), ((vararg)))))
+#elif defined(__GNUC__)
+#define WINPTY_SNPRINTF_FORMAT(fmtarg, vararg) \
+    __attribute__((format(ms_printf, (fmtarg), ((vararg)))))
+#else
+#define WINPTY_SNPRINTF_FORMAT(fmtarg, vararg)
+#endif
+
+// Returns a value between 0 and size - 1 (inclusive) on success.  Returns -1
+// on failure (including truncation).  The output buffer is always
+// NUL-terminated.
+inline int
+winpty_vsnprintf(char *out, size_t size, const char *fmt, va_list ap) {
+    ASSERT(size > 0);
+    out[0] = '\0';
+#if defined(_MSC_VER) && _MSC_VER < 1900
+    // MSVC 2015 added a C99-conforming vsnprintf.
+    int count = _vsnprintf_s(out, size, _TRUNCATE, fmt, ap);
+#else
+    // MinGW configurations frequently provide a vsnprintf function that simply
+    // calls one of the MS _vsnprintf* functions, which are not C99 conformant.
+    int count = vsnprintf(out, size, fmt, ap);
+#endif
+    if (count < 0 || static_cast<size_t>(count) >= size) {
+        // On truncation, some *printf* implementations return the
+        // non-truncated size, but other implementations returns -1.  Return
+        // -1 for consistency.
+        count = -1;
+        // Guarantee NUL termination.
+        out[size - 1] = '\0';
+    } else {
+        // Guarantee NUL termination.
+        out[count] = '\0';
+    }
+    return count;
+}
+
+// Wraps winpty_vsnprintf.
+inline int winpty_snprintf(char *out, size_t size, const char *fmt, ...)
+    WINPTY_SNPRINTF_FORMAT(3, 4);
+inline int winpty_snprintf(char *out, size_t size, const char *fmt, ...) {
+    va_list ap;
+    va_start(ap, fmt);
+    const int count = winpty_vsnprintf(out, size, fmt, ap);
+    va_end(ap);
+    return count;
+}
+
+// Wraps winpty_vsnprintf with automatic size determination.
+template <size_t size>
+int winpty_vsnprintf(char (&out)[size], const char *fmt, va_list ap) {
+    return winpty_vsnprintf(out, size, fmt, ap);
+}
+
+// Wraps winpty_vsnprintf with automatic size determination.
+template <size_t size>
+int winpty_snprintf(char (&out)[size], const char *fmt, ...)
+    WINPTY_SNPRINTF_FORMAT(2, 3);
+template <size_t size>
+int winpty_snprintf(char (&out)[size], const char *fmt, ...) {
+    va_list ap;
+    va_start(ap, fmt);
+    const int count = winpty_vsnprintf(out, size, fmt, ap);
+    va_end(ap);
+    return count;
+}
+
+#endif // WINPTY_SNPRINTF_H
diff --git a/node_modules/node-pty/deps/winpty/src/subdir.mk b/node_modules/node-pty/deps/winpty/src/subdir.mk
new file mode 100644 (file)
index 0000000..9ae8031
--- /dev/null
@@ -0,0 +1,5 @@
+include src/agent/subdir.mk
+include src/debugserver/subdir.mk
+include src/libwinpty/subdir.mk
+include src/tests/subdir.mk
+include src/unix-adapter/subdir.mk
diff --git a/node_modules/node-pty/deps/winpty/src/tests/subdir.mk b/node_modules/node-pty/deps/winpty/src/tests/subdir.mk
new file mode 100644 (file)
index 0000000..18799c4
--- /dev/null
@@ -0,0 +1,28 @@
+# Copyright (c) 2015 Ryan Prichard
+#
+# 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.
+
+build/%.exe : src/tests/%.cc build/winpty.dll
+       $(info Building $@)
+       @$(MINGW_CXX) $(MINGW_CXXFLAGS) $(MINGW_LDFLAGS) -o $@ $^
+
+TEST_PROGRAMS = \
+        build/trivial_test.exe
+
+-include $(TEST_PROGRAMS:.exe=.d)
diff --git a/node_modules/node-pty/deps/winpty/src/tests/trivial_test.cc b/node_modules/node-pty/deps/winpty/src/tests/trivial_test.cc
new file mode 100644 (file)
index 0000000..2188a4b
--- /dev/null
@@ -0,0 +1,158 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include <windows.h>
+
+#include <cassert>
+#include <cctype>
+#include <cstdio>
+#include <cstdlib>
+#include <cwchar>
+#include <vector>
+
+#include "../include/winpty.h"
+#include "../shared/DebugClient.h"
+
+static std::vector<unsigned char> filterContent(
+        const std::vector<unsigned char> &content) {
+    std::vector<unsigned char> result;
+    auto it = content.begin();
+    const auto itEnd = content.end();
+    while (it < itEnd) {
+        if (*it == '\r') {
+            // Filter out carriage returns.  Sometimes the output starts with
+            // a single CR; other times, it has multiple CRs.
+            it++;
+        } else if (*it == '\x1b' && (it + 1) < itEnd && *(it + 1) == '[') {
+            // Filter out escape sequences.  They have no interior letters and
+            // end with a single letter.
+            it += 2;
+            while (it < itEnd && !isalpha(*it)) {
+                it++;
+            }
+            it++;
+        } else {
+            // Let everything else through.
+            result.push_back(*it);
+            it++;
+        }
+    }
+    return result;
+}
+
+// Read bytes from the non-overlapped file handle until the file is closed or
+// until an I/O error occurs.
+static std::vector<unsigned char> readAll(HANDLE handle) {
+    unsigned char buf[1024];
+    std::vector<unsigned char> result;
+    while (true) {
+        DWORD amount = 0;
+        BOOL ret = ReadFile(handle, buf, sizeof(buf), &amount, nullptr);
+        if (!ret || amount == 0) {
+            break;
+        }
+        result.insert(result.end(), buf, buf + amount);
+    }
+    return result;
+}
+
+static void parentTest() {
+    wchar_t program[1024];
+    wchar_t cmdline[1024];
+    GetModuleFileNameW(nullptr, program, 1024);
+
+    {
+        // XXX: We'd like to use swprintf, which is part of C99 and takes a
+        // size_t maxlen argument.  MinGW-w64 has this function, as does MSVC.
+        // The old MinGW doesn't, though -- instead, it apparently provides an
+        // swprintf taking no maxlen argument.  This *might* be a regression?
+        // (There is also no swnprintf, but that function is obsolescent with a
+        // correct swprintf, and it isn't in POSIX or ISO C.)
+        //
+        // Visual C++ 6 also provided this non-conformant swprintf, and I'm
+        // guessing MSVCRT.DLL does too.  (My impression is that the old MinGW
+        // prefers to rely on MSVCRT.DLL for convenience?)
+        //
+        // I could compile differently for old MinGW, but what if it fixes its
+        // function later?  Instead, use a workaround.  It's starting to make
+        // sense to drop MinGW support in favor of MinGW-w64.  This is too
+        // annoying.
+        //
+        // grepbait: OLD-MINGW / WINPTY_TARGET_MSYS1
+        cmdline[0] = L'\0';
+        wcscat(cmdline, L"\"");
+        wcscat(cmdline, program);
+        wcscat(cmdline, L"\" CHILD");
+    }
+    // swnprintf(cmdline, sizeof(cmdline) / sizeof(cmdline[0]),
+    //           L"\"%ls\" CHILD", program);
+
+    auto agentCfg = winpty_config_new(0, nullptr);
+    assert(agentCfg != nullptr);
+    auto pty = winpty_open(agentCfg, nullptr);
+    assert(pty != nullptr);
+    winpty_config_free(agentCfg);
+
+    HANDLE conin = CreateFileW(
+        winpty_conin_name(pty),
+        GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
+    HANDLE conout = CreateFileW(
+        winpty_conout_name(pty),
+        GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
+    assert(conin != INVALID_HANDLE_VALUE);
+    assert(conout != INVALID_HANDLE_VALUE);
+
+    auto spawnCfg = winpty_spawn_config_new(
+            WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN, program, cmdline,
+            nullptr, nullptr, nullptr);
+    assert(spawnCfg != nullptr);
+    HANDLE process = nullptr;
+    BOOL spawnSuccess = winpty_spawn(
+        pty, spawnCfg, &process, nullptr, nullptr, nullptr);
+    assert(spawnSuccess && process != nullptr);
+
+    auto content = readAll(conout);
+    content = filterContent(content);
+
+    std::vector<unsigned char> expectedContent = {
+        'H', 'I', '\n', 'X', 'Y', '\n'
+    };
+    DWORD exitCode = 0;
+    assert(GetExitCodeProcess(process, &exitCode) && exitCode == 42);
+    CloseHandle(process);
+    CloseHandle(conin);
+    CloseHandle(conout);
+    assert(content == expectedContent);
+    winpty_free(pty);
+}
+
+static void childTest() {
+    printf("HI\nXY\n");
+    exit(42);
+}
+
+int main(int argc, char *argv[]) {
+    if (argc == 1) {
+        parentTest();
+    } else {
+        childTest();
+    }
+    return 0;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.cc b/node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.cc
new file mode 100644 (file)
index 0000000..39f1e09
--- /dev/null
@@ -0,0 +1,114 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "InputHandler.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <sys/select.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <vector>
+
+#include "../shared/DebugClient.h"
+#include "Util.h"
+#include "WakeupFd.h"
+
+InputHandler::InputHandler(
+        HANDLE conin, int inputfd, WakeupFd &completionWakeup) :
+    m_conin(conin),
+    m_inputfd(inputfd),
+    m_completionWakeup(completionWakeup),
+    m_threadHasBeenJoined(false),
+    m_shouldShutdown(0),
+    m_threadCompleted(0)
+{
+    pthread_create(&m_thread, NULL, InputHandler::threadProcS, this);
+}
+
+void InputHandler::shutdown() {
+    startShutdown();
+    if (!m_threadHasBeenJoined) {
+        int ret = pthread_join(m_thread, NULL);
+        assert(ret == 0 && "pthread_join failed");
+        m_threadHasBeenJoined = true;
+    }
+}
+
+void InputHandler::threadProc() {
+    std::vector<char> buffer(4096);
+    fd_set readfds;
+    FD_ZERO(&readfds);
+    while (true) {
+        // Handle shutdown.
+        m_wakeup.reset();
+        if (m_shouldShutdown) {
+            trace("InputHandler: shutting down");
+            break;
+        }
+
+        // Block until data arrives.
+        {
+            const int max_fd = std::max(m_inputfd, m_wakeup.fd());
+            FD_SET(m_inputfd, &readfds);
+            FD_SET(m_wakeup.fd(), &readfds);
+            selectWrapper("InputHandler", max_fd + 1, &readfds);
+            if (!FD_ISSET(m_inputfd, &readfds)) {
+                continue;
+            }
+        }
+
+        const int numRead = read(m_inputfd, &buffer[0], buffer.size());
+        if (numRead == -1 && errno == EINTR) {
+            // Apparently, this read is interrupted on Cygwin 1.7 by a SIGWINCH
+            // signal even though I set the SA_RESTART flag on the handler.
+            continue;
+        }
+
+        // tty is closed, or the read failed for some unexpected reason.
+        if (numRead <= 0) {
+            trace("InputHandler: tty read failed: numRead=%d", numRead);
+            break;
+        }
+
+        DWORD written = 0;
+        BOOL ret = WriteFile(m_conin,
+                             &buffer[0], numRead,
+                             &written, NULL);
+        if (!ret || written != static_cast<DWORD>(numRead)) {
+            if (!ret && GetLastError() == ERROR_BROKEN_PIPE) {
+                trace("InputHandler: pipe closed: written=%u",
+                    static_cast<unsigned int>(written));
+            } else {
+                trace("InputHandler: write failed: "
+                    "ret=%d lastError=0x%x numRead=%d written=%u",
+                    ret,
+                    static_cast<unsigned int>(GetLastError()),
+                    numRead,
+                    static_cast<unsigned int>(written));
+            }
+            break;
+        }
+    }
+    m_threadCompleted = 1;
+    m_completionWakeup.set();
+}
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.h b/node_modules/node-pty/deps/winpty/src/unix-adapter/InputHandler.h
new file mode 100644 (file)
index 0000000..9c3f540
--- /dev/null
@@ -0,0 +1,56 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#ifndef UNIX_ADAPTER_INPUT_HANDLER_H
+#define UNIX_ADAPTER_INPUT_HANDLER_H
+
+#include <windows.h>
+#include <pthread.h>
+#include <signal.h>
+
+#include "WakeupFd.h"
+
+// Connect a Cygwin blocking fd to winpty CONIN.
+class InputHandler {
+public:
+    InputHandler(HANDLE conin, int inputfd, WakeupFd &completionWakeup);
+    ~InputHandler() { shutdown(); }
+    bool isComplete() { return m_threadCompleted; }
+    void startShutdown() { m_shouldShutdown = 1; m_wakeup.set(); }
+    void shutdown();
+
+private:
+    static void *threadProcS(void *pvthis) {
+        reinterpret_cast<InputHandler*>(pvthis)->threadProc();
+        return NULL;
+    }
+    void threadProc();
+
+    HANDLE m_conin;
+    int m_inputfd;
+    pthread_t m_thread;
+    WakeupFd &m_completionWakeup;
+    WakeupFd m_wakeup;
+    bool m_threadHasBeenJoined;
+    volatile sig_atomic_t m_shouldShutdown;
+    volatile sig_atomic_t m_threadCompleted;
+};
+
+#endif // UNIX_ADAPTER_INPUT_HANDLER_H
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.cc b/node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.cc
new file mode 100644 (file)
index 0000000..573b8ad
--- /dev/null
@@ -0,0 +1,80 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "OutputHandler.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <sys/select.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <vector>
+
+#include "../shared/DebugClient.h"
+#include "Util.h"
+#include "WakeupFd.h"
+
+OutputHandler::OutputHandler(
+        HANDLE conout, int outputfd, WakeupFd &completionWakeup) :
+    m_conout(conout),
+    m_outputfd(outputfd),
+    m_completionWakeup(completionWakeup),
+    m_threadHasBeenJoined(false),
+    m_threadCompleted(0)
+{
+    pthread_create(&m_thread, NULL, OutputHandler::threadProcS, this);
+}
+
+void OutputHandler::shutdown() {
+    if (!m_threadHasBeenJoined) {
+        int ret = pthread_join(m_thread, NULL);
+        assert(ret == 0 && "pthread_join failed");
+        m_threadHasBeenJoined = true;
+    }
+}
+
+void OutputHandler::threadProc() {
+    std::vector<char> buffer(4096);
+    while (true) {
+        DWORD numRead = 0;
+        BOOL ret = ReadFile(m_conout,
+                            &buffer[0], buffer.size(),
+                            &numRead, NULL);
+        if (!ret || numRead == 0) {
+            if (!ret && GetLastError() == ERROR_BROKEN_PIPE) {
+                trace("OutputHandler: pipe closed: numRead=%u",
+                    static_cast<unsigned int>(numRead));
+            } else {
+                trace("OutputHandler: read failed: "
+                    "ret=%d lastError=0x%x numRead=%u",
+                    ret,
+                    static_cast<unsigned int>(GetLastError()),
+                    static_cast<unsigned int>(numRead));
+            }
+            break;
+        }
+        if (!writeAll(m_outputfd, &buffer[0], numRead)) {
+            break;
+        }
+    }
+    m_threadCompleted = 1;
+    m_completionWakeup.set();
+}
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.h b/node_modules/node-pty/deps/winpty/src/unix-adapter/OutputHandler.h
new file mode 100644 (file)
index 0000000..48241c5
--- /dev/null
@@ -0,0 +1,53 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#ifndef UNIX_ADAPTER_OUTPUT_HANDLER_H
+#define UNIX_ADAPTER_OUTPUT_HANDLER_H
+
+#include <windows.h>
+#include <pthread.h>
+#include <signal.h>
+
+#include "WakeupFd.h"
+
+// Connect winpty CONOUT/CONERR to a Cygwin blocking fd.
+class OutputHandler {
+public:
+    OutputHandler(HANDLE conout, int outputfd, WakeupFd &completionWakeup);
+    ~OutputHandler() { shutdown(); }
+    bool isComplete() { return m_threadCompleted; }
+    void shutdown();
+
+private:
+    static void *threadProcS(void *pvthis) {
+        reinterpret_cast<OutputHandler*>(pvthis)->threadProc();
+        return NULL;
+    }
+    void threadProc();
+
+    HANDLE m_conout;
+    int m_outputfd;
+    pthread_t m_thread;
+    WakeupFd &m_completionWakeup;
+    bool m_threadHasBeenJoined;
+    volatile sig_atomic_t m_threadCompleted;
+};
+
+#endif // UNIX_ADAPTER_OUTPUT_HANDLER_H
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/Util.cc b/node_modules/node-pty/deps/winpty/src/unix-adapter/Util.cc
new file mode 100644 (file)
index 0000000..e13f84a
--- /dev/null
@@ -0,0 +1,86 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#include "Util.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "../shared/DebugClient.h"
+
+// Write the entire buffer, restarting it as necessary.
+bool writeAll(int fd, const void *buffer, size_t size) {
+    size_t written = 0;
+    while (written < size) {
+        int ret = write(fd,
+                        reinterpret_cast<const char*>(buffer) + written,
+                        size - written);
+        if (ret == -1 && errno == EINTR) {
+            continue;
+        }
+        if (ret <= 0) {
+            trace("write failed: "
+                "fd=%d errno=%d size=%u written=%d ret=%d",
+                fd,
+                errno,
+                static_cast<unsigned int>(size),
+                static_cast<unsigned int>(written),
+                ret);
+            return false;
+        }
+        assert(static_cast<size_t>(ret) <= size - written);
+        written += ret;
+    }
+    assert(written == size);
+    return true;
+}
+
+bool writeStr(int fd, const char *str) {
+    return writeAll(fd, str, strlen(str));
+}
+
+void selectWrapper(const char *diagName, int nfds, fd_set *readfds) {
+    int ret = select(nfds, readfds, NULL, NULL, NULL);
+    if (ret < 0) {
+        if (errno == EINTR) {
+            FD_ZERO(readfds);
+            return;
+        }
+#ifdef WINPTY_TARGET_MSYS1
+        // The select system call sometimes fails with EAGAIN instead of EINTR.
+        // This apparantly only happens with the old Cygwin fork "MSYS" used in
+        // the mingw.org project.  select is not supposed to fail with EAGAIN,
+        // and EAGAIN does not make much sense as an error code.  (The whole
+        // point of select is to block.)
+        if (errno == EAGAIN) {
+            trace("%s select returned EAGAIN: interpreting like EINTR",
+                diagName);
+            FD_ZERO(readfds);
+            return;
+        }
+#endif
+        fprintf(stderr, "Internal error: %s select failed: "
+            "error %d", diagName, errno);
+        abort();
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/Util.h b/node_modules/node-pty/deps/winpty/src/unix-adapter/Util.h
new file mode 100644 (file)
index 0000000..cadb4c8
--- /dev/null
@@ -0,0 +1,31 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef UNIX_ADAPTER_UTIL_H
+#define UNIX_ADAPTER_UTIL_H
+
+#include <stdlib.h>
+#include <sys/select.h>
+
+bool writeAll(int fd, const void *buffer, size_t size);
+bool writeStr(int fd, const char *str);
+void selectWrapper(const char *diagName, int nfds, fd_set *readfds);
+
+#endif // UNIX_ADAPTER_UTIL_H
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.cc b/node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.cc
new file mode 100644 (file)
index 0000000..6b47379
--- /dev/null
@@ -0,0 +1,70 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+#include "WakeupFd.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+static void setFdNonBlock(int fd) {
+    int status = fcntl(fd, F_GETFL);
+    fcntl(fd, F_SETFL, status | O_NONBLOCK);
+}
+
+WakeupFd::WakeupFd() {
+    int pipeFd[2];
+    if (pipe(pipeFd) != 0) {
+        perror("Could not create internal wakeup pipe");
+        abort();
+    }
+    m_pipeReadFd = pipeFd[0];
+    m_pipeWriteFd = pipeFd[1];
+    setFdNonBlock(m_pipeReadFd);
+    setFdNonBlock(m_pipeWriteFd);
+}
+
+WakeupFd::~WakeupFd() {
+    close(m_pipeReadFd);
+    close(m_pipeWriteFd);
+}
+
+void WakeupFd::set() {
+    char dummy = 0;
+    int ret;
+    do {
+        ret = write(m_pipeWriteFd, &dummy, 1);
+    } while (ret < 0 && errno == EINTR);
+}
+
+void WakeupFd::reset() {
+    char tmpBuf[256];
+    while (true) {
+        int amount = read(m_pipeReadFd, tmpBuf, sizeof(tmpBuf));
+        if (amount < 0 && errno == EAGAIN) {
+            break;
+        } else if (amount <= 0) {
+            perror("error reading from internal wakeup pipe");
+            abort();
+        }
+    }
+}
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.h b/node_modules/node-pty/deps/winpty/src/unix-adapter/WakeupFd.h
new file mode 100644 (file)
index 0000000..dd8d362
--- /dev/null
@@ -0,0 +1,42 @@
+// Copyright (c) 2015 Ryan Prichard
+//
+// 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.
+
+#ifndef UNIX_ADAPTER_WAKEUP_FD_H
+#define UNIX_ADAPTER_WAKEUP_FD_H
+
+class WakeupFd {
+public:
+    WakeupFd();
+    ~WakeupFd();
+    int fd()   { return m_pipeReadFd; }
+    void set();
+    void reset();
+
+private:
+    // Do not allow copying the WakeupFd object.
+    WakeupFd(const WakeupFd &other);
+    WakeupFd &operator=(const WakeupFd &other);
+
+private:
+    int m_pipeReadFd;
+    int m_pipeWriteFd;
+};
+
+#endif // UNIX_ADAPTER_WAKEUP_FD_H
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/main.cc b/node_modules/node-pty/deps/winpty/src/unix-adapter/main.cc
new file mode 100644 (file)
index 0000000..992cb70
--- /dev/null
@@ -0,0 +1,729 @@
+// Copyright (c) 2011-2015 Ryan Prichard
+//
+// 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.
+
+// MSYS's sys/cygwin.h header only declares cygwin_internal if WINVER is
+// defined, which is defined in windows.h.  Therefore, include windows.h early.
+#include <windows.h>
+
+#include <assert.h>
+#include <cygwin/version.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/select.h>
+#include <sys/cygwin.h>
+#include <termios.h>
+#include <unistd.h>
+
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <winpty.h>
+#include "../shared/DebugClient.h"
+#include "../shared/UnixCtrlChars.h"
+#include "../shared/WinptyVersion.h"
+#include "InputHandler.h"
+#include "OutputHandler.h"
+#include "Util.h"
+#include "WakeupFd.h"
+
+#define CSI "\x1b["
+
+static WakeupFd *g_mainWakeup = NULL;
+
+static WakeupFd &mainWakeup()
+{
+    if (g_mainWakeup == NULL) {
+        static const char msg[] = "Internal error: g_mainWakeup is NULL\r\n";
+        write(STDERR_FILENO, msg, sizeof(msg) - 1);
+        abort();
+    }
+    return *g_mainWakeup;
+}
+
+struct SavedTermiosMode {
+    int count;
+    bool valid[3];
+    termios mode[3];
+};
+
+// Put the input terminal into non-canonical mode.
+static SavedTermiosMode setRawTerminalMode(
+    bool allowNonTtys, bool setStdout, bool setStderr)
+{
+    SavedTermiosMode ret;
+    const char *const kNames[3] = { "stdin", "stdout", "stderr" };
+
+    ret.valid[0] = true;
+    ret.valid[1] = setStdout;
+    ret.valid[2] = setStderr;
+
+    for (int i = 0; i < 3; ++i) {
+        if (!ret.valid[i]) {
+            continue;
+        }
+        if (!isatty(i)) {
+            ret.valid[i] = false;
+            if (!allowNonTtys) {
+                fprintf(stderr, "%s is not a tty\n", kNames[i]);
+                exit(1);
+            }
+        } else {
+            ret.valid[i] = true;
+            if (tcgetattr(i, &ret.mode[i]) < 0) {
+                perror("tcgetattr failed");
+                exit(1);
+            }
+        }
+    }
+
+    if (ret.valid[STDIN_FILENO]) {
+        termios buf;
+        if (tcgetattr(STDIN_FILENO, &buf) < 0) {
+            perror("tcgetattr failed");
+            exit(1);
+        }
+        buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+        buf.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
+        buf.c_cflag &= ~(CSIZE | PARENB);
+        buf.c_cflag |= CS8;
+        buf.c_cc[VMIN] = 1;  // blocking read
+        buf.c_cc[VTIME] = 0;
+        if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &buf) < 0) {
+            fprintf(stderr, "tcsetattr failed\n");
+            exit(1);
+        }
+    }
+
+    for (int i = STDOUT_FILENO; i <= STDERR_FILENO; ++i) {
+        if (!ret.valid[i]) {
+            continue;
+        }
+        termios buf;
+        if (tcgetattr(i, &buf) < 0) {
+            perror("tcgetattr failed");
+            exit(1);
+        }
+        buf.c_cflag &= ~(CSIZE | PARENB);
+        buf.c_cflag |= CS8;
+        buf.c_oflag &= ~OPOST;
+        if (tcsetattr(i, TCSAFLUSH, &buf) < 0) {
+            fprintf(stderr, "tcsetattr failed\n");
+            exit(1);
+        }
+    }
+
+    return ret;
+}
+
+static void restoreTerminalMode(const SavedTermiosMode &original)
+{
+    for (int i = 0; i < 3; ++i) {
+        if (!original.valid[i]) {
+            continue;
+        }
+        if (tcsetattr(i, TCSAFLUSH, &original.mode[i]) < 0) {
+            perror("error restoring terminal mode");
+            exit(1);
+        }
+    }
+}
+
+static void debugShowKey(bool allowNonTtys)
+{
+    printf("\nPress any keys -- Ctrl-D exits\n\n");
+    const SavedTermiosMode saved =
+        setRawTerminalMode(allowNonTtys, false, false);
+    char buf[128];
+    while (true) {
+        const ssize_t len = read(STDIN_FILENO, buf, sizeof(buf));
+        if (len <= 0) {
+            break;
+        }
+        for (int i = 0; i < len; ++i) {
+            char ctrl = decodeUnixCtrlChar(buf[i]);
+            if (ctrl == '\0') {
+                putchar(buf[i]);
+            } else {
+                putchar('^');
+                putchar(ctrl);
+            }
+        }
+        for (int i = 0; i < len; ++i) {
+            unsigned char uch = buf[i];
+            printf("\t%3d %04o 0x%02x\n", uch, uch, uch);
+            fflush(stdout);
+        }
+        if (buf[0] == 4) {
+            // Ctrl-D
+            break;
+        }
+    }
+    restoreTerminalMode(saved);
+}
+
+static void terminalResized(int signo)
+{
+    mainWakeup().set();
+}
+
+static void registerResizeSignalHandler()
+{
+    struct sigaction resizeSigAct;
+    memset(&resizeSigAct, 0, sizeof(resizeSigAct));
+    resizeSigAct.sa_handler = terminalResized;
+    resizeSigAct.sa_flags = SA_RESTART;
+    sigaction(SIGWINCH, &resizeSigAct, NULL);
+}
+
+// Convert the path to a Win32 path if it is a POSIX path, and convert slashes
+// to backslashes.
+static std::string convertPosixPathToWin(const std::string &path)
+{
+    char *tmp;
+#if defined(CYGWIN_VERSION_CYGWIN_CONV) && \
+        CYGWIN_VERSION_API_MINOR >= CYGWIN_VERSION_CYGWIN_CONV
+    // MSYS2 and versions of Cygwin released after 2009 or so use this API.
+    // The original MSYS still lacks this API.
+    ssize_t newSize = cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
+                                       path.c_str(), NULL, 0);
+    assert(newSize >= 0);
+    tmp = new char[newSize + 1];
+    ssize_t success = cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
+                                       path.c_str(), tmp, newSize + 1);
+    assert(success == 0);
+#else
+    // In the current Cygwin header file, this API is documented as deprecated
+    // because it's restricted to paths of MAX_PATH length.  In the CVS version
+    // of MSYS, the newer API doesn't exist, and this older API is implemented
+    // using msys_p2w, which seems like it would handle paths larger than
+    // MAX_PATH, but there's no way to query how large the new path is.
+    // Hopefully, this is large enough.
+    tmp = new char[MAX_PATH + path.size()];
+    cygwin_conv_to_win32_path(path.c_str(), tmp);
+#endif
+    for (int i = 0; tmp[i] != '\0'; ++i) {
+        if (tmp[i] == '/')
+            tmp[i] = '\\';
+    }
+    std::string ret(tmp);
+    delete [] tmp;
+    return ret;
+}
+
+static std::string resolvePath(const std::string &path)
+{
+    char ret[PATH_MAX];
+    ret[0] = '\0';
+    if (realpath(path.c_str(), ret) != ret) {
+        return std::string();
+    }
+    return ret;
+}
+
+template <size_t N>
+static bool endsWith(const std::string &path, const char (&suf)[N])
+{
+    const size_t suffixLen = N - 1;
+    char actualSuf[N];
+    if (path.size() < suffixLen) {
+        return false;
+    }
+    strcpy(actualSuf, &path.c_str()[path.size() - suffixLen]);
+    for (size_t i = 0; i < suffixLen; ++i) {
+        actualSuf[i] = tolower(actualSuf[i]);
+    }
+    return !strcmp(actualSuf, suf);
+}
+
+static std::string findProgram(
+    const char *winptyProgName,
+    const std::string &prog)
+{
+    std::string candidate;
+    if (prog.find('/') == std::string::npos &&
+            prog.find('\\') == std::string::npos) {
+        // XXX: It would be nice to use a lambda here (once/if old MSYS support
+        // is dropped).
+        // Search the PATH.
+        const char *const pathVar = getenv("PATH");
+        const std::string pathList(pathVar ? pathVar : "");
+        size_t elpos = 0;
+        while (true) {
+            const size_t elend = pathList.find(':', elpos);
+            candidate = pathList.substr(elpos, elend - elpos);
+            if (!candidate.empty() && *(candidate.end() - 1) != '/') {
+                candidate += '/';
+            }
+            candidate += prog;
+            candidate = resolvePath(candidate);
+            if (!candidate.empty()) {
+                int perm = X_OK;
+                if (endsWith(candidate, ".bat") || endsWith(candidate, ".cmd")) {
+#ifdef __MSYS__
+                    // In MSYS/MSYS2, batch files don't have the execute bit
+                    // set, so just check that they're readable.
+                    perm = R_OK;
+#endif
+                } else if (endsWith(candidate, ".com") || endsWith(candidate, ".exe")) {
+                    // Do nothing.
+                } else {
+                    // Make the exe extension explicit so that we don't try to
+                    // run shell scripts with CreateProcess/winpty_spawn.
+                    candidate += ".exe";
+                }
+                if (!access(candidate.c_str(), perm)) {
+                    break;
+                }
+            }
+            if (elend == std::string::npos) {
+                fprintf(stderr, "%s: error: cannot start '%s': Not found in PATH\n",
+                    winptyProgName, prog.c_str());
+                exit(1);
+            } else {
+                elpos = elend + 1;
+            }
+        }
+    } else {
+        candidate = resolvePath(prog);
+        if (candidate.empty()) {
+            std::string errstr(strerror(errno));
+            fprintf(stderr, "%s: error: cannot start '%s': %s\n",
+                winptyProgName, prog.c_str(), errstr.c_str());
+            exit(1);
+        }
+    }
+    return convertPosixPathToWin(candidate);
+}
+
+// Convert argc/argv into a Win32 command-line following the escaping convention
+// documented on MSDN.  (e.g. see CommandLineToArgvW documentation)
+static std::string argvToCommandLine(const std::vector<std::string> &argv)
+{
+    std::string result;
+    for (size_t argIndex = 0; argIndex < argv.size(); ++argIndex) {
+        if (argIndex > 0)
+            result.push_back(' ');
+        const char *arg = argv[argIndex].c_str();
+        const bool quote =
+            strchr(arg, ' ') != NULL ||
+            strchr(arg, '\t') != NULL ||
+            *arg == '\0';
+        if (quote)
+            result.push_back('\"');
+        int bsCount = 0;
+        for (const char *p = arg; *p != '\0'; ++p) {
+            if (*p == '\\') {
+                bsCount++;
+            } else if (*p == '\"') {
+                result.append(bsCount * 2 + 1, '\\');
+                result.push_back('\"');
+                bsCount = 0;
+            } else {
+                result.append(bsCount, '\\');
+                bsCount = 0;
+                result.push_back(*p);
+            }
+        }
+        if (quote) {
+            result.append(bsCount * 2, '\\');
+            result.push_back('\"');
+        } else {
+            result.append(bsCount, '\\');
+        }
+    }
+    return result;
+}
+
+static wchar_t *heapMbsToWcs(const char *text)
+{
+    // Calling mbstowcs with a NULL first argument seems to be broken on MSYS.
+    // Instead of returning the size of the converted string, it returns 0.
+    // Using strlen(text) * 2 is probably big enough.
+    size_t maxLen = strlen(text) * 2 + 1;
+    wchar_t *ret = new wchar_t[maxLen];
+    size_t len = mbstowcs(ret, text, maxLen);
+    assert(len != (size_t)-1 && len < maxLen);
+    return ret;
+}
+
+static char *heapWcsToMbs(const wchar_t *text)
+{
+    // Calling wcstombs with a NULL first argument seems to be broken on MSYS.
+    // Instead of returning the size of the converted string, it returns 0.
+    // Using wcslen(text) * 3 is big enough for UTF-8 and probably other
+    // encodings.  For UTF-8, codepoints that fit in a single wchar
+    // (U+0000 to U+FFFF) are encoded using 1-3 bytes.  The remaining code
+    // points needs two wchar's and are encoded using 4 bytes.
+    size_t maxLen = wcslen(text) * 3 + 1;
+    char *ret = new char[maxLen];
+    size_t len = wcstombs(ret, text, maxLen);
+    if (len == (size_t)-1 || len >= maxLen) {
+        delete [] ret;
+        return NULL;
+    } else {
+        return ret;
+    }
+}
+
+static std::string wcsToMbs(const wchar_t *text)
+{
+    std::string ret;
+    const char *ptr = heapWcsToMbs(text);
+    if (ptr != NULL) {
+        ret = ptr;
+        delete [] ptr;
+    }
+    return ret;
+}
+
+void setupWin32Environment()
+{
+    std::map<std::string, std::string> varsToCopy;
+    const char *vars[] = {
+        "WINPTY_DEBUG",
+        "WINPTY_SHOW_CONSOLE",
+        NULL
+    };
+    for (int i = 0; vars[i] != NULL; ++i) {
+        const char *cstr = getenv(vars[i]);
+        if (cstr != NULL && cstr[0] != '\0') {
+            varsToCopy[vars[i]] = cstr;
+        }
+    }
+
+#if defined(__MSYS__) && CYGWIN_VERSION_API_MINOR >= 48 || \
+        !defined(__MSYS__) && CYGWIN_VERSION_API_MINOR >= 153
+    // Use CW_SYNC_WINENV to copy the Unix environment to the Win32
+    // environment.  The command performs special translation on some variables
+    // (such as PATH and TMP).  It also copies the debugging environment
+    // variables.
+    //
+    // Note that the API minor versions have diverged in Cygwin and MSYS.
+    // CW_SYNC_WINENV was added to Cygwin in version 153.  (Cygwin's
+    // include/cygwin/version.h says that CW_SETUP_WINENV was added in 153.
+    // The flag was renamed 8 days after it was added, but the API docs weren't
+    // updated.)  The flag was added to MSYS in version 48.
+    //
+    // Also, in my limited testing, this call seems to be necessary with Cygwin
+    // but unnecessary with MSYS.  Perhaps MSYS is automatically syncing the
+    // Unix environment with the Win32 environment before starting console.exe?
+    // It shouldn't hurt to call it for MSYS.
+    cygwin_internal(CW_SYNC_WINENV);
+#endif
+
+    // Copy debugging environment variables from the Cygwin environment
+    // to the Win32 environment so the agent will inherit it.
+    for (std::map<std::string, std::string>::iterator it = varsToCopy.begin();
+            it != varsToCopy.end();
+            ++it) {
+        wchar_t *nameW = heapMbsToWcs(it->first.c_str());
+        wchar_t *valueW = heapMbsToWcs(it->second.c_str());
+        SetEnvironmentVariableW(nameW, valueW);
+        delete [] nameW;
+        delete [] valueW;
+    }
+
+    // Clear the TERM variable.  The child process's immediate console/terminal
+    // environment is a Windows console, not the terminal that winpty is
+    // communicating with.  Leaving the TERM variable set can break programs in
+    // various ways.  (e.g. arrows keys broken in Cygwin less, IronPython's
+    // help(...) function doesn't start, misc programs decide they should
+    // output color escape codes on pre-Win10).  See
+    // https://github.com/rprichard/winpty/issues/43.
+    SetEnvironmentVariableW(L"TERM", NULL);
+}
+
+static void usage(const char *program, int exitCode)
+{
+    printf("Usage: %s [options] [--] program [args]\n", program);
+    printf("\n");
+    printf("Options:\n");
+    printf("  -h, --help  Show this help message\n");
+    printf("  --mouse     Enable terminal mouse input\n");
+    printf("  --showkey   Dump STDIN escape sequences\n");
+    printf("  --version   Show the winpty version number\n");
+    exit(exitCode);
+}
+
+struct Arguments {
+    std::vector<std::string> childArgv;
+    bool mouseInput;
+    bool testAllowNonTtys;
+    bool testConerr;
+    bool testPlainOutput;
+    bool testColorEscapes;
+};
+
+static void parseArguments(int argc, char *argv[], Arguments &out)
+{
+    out.mouseInput = false;
+    out.testAllowNonTtys = false;
+    out.testConerr = false;
+    out.testPlainOutput = false;
+    out.testColorEscapes = false;
+    bool doShowKeys = false;
+    const char *const program = argc >= 1 ? argv[0] : "<program>";
+    int argi = 1;
+    while (argi < argc) {
+        std::string arg(argv[argi++]);
+        if (arg.size() >= 1 && arg[0] == '-') {
+            if (arg == "-h" || arg == "--help") {
+                usage(program, 0);
+            } else if (arg == "--mouse") {
+                out.mouseInput = true;
+            } else if (arg == "--showkey") {
+                doShowKeys = true;
+            } else if (arg == "--version") {
+                dumpVersionToStdout();
+                exit(0);
+            } else if (arg == "-Xallow-non-tty") {
+                out.testAllowNonTtys = true;
+            } else if (arg == "-Xconerr") {
+                out.testConerr = true;
+            } else if (arg == "-Xplain") {
+                out.testPlainOutput = true;
+            } else if (arg == "-Xcolor") {
+                out.testColorEscapes = true;
+            } else if (arg == "--") {
+                break;
+            } else {
+                fprintf(stderr, "Error: unrecognized option: '%s'\n",
+                    arg.c_str());
+                exit(1);
+            }
+        } else {
+            out.childArgv.push_back(arg);
+            break;
+        }
+    }
+    for (; argi < argc; ++argi) {
+        out.childArgv.push_back(argv[argi]);
+    }
+    if (doShowKeys) {
+        debugShowKey(out.testAllowNonTtys);
+        exit(0);
+    }
+    if (out.childArgv.size() == 0) {
+        usage(program, 1);
+    }
+}
+
+static std::string errorMessageToString(DWORD err)
+{
+    // Use FormatMessageW rather than FormatMessageA, because we want to use
+    // wcstombs to convert to the Cygwin locale, which might not match the
+    // codepage FormatMessageA would use.  We need to convert using wcstombs,
+    // rather than print using %ls, because %ls doesn't work in the original
+    // MSYS.
+    wchar_t *wideMsgPtr = NULL;
+    const DWORD formatRet = FormatMessageW(
+        FORMAT_MESSAGE_FROM_SYSTEM |
+            FORMAT_MESSAGE_ALLOCATE_BUFFER |
+            FORMAT_MESSAGE_IGNORE_INSERTS,
+        NULL,
+        err,
+        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+        reinterpret_cast<wchar_t*>(&wideMsgPtr),
+        0,
+        NULL);
+    if (formatRet == 0 || wideMsgPtr == NULL) {
+        return std::string();
+    }
+    std::string msg = wcsToMbs(wideMsgPtr);
+    LocalFree(wideMsgPtr);
+    const size_t pos = msg.find_last_not_of(" \r\n\t");
+    if (pos == std::string::npos) {
+        msg.clear();
+    } else {
+        msg.erase(pos + 1);
+    }
+    return msg;
+}
+
+static std::string formatErrorMessage(DWORD err)
+{
+    char buf[64];
+    sprintf(buf, "error %#x", static_cast<unsigned int>(err));
+    std::string ret = errorMessageToString(err);
+    if (ret.empty()) {
+        ret += buf;
+    } else {
+        ret += " (";
+        ret += buf;
+        ret += ")";
+    }
+    return ret;
+}
+
+int main(int argc, char *argv[])
+{
+    setlocale(LC_ALL, "");
+
+    g_mainWakeup = new WakeupFd();
+
+    Arguments args;
+    parseArguments(argc, argv, args);
+
+    setupWin32Environment();
+
+    winsize sz = { 0 };
+    sz.ws_col = 80;
+    sz.ws_row = 25;
+    ioctl(STDIN_FILENO, TIOCGWINSZ, &sz);
+
+    DWORD agentFlags = WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION;
+    if (args.testConerr)        { agentFlags |= WINPTY_FLAG_CONERR; }
+    if (args.testPlainOutput)   { agentFlags |= WINPTY_FLAG_PLAIN_OUTPUT; }
+    if (args.testColorEscapes)  { agentFlags |= WINPTY_FLAG_COLOR_ESCAPES; }
+    winpty_config_t *agentCfg = winpty_config_new(agentFlags, NULL);
+    assert(agentCfg != NULL);
+    winpty_config_set_initial_size(agentCfg, sz.ws_col, sz.ws_row);
+    if (args.mouseInput) {
+        winpty_config_set_mouse_mode(agentCfg, WINPTY_MOUSE_MODE_FORCE);
+    }
+
+    winpty_error_ptr_t openErr = NULL;
+    winpty_t *wp = winpty_open(agentCfg, &openErr);
+    if (wp == NULL) {
+        fprintf(stderr, "Error creating winpty: %s\n",
+            wcsToMbs(winpty_error_msg(openErr)).c_str());
+        exit(1);
+    }
+    winpty_config_free(agentCfg);
+    winpty_error_free(openErr);
+
+    HANDLE conin = CreateFileW(winpty_conin_name(wp), GENERIC_WRITE, 0, NULL,
+                               OPEN_EXISTING, 0, NULL);
+    HANDLE conout = CreateFileW(winpty_conout_name(wp), GENERIC_READ, 0, NULL,
+                                OPEN_EXISTING, 0, NULL);
+    assert(conin != INVALID_HANDLE_VALUE);
+    assert(conout != INVALID_HANDLE_VALUE);
+    HANDLE conerr = NULL;
+    if (args.testConerr) {
+        conerr = CreateFileW(winpty_conerr_name(wp), GENERIC_READ, 0, NULL,
+                             OPEN_EXISTING, 0, NULL);
+        assert(conerr != INVALID_HANDLE_VALUE);
+    }
+
+    HANDLE childHandle = NULL;
+
+    {
+        // Start the child process under the console.
+        args.childArgv[0] = findProgram(argv[0], args.childArgv[0]);
+        std::string cmdLine = argvToCommandLine(args.childArgv);
+        wchar_t *cmdLineW = heapMbsToWcs(cmdLine.c_str());
+
+        winpty_spawn_config_t *spawnCfg = winpty_spawn_config_new(
+                WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN,
+                NULL, cmdLineW, NULL, NULL, NULL);
+        assert(spawnCfg != NULL);
+
+        winpty_error_ptr_t spawnErr = NULL;
+        DWORD lastError = 0;
+        BOOL spawnRet = winpty_spawn(wp, spawnCfg, &childHandle, NULL,
+            &lastError, &spawnErr);
+        winpty_spawn_config_free(spawnCfg);
+
+        if (!spawnRet) {
+            winpty_result_t spawnCode = winpty_error_code(spawnErr);
+            if (spawnCode == WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED) {
+                fprintf(stderr, "%s: error: cannot start '%s': %s\n",
+                    argv[0],
+                    cmdLine.c_str(),
+                    formatErrorMessage(lastError).c_str());
+            } else {
+                fprintf(stderr, "%s: error: cannot start '%s': internal error: %s\n",
+                    argv[0],
+                    cmdLine.c_str(),
+                    wcsToMbs(winpty_error_msg(spawnErr)).c_str());
+            }
+            exit(1);
+        }
+        winpty_error_free(spawnErr);
+        delete [] cmdLineW;
+    }
+
+    registerResizeSignalHandler();
+    SavedTermiosMode mode =
+        setRawTerminalMode(args.testAllowNonTtys, true, args.testConerr);
+
+    InputHandler inputHandler(conin, STDIN_FILENO, mainWakeup());
+    OutputHandler outputHandler(conout, STDOUT_FILENO, mainWakeup());
+    OutputHandler *errorHandler = NULL;
+    if (args.testConerr) {
+        errorHandler = new OutputHandler(conerr, STDERR_FILENO, mainWakeup());
+    }
+
+    while (true) {
+        fd_set readfds;
+        FD_ZERO(&readfds);
+        FD_SET(mainWakeup().fd(), &readfds);
+        selectWrapper("main thread", mainWakeup().fd() + 1, &readfds);
+        mainWakeup().reset();
+
+        // Check for terminal resize.
+        {
+            winsize sz2;
+            ioctl(STDIN_FILENO, TIOCGWINSZ, &sz2);
+            if (memcmp(&sz, &sz2, sizeof(sz)) != 0) {
+                sz = sz2;
+                winpty_set_size(wp, sz.ws_col, sz.ws_row, NULL);
+            }
+        }
+
+        // Check for an I/O handler shutting down (possibly indicating that the
+        // child process has exited).
+        if (inputHandler.isComplete() || outputHandler.isComplete() ||
+                (errorHandler != NULL && errorHandler->isComplete())) {
+            break;
+        }
+    }
+
+    // Kill the agent connection.  This will kill the agent, closing the CONIN
+    // and CONOUT pipes on the agent pipe, prompting our I/O handler to shut
+    // down.
+    winpty_free(wp);
+
+    inputHandler.shutdown();
+    outputHandler.shutdown();
+    CloseHandle(conin);
+    CloseHandle(conout);
+
+    if (errorHandler != NULL) {
+        errorHandler->shutdown();
+        delete errorHandler;
+        CloseHandle(conerr);
+    }
+
+    restoreTerminalMode(mode);
+
+    DWORD exitCode = 0;
+    if (!GetExitCodeProcess(childHandle, &exitCode)) {
+        exitCode = 1;
+    }
+    CloseHandle(childHandle);
+    return exitCode;
+}
diff --git a/node_modules/node-pty/deps/winpty/src/unix-adapter/subdir.mk b/node_modules/node-pty/deps/winpty/src/unix-adapter/subdir.mk
new file mode 100644 (file)
index 0000000..200193a
--- /dev/null
@@ -0,0 +1,41 @@
+# Copyright (c) 2011-2015 Ryan Prichard
+#
+# 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.
+
+ALL_TARGETS += build/$(UNIX_ADAPTER_EXE)
+
+$(eval $(call def_unix_target,unix-adapter,))
+
+UNIX_ADAPTER_OBJECTS = \
+       build/unix-adapter/unix-adapter/InputHandler.o \
+       build/unix-adapter/unix-adapter/OutputHandler.o \
+       build/unix-adapter/unix-adapter/Util.o \
+       build/unix-adapter/unix-adapter/WakeupFd.o \
+       build/unix-adapter/unix-adapter/main.o \
+       build/unix-adapter/shared/DebugClient.o \
+       build/unix-adapter/shared/WinptyAssert.o \
+       build/unix-adapter/shared/WinptyVersion.o
+
+build/unix-adapter/shared/WinptyVersion.o : build/gen/GenVersion.h
+
+build/$(UNIX_ADAPTER_EXE) : $(UNIX_ADAPTER_OBJECTS) build/winpty.dll
+       $(info Linking $@)
+       @$(UNIX_CXX) $(UNIX_LDFLAGS) -o $@ $^
+
+-include $(UNIX_ADAPTER_OBJECTS:.o=.d)
diff --git a/node_modules/node-pty/deps/winpty/src/winpty.gyp b/node_modules/node-pty/deps/winpty/src/winpty.gyp
new file mode 100644 (file)
index 0000000..7ee68d5
--- /dev/null
@@ -0,0 +1,206 @@
+{
+    # The MSVC generator is the default.  Select the compiler version by
+    # passing -G msvs_version=<ver> to gyp.  <ver> is a string like 2013e.
+    # See gyp\pylib\gyp\MSVSVersion.py for sample version strings.  You
+    # can also pass configurations.gypi to gyp for 32-bit and 64-bit builds.
+    # See that file for details.
+    #
+    # Pass --format=make to gyp to generate a Makefile instead.  The Makefile
+    # can be configured by passing variables to make, e.g.:
+    #    make -j4 CXX=i686-w64-mingw32-g++ LDFLAGS="-static -static-libgcc -static-libstdc++"
+
+    'variables': {
+        'WINPTY_COMMIT_HASH%': '<!(cmd /c "cd shared && GetCommitHash.bat")',
+    },
+    'target_defaults' : {
+        'defines' : [
+            'UNICODE',
+            '_UNICODE',
+            '_WIN32_WINNT=0x0501',
+            'NOMINMAX',
+        ],
+        'include_dirs': [
+            # Add the 'src/gen' directory to the include path and force gyp to
+            # run the script (re)generating the version header.
+            '<!(cmd /c "cd shared && UpdateGenVersion.bat <(WINPTY_COMMIT_HASH)")',
+        ],
+    },
+    'targets' : [
+        {
+            'target_name' : 'winpty-agent',
+            'type' : 'executable',
+            'include_dirs' : [
+                'include',
+            ],
+            'defines' : [
+                'WINPTY_AGENT_ASSERT',
+            ],
+            'libraries' : [
+                '-ladvapi32',
+                '-lshell32',
+                '-luser32',
+            ],
+            'msvs_settings': {
+                # Specify this setting here to override a setting from somewhere
+                # else, such as node's common.gypi.
+                'VCCLCompilerTool': {
+                    'ExceptionHandling': '1', # /EHsc
+                },
+            },
+            'sources' : [
+                'agent/Agent.h',
+                'agent/Agent.cc',
+                'agent/AgentCreateDesktop.h',
+                'agent/AgentCreateDesktop.cc',
+                'agent/ConsoleFont.cc',
+                'agent/ConsoleFont.h',
+                'agent/ConsoleInput.cc',
+                'agent/ConsoleInput.h',
+                'agent/ConsoleInputReencoding.cc',
+                'agent/ConsoleInputReencoding.h',
+                'agent/ConsoleLine.cc',
+                'agent/ConsoleLine.h',
+                'agent/Coord.h',
+                'agent/DebugShowInput.h',
+                'agent/DebugShowInput.cc',
+                'agent/DefaultInputMap.h',
+                'agent/DefaultInputMap.cc',
+                'agent/DsrSender.h',
+                'agent/EventLoop.h',
+                'agent/EventLoop.cc',
+                'agent/InputMap.h',
+                'agent/InputMap.cc',
+                'agent/LargeConsoleRead.h',
+                'agent/LargeConsoleRead.cc',
+                'agent/NamedPipe.h',
+                'agent/NamedPipe.cc',
+                'agent/Scraper.h',
+                'agent/Scraper.cc',
+                'agent/SimplePool.h',
+                'agent/SmallRect.h',
+                'agent/Terminal.h',
+                'agent/Terminal.cc',
+                'agent/UnicodeEncoding.h',
+                'agent/Win32Console.cc',
+                'agent/Win32Console.h',
+                'agent/Win32ConsoleBuffer.cc',
+                'agent/Win32ConsoleBuffer.h',
+                'agent/main.cc',
+                'shared/AgentMsg.h',
+                'shared/BackgroundDesktop.h',
+                'shared/BackgroundDesktop.cc',
+                'shared/Buffer.h',
+                'shared/Buffer.cc',
+                'shared/DebugClient.h',
+                'shared/DebugClient.cc',
+                'shared/GenRandom.h',
+                'shared/GenRandom.cc',
+                'shared/OsModule.h',
+                'shared/OwnedHandle.h',
+                'shared/OwnedHandle.cc',
+                'shared/StringBuilder.h',
+                'shared/StringUtil.cc',
+                'shared/StringUtil.h',
+                'shared/UnixCtrlChars.h',
+                'shared/WindowsSecurity.cc',
+                'shared/WindowsSecurity.h',
+                'shared/WindowsVersion.h',
+                'shared/WindowsVersion.cc',
+                'shared/WinptyAssert.h',
+                'shared/WinptyAssert.cc',
+                'shared/WinptyException.h',
+                'shared/WinptyException.cc',
+                'shared/WinptyVersion.h',
+                'shared/WinptyVersion.cc',
+                'shared/winpty_snprintf.h',
+            ],
+        },
+        {
+            'target_name' : 'winpty',
+            'type' : 'shared_library',
+            'include_dirs' : [
+                'include',
+            ],
+            'defines' : [
+                'COMPILING_WINPTY_DLL',
+            ],
+            'libraries' : [
+                '-ladvapi32',
+                '-luser32',
+            ],
+            'msvs_settings': {
+                # Specify this setting here to override a setting from somewhere
+                # else, such as node's common.gypi.
+                'VCCLCompilerTool': {
+                    'ExceptionHandling': '1', # /EHsc
+                },
+            },
+            'sources' : [
+                'include/winpty.h',
+                'libwinpty/AgentLocation.cc',
+                'libwinpty/AgentLocation.h',
+                'libwinpty/winpty.cc',
+                'shared/AgentMsg.h',
+                'shared/BackgroundDesktop.h',
+                'shared/BackgroundDesktop.cc',
+                'shared/Buffer.h',
+                'shared/Buffer.cc',
+                'shared/DebugClient.h',
+                'shared/DebugClient.cc',
+                'shared/GenRandom.h',
+                'shared/GenRandom.cc',
+                'shared/OsModule.h',
+                'shared/OwnedHandle.h',
+                'shared/OwnedHandle.cc',
+                'shared/StringBuilder.h',
+                'shared/StringUtil.cc',
+                'shared/StringUtil.h',
+                'shared/WindowsSecurity.cc',
+                'shared/WindowsSecurity.h',
+                'shared/WindowsVersion.h',
+                'shared/WindowsVersion.cc',
+                'shared/WinptyAssert.h',
+                'shared/WinptyAssert.cc',
+                'shared/WinptyException.h',
+                'shared/WinptyException.cc',
+                'shared/WinptyVersion.h',
+                'shared/WinptyVersion.cc',
+                'shared/winpty_snprintf.h',
+            ],
+        },
+        {
+            'target_name' : 'winpty-debugserver',
+            'type' : 'executable',
+            'msvs_settings': {
+                # Specify this setting here to override a setting from somewhere
+                # else, such as node's common.gypi.
+                'VCCLCompilerTool': {
+                    'ExceptionHandling': '1', # /EHsc
+                },
+            },
+            'sources' : [
+                'debugserver/DebugServer.cc',
+                'shared/DebugClient.h',
+                'shared/DebugClient.cc',
+                'shared/OwnedHandle.h',
+                'shared/OwnedHandle.cc',
+                'shared/OsModule.h',
+                'shared/StringBuilder.h',
+                'shared/StringUtil.cc',
+                'shared/StringUtil.h',
+                'shared/WindowsSecurity.h',
+                'shared/WindowsSecurity.cc',
+                'shared/WindowsVersion.h',
+                'shared/WindowsVersion.cc',
+                'shared/WinptyAssert.h',
+                'shared/WinptyAssert.cc',
+                'shared/WinptyException.h',
+                'shared/WinptyException.cc',
+                'shared/winpty_snprintf.h',
+            ],
+            'libraries' : [
+                '-ladvapi32',
+            ],
+        }
+    ],
+}
diff --git a/node_modules/node-pty/deps/winpty/vcbuild.bat b/node_modules/node-pty/deps/winpty/vcbuild.bat
new file mode 100644 (file)
index 0000000..f3787a2
--- /dev/null
@@ -0,0 +1,83 @@
+@echo off
+
+REM -- Script requirements:
+REM --
+REM --  * git               This program must be in the Path to check out
+REM --                      build-gyp.  If that directory already exists, then
+REM --                      git isn't necessary, but if it is missing, no
+REM --                      commit hash will be embedded into binaries.
+REM --
+REM --  * python            A non-Cygwin Python 2 python.exe must be in the
+REM --                      Path to run gyp.
+REM --
+REM --  * msbuild           msbuild must be in the Path.  It is probably
+REM --                      important to have msbuild from the correct MSVC
+REM --                      release.
+REM --
+REM -- The script's output binaries are in the src/Release/{Win32,x64}
+REM -- directory.
+
+REM -------------------------------------------------------------------------
+REM -- Parse arguments
+
+setlocal
+cd %~dp0
+set GYP_ARGS=
+set MSVC_PLATFORM=x64
+
+:ParamLoop
+if "%1" == "" goto :ParamDone
+if "%1" == "--msvc-platform" (
+    REM -- One of Win32 or x64.
+    set MSVC_PLATFORM=%2
+    shift && shift
+    goto :ParamLoop
+)
+if "%1" == "--gyp-msvs-version" (
+    set GYP_ARGS=%GYP_ARGS% -G msvs_version=%2
+    shift && shift
+    goto :ParamLoop
+)
+if "%1" == "--toolset" (
+    set GYP_ARGS=%GYP_ARGS% -D WINPTY_MSBUILD_TOOLSET=%2
+    shift && shift
+    goto :ParamLoop
+)
+if "%1" == "--commit-hash" (
+    set GYP_ARGS=%GYP_ARGS% -D WINPTY_COMMIT_HASH=%2
+    shift && shift
+    goto :ParamLoop
+)
+echo error: Unrecognized argument: %1
+exit /b 1
+:ParamDone
+
+REM -------------------------------------------------------------------------
+REM -- Check out GYP.  GYP doesn't seem to have releases, so just use the
+REM -- current master commit.
+
+if not exist build-gyp (
+    git clone https://chromium.googlesource.com/external/gyp build-gyp || (
+        echo error: GYP clone failed
+        exit /b 1
+    )
+)
+
+REM -------------------------------------------------------------------------
+REM -- Run gyp to generate MSVC project files.
+
+cd src
+
+call ..\build-gyp\gyp.bat winpty.gyp -I configurations.gypi %GYP_ARGS%
+if errorlevel 1 (
+    echo error: GYP failed
+    exit /b 1
+)
+
+REM -------------------------------------------------------------------------
+REM -- Compile the project.
+
+msbuild winpty.sln /m /p:Platform=%MSVC_PLATFORM% || (
+    echo error: msbuild failed
+    exit /b 1
+)
diff --git a/node_modules/node-pty/lib/conpty_console_list_agent.js b/node_modules/node-pty/lib/conpty_console_list_agent.js
new file mode 100644 (file)
index 0000000..e5217ef
--- /dev/null
@@ -0,0 +1,20 @@
+"use strict";
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ *
+ * This module fetches the console process list for a particular PID. It must be
+ * called from a different process (child_process.fork) as there can only be a
+ * single console attached to a process.
+ */
+var getConsoleProcessList;
+try {
+    getConsoleProcessList = require('../build/Release/conpty_console_list.node').getConsoleProcessList;
+}
+catch (err) {
+    getConsoleProcessList = require('../build/Debug/conpty_console_list.node').getConsoleProcessList;
+}
+var shellPid = parseInt(process.argv[2], 10);
+var consoleProcessList = getConsoleProcessList(shellPid);
+process.send({ consoleProcessList: consoleProcessList });
+process.exit(0);
+//# sourceMappingURL=conpty_console_list_agent.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/conpty_console_list_agent.js.map b/node_modules/node-pty/lib/conpty_console_list_agent.js.map
new file mode 100644 (file)
index 0000000..7d0ad08
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"conpty_console_list_agent.js","sourceRoot":"","sources":["../src/conpty_console_list_agent.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;AAEH,IAAI,qBAA0B,CAAC;AAC/B,IAAI;IACF,qBAAqB,GAAG,OAAO,CAAC,2CAA2C,CAAC,CAAC,qBAAqB,CAAC;CACpG;AAAC,OAAO,GAAG,EAAE;IACZ,qBAAqB,GAAG,OAAO,CAAC,yCAAyC,CAAC,CAAC,qBAAqB,CAAC;CAClG;AAED,IAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/C,IAAM,kBAAkB,GAAG,qBAAqB,CAAC,QAAQ,CAAC,CAAC;AAC3D,OAAO,CAAC,IAAI,CAAC,EAAE,kBAAkB,oBAAA,EAAE,CAAC,CAAC;AACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/eventEmitter2.js b/node_modules/node-pty/lib/eventEmitter2.js
new file mode 100644 (file)
index 0000000..c53d1f0
--- /dev/null
@@ -0,0 +1,46 @@
+"use strict";
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var EventEmitter2 = /** @class */ (function () {
+    function EventEmitter2() {
+        this._listeners = [];
+    }
+    Object.defineProperty(EventEmitter2.prototype, "event", {
+        get: function () {
+            var _this = this;
+            if (!this._event) {
+                this._event = function (listener) {
+                    _this._listeners.push(listener);
+                    var disposable = {
+                        dispose: function () {
+                            for (var i = 0; i < _this._listeners.length; i++) {
+                                if (_this._listeners[i] === listener) {
+                                    _this._listeners.splice(i, 1);
+                                    return;
+                                }
+                            }
+                        }
+                    };
+                    return disposable;
+                };
+            }
+            return this._event;
+        },
+        enumerable: true,
+        configurable: true
+    });
+    EventEmitter2.prototype.fire = function (data) {
+        var queue = [];
+        for (var i = 0; i < this._listeners.length; i++) {
+            queue.push(this._listeners[i]);
+        }
+        for (var i = 0; i < queue.length; i++) {
+            queue[i].call(undefined, data);
+        }
+    };
+    return EventEmitter2;
+}());
+exports.EventEmitter2 = EventEmitter2;
+//# sourceMappingURL=eventEmitter2.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/eventEmitter2.js.map b/node_modules/node-pty/lib/eventEmitter2.js.map
new file mode 100644 (file)
index 0000000..b850094
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"eventEmitter2.js","sourceRoot":"","sources":["../src/eventEmitter2.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAYH;IAAA;QACU,eAAU,GAAmB,EAAE,CAAC;IAgC1C,CAAC;IA7BC,sBAAW,gCAAK;aAAhB;YAAA,iBAkBC;YAjBC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;gBAChB,IAAI,CAAC,MAAM,GAAG,UAAC,QAAuB;oBACpC,KAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;oBAC/B,IAAM,UAAU,GAAG;wBACjB,OAAO,EAAE;4BACP,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gCAC/C,IAAI,KAAI,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;oCACnC,KAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;oCAC7B,OAAO;iCACR;6BACF;wBACH,CAAC;qBACF,CAAC;oBACF,OAAO,UAAU,CAAC;gBACpB,CAAC,CAAC;aACH;YACD,OAAO,IAAI,CAAC,MAAM,CAAC;QACrB,CAAC;;;OAAA;IAEM,4BAAI,GAAX,UAAY,IAAO;QACjB,IAAM,KAAK,GAAmB,EAAE,CAAC;QACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC/C,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;SAChC;QACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACrC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;SAChC;IACH,CAAC;IACH,oBAAC;AAAD,CAAC,AAjCD,IAiCC;AAjCY,sCAAa"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/eventEmitter2.test.js b/node_modules/node-pty/lib/eventEmitter2.test.js
new file mode 100644 (file)
index 0000000..14e65a0
--- /dev/null
@@ -0,0 +1,30 @@
+"use strict";
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var assert = require("assert");
+var eventEmitter2_1 = require("./eventEmitter2");
+describe('EventEmitter2', function () {
+    it('should fire listeners multiple times', function () {
+        var order = [];
+        var emitter = new eventEmitter2_1.EventEmitter2();
+        emitter.event(function (data) { return order.push(data + 'a'); });
+        emitter.event(function (data) { return order.push(data + 'b'); });
+        emitter.fire(1);
+        emitter.fire(2);
+        assert.deepEqual(order, ['1a', '1b', '2a', '2b']);
+    });
+    it('should not fire listeners once disposed', function () {
+        var order = [];
+        var emitter = new eventEmitter2_1.EventEmitter2();
+        emitter.event(function (data) { return order.push(data + 'a'); });
+        var disposeB = emitter.event(function (data) { return order.push(data + 'b'); });
+        emitter.event(function (data) { return order.push(data + 'c'); });
+        emitter.fire(1);
+        disposeB.dispose();
+        emitter.fire(2);
+        assert.deepEqual(order, ['1a', '1b', '1c', '2a', '2c']);
+    });
+});
+//# sourceMappingURL=eventEmitter2.test.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/eventEmitter2.test.js.map b/node_modules/node-pty/lib/eventEmitter2.test.js.map
new file mode 100644 (file)
index 0000000..d3b95e6
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"eventEmitter2.test.js","sourceRoot":"","sources":["../src/eventEmitter2.test.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,+BAAiC;AACjC,iDAAgD;AAEhD,QAAQ,CAAC,eAAe,EAAE;IACxB,EAAE,CAAC,sCAAsC,EAAE;QACzC,IAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,IAAM,OAAO,GAAG,IAAI,6BAAa,EAAU,CAAC;QAC5C,OAAO,CAAC,KAAK,CAAC,UAAA,IAAI,IAAI,OAAA,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,EAAtB,CAAsB,CAAC,CAAC;QAC9C,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ules/node-pty/lib/index.js
new file mode 100644 (file)
index 0000000..904748e
--- /dev/null
@@ -0,0 +1,50 @@
+"use strict";
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var terminalCtor;
+if (process.platform === 'win32') {
+    terminalCtor = require('./windowsTerminal').WindowsTerminal;
+}
+else {
+    terminalCtor = require('./unixTerminal').UnixTerminal;
+}
+/**
+ * Forks a process as a pseudoterminal.
+ * @param file The file to launch.
+ * @param args The file's arguments as argv (string[]) or in a pre-escaped
+ * CommandLine format (string). Note that the CommandLine option is only
+ * available on Windows and is expected to be escaped properly.
+ * @param options The options of the terminal.
+ * @throws When the file passed to spawn with does not exists.
+ * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
+ * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
+ * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx
+ */
+function spawn(file, args, opt) {
+    return new terminalCtor(file, args, opt);
+}
+exports.spawn = spawn;
+/** @deprecated */
+function fork(file, args, opt) {
+    return new terminalCtor(file, args, opt);
+}
+exports.fork = fork;
+/** @deprecated */
+function createTerminal(file, args, opt) {
+    return new terminalCtor(file, args, opt);
+}
+exports.createTerminal = createTerminal;
+function open(options) {
+    return terminalCtor.open(options);
+}
+exports.open = open;
+/**
+ * Expose the native API when not Windows, note that this is not public API and
+ * could be removed at any time.
+ */
+exports.native = (process.platform !== 'win32' ? require('../build/Release/pty.node') : null);
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/index.js.map b/node_modules/node-pty/lib/index.js.map
new file mode 100644 (file)
index 0000000..74162a6
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAKH,IAAI,YAAiB,CAAC;AACtB,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,YAAY,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC,eAAe,CAAC;CAC7D;KAAM;IACL,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC,YAAY,CAAC;CACvD;AAED;;;;;;;;;;;GAWG;AACH,SAAgB,KAAK,CAAC,IAAa,EAAE,IAAwB,EAAE,GAA8C;IAC3G,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC;AAFD,sBAEC;AAED,kBAAkB;AAClB,SAAgB,IAAI,CAAC,IAAa,EAAE,IAAwB,EAAE,GAA8C;IAC1G,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC;AAFD,oBAEC;AAED,kBAAkB;AAClB,SAAgB,cAAc,CAAC,IAAa,EAAE,IAAwB,EAAE,GAA8C;IACpH,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC;AAFD,wCAEC;AAED,SAAgB,IAAI,CAAC,OAAwB;IAC3C,OAAO,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC;AAFD,oBAEC;AAED;;;GAGG;AACU,QAAA,MAAM,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/interfaces.js b/node_modules/node-pty/lib/interfaces.js
new file mode 100644 (file)
index 0000000..63c5d5b
--- /dev/null
@@ -0,0 +1,7 @@
+"use strict";
+/**
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+//# sourceMappingURL=interfaces.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/interfaces.js.map b/node_modules/node-pty/lib/interfaces.js.map
new file mode 100644 (file)
index 0000000..ab6d381
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":";AAAA;;;GAGG"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/terminal.js b/node_modules/node-pty/lib/terminal.js
new file mode 100644 (file)
index 0000000..a4f1eed
--- /dev/null
@@ -0,0 +1,167 @@
+"use strict";
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var events_1 = require("events");
+var eventEmitter2_1 = require("./eventEmitter2");
+exports.DEFAULT_COLS = 80;
+exports.DEFAULT_ROWS = 24;
+/**
+ * Default messages to indicate PAUSE/RESUME for automatic flow control.
+ * To avoid conflicts with rebound XON/XOFF control codes (such as on-my-zsh),
+ * the sequences can be customized in `IPtyForkOptions`.
+ */
+var FLOW_CONTROL_PAUSE = '\x13'; // defaults to XOFF
+var FLOW_CONTROL_RESUME = '\x11'; // defaults to XON
+var Terminal = /** @class */ (function () {
+    function Terminal(opt) {
+        this._onData = new eventEmitter2_1.EventEmitter2();
+        this._onExit = new eventEmitter2_1.EventEmitter2();
+        // for 'close'
+        this._internalee = new events_1.EventEmitter();
+        if (!opt) {
+            return;
+        }
+        // Do basic type checks here in case node-pty is being used within JavaScript. If the wrong
+        // types go through to the C++ side it can lead to hard to diagnose exceptions.
+        this._checkType('name', opt.name ? opt.name : null, 'string');
+        this._checkType('cols', opt.cols ? opt.cols : null, 'number');
+        this._checkType('rows', opt.rows ? opt.rows : null, 'number');
+        this._checkType('cwd', opt.cwd ? opt.cwd : null, 'string');
+        this._checkType('env', opt.env ? opt.env : null, 'object');
+        this._checkType('uid', opt.uid ? opt.uid : null, 'number');
+        this._checkType('gid', opt.gid ? opt.gid : null, 'number');
+        this._checkType('encoding', opt.encoding ? opt.encoding : null, 'string');
+        // setup flow control handling
+        this.handleFlowControl = !!(opt.handleFlowControl);
+        this._flowControlPause = opt.flowControlPause || FLOW_CONTROL_PAUSE;
+        this._flowControlResume = opt.flowControlResume || FLOW_CONTROL_RESUME;
+    }
+    Object.defineProperty(Terminal.prototype, "onData", {
+        get: function () { return this._onData.event; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(Terminal.prototype, "onExit", {
+        get: function () { return this._onExit.event; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(Terminal.prototype, "pid", {
+        get: function () { return this._pid; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(Terminal.prototype, "cols", {
+        get: function () { return this._cols; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(Terminal.prototype, "rows", {
+        get: function () { return this._rows; },
+        enumerable: true,
+        configurable: true
+    });
+    Terminal.prototype.write = function (data) {
+        if (this.handleFlowControl) {
+            // PAUSE/RESUME messages are not forwarded to the pty
+            if (data === this._flowControlPause) {
+                this.pause();
+                return;
+            }
+            if (data === this._flowControlResume) {
+                this.resume();
+                return;
+            }
+        }
+        // everything else goes to the real pty
+        this._write(data);
+    };
+    Terminal.prototype._forwardEvents = function () {
+        var _this = this;
+        this.on('data', function (e) { return _this._onData.fire(e); });
+        this.on('exit', function (exitCode, signal) { return _this._onExit.fire({ exitCode: exitCode, signal: signal }); });
+    };
+    Terminal.prototype._checkType = function (name, value, type) {
+        if (value && typeof value !== type) {
+            throw new Error(name + " must be a " + type + " (not a " + typeof value + ")");
+        }
+    };
+    /** See net.Socket.end */
+    Terminal.prototype.end = function (data) {
+        this._socket.end(data);
+    };
+    /** See stream.Readable.pipe */
+    Terminal.prototype.pipe = function (dest, options) {
+        return this._socket.pipe(dest, options);
+    };
+    /** See net.Socket.pause */
+    Terminal.prototype.pause = function () {
+        return this._socket.pause();
+    };
+    /** See net.Socket.resume */
+    Terminal.prototype.resume = function () {
+        return this._socket.resume();
+    };
+    /** See net.Socket.setEncoding */
+    Terminal.prototype.setEncoding = function (encoding) {
+        if (this._socket._decoder) {
+            delete this._socket._decoder;
+        }
+        if (encoding) {
+            this._socket.setEncoding(encoding);
+        }
+    };
+    Terminal.prototype.addListener = function (eventName, listener) { this.on(eventName, listener); };
+    Terminal.prototype.on = function (eventName, listener) {
+        if (eventName === 'close') {
+            this._internalee.on('close', listener);
+            return;
+        }
+        this._socket.on(eventName, listener);
+    };
+    Terminal.prototype.emit = function (eventName) {
+        var args = [];
+        for (var _i = 1; _i < arguments.length; _i++) {
+            args[_i - 1] = arguments[_i];
+        }
+        if (eventName === 'close') {
+            return this._internalee.emit.apply(this._internalee, arguments);
+        }
+        return this._socket.emit.apply(this._socket, arguments);
+    };
+    Terminal.prototype.listeners = function (eventName) {
+        return this._socket.listeners(eventName);
+    };
+    Terminal.prototype.removeListener = function (eventName, listener) {
+        this._socket.removeListener(eventName, listener);
+    };
+    Terminal.prototype.removeAllListeners = function (eventName) {
+        this._socket.removeAllListeners(eventName);
+    };
+    Terminal.prototype.once = function (eventName, listener) {
+        this._socket.once(eventName, listener);
+    };
+    Terminal.prototype._close = function () {
+        this._socket.writable = false;
+        this._socket.readable = false;
+        this.write = function () { };
+        this.end = function () { };
+        this._writable = false;
+        this._readable = false;
+    };
+    Terminal.prototype._parseEnv = function (env) {
+        var keys = Object.keys(env || {});
+        var pairs = [];
+        for (var i = 0; i < keys.length; i++) {
+            pairs.push(keys[i] + '=' + env[keys[i]]);
+        }
+        return pairs;
+    };
+    return Terminal;
+}());
+exports.Terminal = Terminal;
+//# sourceMappingURL=terminal.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/terminal.js.map b/node_modules/node-pty/lib/ter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IACf,CAAC;IACH,eAAC;AAAD,CAAC,AA3KD,IA2KC;AA3KqB,4BAAQ"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/terminal.test.js b/node_modules/node-pty/lib/terminal.test.js
new file mode 100644 (file)
index 0000000..da0e516
--- /dev/null
@@ -0,0 +1,58 @@
+"use strict";
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var assert = require("assert");
+var windowsTerminal_1 = require("./windowsTerminal");
+var unixTerminal_1 = require("./unixTerminal");
+var terminalConstructor = (process.platform === 'win32') ? windowsTerminal_1.WindowsTerminal : unixTerminal_1.UnixTerminal;
+var SHELL = (process.platform === 'win32') ? 'cmd.exe' : '/bin/bash';
+var terminalCtor;
+if (process.platform === 'win32') {
+    terminalCtor = require('./windowsTerminal');
+}
+else {
+    terminalCtor = require('./unixTerminal');
+}
+describe('Terminal', function () {
+    describe('constructor', function () {
+        it('should do basic type checks', function () {
+            assert.throws(function () { return new terminalCtor('a', 'b', { 'name': {} }); }, 'name must be a string (not a object)');
+        });
+    });
+    describe('automatic flow control', function () {
+        it('should respect ctor flow control options', function () {
+            var pty = new terminalConstructor(SHELL, [], { handleFlowControl: true, flowControlPause: 'abc', flowControlResume: '123' });
+            assert.equal(pty.handleFlowControl, true);
+            assert.equal(pty._flowControlPause, 'abc');
+            assert.equal(pty._flowControlResume, '123');
+        });
+        // TODO: I don't think this test ever worked due to pollUntil being used incorrectly
+        // it('should do flow control automatically', async function(): Promise<void> {
+        //   // Flow control doesn't work on Windows
+        //   if (process.platform === 'win32') {
+        //     return;
+        //   }
+        //   this.timeout(10000);
+        //   const pty = new terminalConstructor(SHELL, [], {handleFlowControl: true, flowControlPause: 'PAUSE', flowControlResume: 'RESUME'});
+        //   let read: string = '';
+        //   pty.on('data', data => read += data);
+        //   pty.on('pause', () => read += 'paused');
+        //   pty.on('resume', () => read += 'resumed');
+        //   pty.write('1');
+        //   pty.write('PAUSE');
+        //   pty.write('2');
+        //   pty.write('RESUME');
+        //   pty.write('3');
+        //   await pollUntil(() => {
+        //     return stripEscapeSequences(read).endsWith('1pausedresumed23');
+        //   }, 100, 10);
+        // });
+    });
+});
+function stripEscapeSequences(data) {
+    return data.replace(/\u001b\[0K/, '');
+}
+//# sourceMappingURL=terminal.test.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/terminal.test.js.map b/node_modules/node-pty/lib/terminal.test.js.map
new file mode 100644 (file)
index 0000000..8f25cd6
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"terminal.test.js","sourceRoot":"","sources":["../src/terminal.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,+BAAiC;AACjC,qDAAoD;AACpD,+CAA8C;AAG9C,IAAM,mBAAmB,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,iCAAe,CAAC,CAAC,CAAC,2BAAY,CAAC;AAC5F,IAAM,KAAK,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;AAEvE,IAAI,YAA4C,CAAC;AACjD,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,YAAY,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC7C;KAAM;IACL,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC1C;AAGD,QAAQ,CAAC,UAAU,EAAE;IACnB,QAAQ,CAAC,aAAa,EAAE;QACtB,EAAE,CAAC,6BAA6B,EAAE;YAChC,MAAM,CAAC,MAAM,CACX,cAAM,OAAA,IAAU,YAAa,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,EAAjD,CAAiD,EACvD,sCAAsC,CACvC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,wBAAwB,EAAE;QACjC,EAAE,CAAC,0CAA0C,EAAE;YAC7C,IAAM,GAAG,GAAG,IAAI,mBAAmB,CAAC,KAAK,EAAE,EAAE,EAAE,EAAC,iBAAiB,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,iBAAiB,EAAE,KAAK,EAAC,CAAC,CAAC;YAC7H,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;YAC1C,MAAM,CAAC,KAAK,CAAE,GAAW,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;YACpD,MAAM,CAAC,KAAK,CAAE,GAAW,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;QACH,oFAAoF;QACpF,+EAA+E;QAC/E,4CAA4C;QAC5C,wCAAwC;QACxC,cAAc;QACd,MAAM;QAEN,yBAAyB;QACzB,uIAAuI;QACvI,2BAA2B;QAC3B,0CAA0C;QAC1C,6CAA6C;QAC7C,+CAA+C;QAC/C,oBAAoB;QACpB,wBAAwB;QACxB,oBAAoB;QACpB,yBAAyB;QACzB,oBAAoB;QACpB,4BAA4B;QAC5B,sEAAsE;QACtE,iBAAiB;QACjB,MAAM;IACR,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAS,oBAAoB,CAAC,IAAY;IACxC,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;AACxC,CAAC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/testUtils.test.js b/node_modules/node-pty/lib/testUtils.test.js
new file mode 100644 (file)
index 0000000..b861d36
--- /dev/null
@@ -0,0 +1,27 @@
+"use strict";
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+function pollUntil(cb, timeout, interval) {
+    return new Promise(function (resolve, reject) {
+        var intervalId = setInterval(function () {
+            if (cb()) {
+                clearInterval(intervalId);
+                clearTimeout(timeoutId);
+                resolve();
+            }
+        }, interval);
+        var timeoutId = setTimeout(function () {
+            clearInterval(intervalId);
+            if (cb()) {
+                resolve();
+            }
+            else {
+                reject();
+            }
+        }, timeout);
+    });
+}
+exports.pollUntil = pollUntil;
+//# sourceMappingURL=testUtils.test.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/testUtils.test.js.map b/node_modules/node-pty/lib/testUtils.test.js.map
new file mode 100644 (file)
index 0000000..73b16dc
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"testUtils.test.js","sourceRoot":"","sources":["../src/testUtils.test.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,SAAgB,SAAS,CAAC,EAAiB,EAAE,OAAe,EAAE,QAAgB;IAC5E,OAAO,IAAI,OAAO,CAAO,UAAC,OAAO,EAAE,MAAM;QACvC,IAAM,UAAU,GAAG,WAAW,CAAC;YAC7B,IAAI,EAAE,EAAE,EAAE;gBACR,aAAa,CAAC,UAAU,CAAC,CAAC;gBAC1B,YAAY,CAAC,SAAS,CAAC,CAAC;gBACxB,OAAO,EAAE,CAAC;aACX;QACH,CAAC,EAAE,QAAQ,CAAC,CAAC;QACb,IAAM,SAAS,GAAG,UAAU,CAAC;YAC3B,aAAa,CAAC,UAAU,CAAC,CAAC;YAC1B,IAAI,EAAE,EAAE,EAAE;gBACR,OAAO,EAAE,CAAC;aACX;iBAAM;gBACL,MAAM,EAAE,CAAC;aACV;QACH,CAAC,EAAE,OAAO,CAAC,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAlBD,8BAkBC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/types.js b/node_modules/node-pty/lib/types.js
new file mode 100644 (file)
index 0000000..3768e95
--- /dev/null
@@ -0,0 +1,7 @@
+"use strict";
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+//# sourceMappingURL=types.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/types.js.map b/node_modules/node-pty/lib/types.js.map
new file mode 100644 (file)
index 0000000..5ab8a95
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA;;;GAGG"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/unixTerminal.js b/node_modules/node-pty/lib/unixTerminal.js
new file mode 100644 (file)
index 0000000..004364d
--- /dev/null
@@ -0,0 +1,276 @@
+"use strict";
+var __extends = (this && this.__extends) || (function () {
+    var extendStatics = function (d, b) {
+        extendStatics = Object.setPrototypeOf ||
+            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+        return extendStatics(d, b);
+    };
+    return function (d, b) {
+        extendStatics(d, b);
+        function __() { this.constructor = d; }
+        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+    };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+var net = require("net");
+var terminal_1 = require("./terminal");
+var utils_1 = require("./utils");
+var pty;
+try {
+    pty = require('../build/Release/pty.node');
+}
+catch (outerError) {
+    try {
+        pty = require('../build/Debug/pty.node');
+    }
+    catch (innerError) {
+        console.error('innerError', innerError);
+        // Re-throw the exception from the Release require if the Debug require fails as well
+        throw outerError;
+    }
+}
+var DEFAULT_FILE = 'sh';
+var DEFAULT_NAME = 'xterm';
+var DESTROY_SOCKET_TIMEOUT_MS = 200;
+var UnixTerminal = /** @class */ (function (_super) {
+    __extends(UnixTerminal, _super);
+    function UnixTerminal(file, args, opt) {
+        var _this = _super.call(this, opt) || this;
+        if (typeof args === 'string') {
+            throw new Error('args as a string is not supported on unix.');
+        }
+        // Initialize arguments
+        args = args || [];
+        file = file || DEFAULT_FILE;
+        opt = opt || {};
+        opt.env = opt.env || process.env;
+        _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
+        _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
+        var uid = opt.uid || -1;
+        var gid = opt.gid || -1;
+        var env = utils_1.assign({}, opt.env);
+        if (opt.env === process.env) {
+            _this._sanitizeEnv(env);
+        }
+        var cwd = opt.cwd || process.cwd();
+        var name = opt.name || env.TERM || DEFAULT_NAME;
+        env.TERM = name;
+        var parsedEnv = _this._parseEnv(env);
+        var encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
+        var onexit = function (code, signal) {
+            // XXX Sometimes a data event is emitted after exit. Wait til socket is
+            // destroyed.
+            if (!_this._emittedClose) {
+                if (_this._boundClose) {
+                    return;
+                }
+                _this._boundClose = true;
+                // From macOS High Sierra 10.13.2 sometimes the socket never gets
+                // closed. A timeout is applied here to avoid the terminal never being
+                // destroyed when this occurs.
+                var timeout_1 = setTimeout(function () {
+                    timeout_1 = null;
+                    // Destroying the socket now will cause the close event to fire
+                    _this._socket.destroy();
+                }, DESTROY_SOCKET_TIMEOUT_MS);
+                _this.once('close', function () {
+                    if (timeout_1 !== null) {
+                        clearTimeout(timeout_1);
+                    }
+                    _this.emit('exit', code, signal);
+                });
+                return;
+            }
+            _this.emit('exit', code, signal);
+        };
+        // fork
+        var term = pty.fork(file, args, parsedEnv, cwd, _this._cols, _this._rows, uid, gid, (encoding === 'utf8'), onexit);
+        _this._socket = new PipeSocket(term.fd);
+        if (encoding !== null) {
+            _this._socket.setEncoding(encoding);
+        }
+        // setup
+        _this._socket.on('error', function (err) {
+            // NOTE: fs.ReadStream gets EAGAIN twice at first:
+            if (err.code) {
+                if (~err.code.indexOf('EAGAIN')) {
+                    return;
+                }
+            }
+            // close
+            _this._close();
+            // EIO on exit from fs.ReadStream:
+            if (!_this._emittedClose) {
+                _this._emittedClose = true;
+                _this.emit('close');
+            }
+            // EIO, happens when someone closes our child process: the only process in
+            // the terminal.
+            // node < 0.6.14: errno 5
+            // node >= 0.6.14: read EIO
+            if (err.code) {
+                if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) {
+                    return;
+                }
+            }
+            // throw anything else
+            if (_this.listeners('error').length < 2) {
+                throw err;
+            }
+        });
+        _this._pid = term.pid;
+        _this._fd = term.fd;
+        _this._pty = term.pty;
+        _this._file = file;
+        _this._name = name;
+        _this._readable = true;
+        _this._writable = true;
+        _this._socket.on('close', function () {
+            if (_this._emittedClose) {
+                return;
+            }
+            _this._emittedClose = true;
+            _this._close();
+            _this.emit('close');
+        });
+        _this._forwardEvents();
+        return _this;
+    }
+    Object.defineProperty(UnixTerminal.prototype, "master", {
+        get: function () { return this._master; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(UnixTerminal.prototype, "slave", {
+        get: function () { return this._slave; },
+        enumerable: true,
+        configurable: true
+    });
+    UnixTerminal.prototype._write = function (data) {
+        this._socket.write(data);
+    };
+    /**
+     * openpty
+     */
+    UnixTerminal.open = function (opt) {
+        var self = Object.create(UnixTerminal.prototype);
+        opt = opt || {};
+        if (arguments.length > 1) {
+            opt = {
+                cols: arguments[1],
+                rows: arguments[2]
+            };
+        }
+        var cols = opt.cols || terminal_1.DEFAULT_COLS;
+        var rows = opt.rows || terminal_1.DEFAULT_ROWS;
+        var encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
+        // open
+        var term = pty.open(cols, rows);
+        self._master = new PipeSocket(term.master);
+        if (encoding !== null) {
+            self._master.setEncoding(encoding);
+        }
+        self._master.resume();
+        self._slave = new PipeSocket(term.slave);
+        if (encoding !== null) {
+            self._slave.setEncoding(encoding);
+        }
+        self._slave.resume();
+        self._socket = self._master;
+        self._pid = null;
+        self._fd = term.master;
+        self._pty = term.pty;
+        self._file = process.argv[0] || 'node';
+        self._name = process.env.TERM || '';
+        self._readable = true;
+        self._writable = true;
+        self._socket.on('error', function (err) {
+            self._close();
+            if (self.listeners('error').length < 2) {
+                throw err;
+            }
+        });
+        self._socket.on('close', function () {
+            self._close();
+        });
+        return self;
+    };
+    UnixTerminal.prototype.destroy = function () {
+        var _this = this;
+        this._close();
+        // Need to close the read stream so node stops reading a dead file
+        // descriptor. Then we can safely SIGHUP the shell.
+        this._socket.once('close', function () {
+            _this.kill('SIGHUP');
+        });
+        this._socket.destroy();
+    };
+    UnixTerminal.prototype.kill = function (signal) {
+        try {
+            process.kill(this.pid, signal || 'SIGHUP');
+        }
+        catch (e) { /* swallow */ }
+    };
+    Object.defineProperty(UnixTerminal.prototype, "process", {
+        /**
+         * Gets the name of the process.
+         */
+        get: function () {
+            return pty.process(this._fd, this._pty) || this._file;
+        },
+        enumerable: true,
+        configurable: true
+    });
+    /**
+     * TTY
+     */
+    UnixTerminal.prototype.resize = function (cols, rows) {
+        if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
+            throw new Error('resizing must be done using positive cols and rows');
+        }
+        pty.resize(this._fd, cols, rows);
+        this._cols = cols;
+        this._rows = rows;
+    };
+    UnixTerminal.prototype._sanitizeEnv = function (env) {
+        // Make sure we didn't start our server from inside tmux.
+        delete env['TMUX'];
+        delete env['TMUX_PANE'];
+        // Make sure we didn't start our server from inside screen.
+        // http://web.mit.edu/gnu/doc/html/screen_20.html
+        delete env['STY'];
+        delete env['WINDOW'];
+        // Delete some variables that might confuse our terminal.
+        delete env['WINDOWID'];
+        delete env['TERMCAP'];
+        delete env['COLUMNS'];
+        delete env['LINES'];
+    };
+    return UnixTerminal;
+}(terminal_1.Terminal));
+exports.UnixTerminal = UnixTerminal;
+/**
+ * Wraps net.Socket to force the handle type "PIPE" by temporarily overwriting
+ * tty_wrap.guessHandleType.
+ * See: https://github.com/chjj/pty.js/issues/103
+ */
+var PipeSocket = /** @class */ (function (_super) {
+    __extends(PipeSocket, _super);
+    function PipeSocket(fd) {
+        var _this = this;
+        var _a = process.binding('pipe_wrap'), Pipe = _a.Pipe, constants = _a.constants; // tslint:disable-line
+        // @types/node has fd as string? https://github.com/DefinitelyTyped/DefinitelyTyped/pull/18275
+        var handle = new Pipe(constants.SOCKET);
+        handle.open(fd);
+        _this = _super.call(this, { handle: handle }) || this;
+        return _this;
+    }
+    return PipeSocket;
+}(net.Socket));
+//# sourceMappingURL=unixTerminal.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/unixTerminal.js.map b/node_modules/node-pty/lib/unixTerminal.js.map
new file mode 100644 (file)
index 0000000..3275877
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"unixTerminal.js","sourceRoot":"","sources":["../src/unixTerminal.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA;;;;GAIG;AACH,yBAA2B;AAC3B,uCAAkE;AAGlE,iCAAiC;AAEjC,IAAI,GAAgB,CAAC;AACrB,IAAI;IACF,GAAG,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;CAC5C;AAAC,OAAO,UAAU,EAAE;IACnB,IAAI;QACF,GAAG,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;KAC1C;IAAC,OAAO,UAAU,EAAE;QACnB,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACxC,qFAAqF;QACrF,MAAM,UAAU,CAAC;KAClB;CACF;AAED,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,YAAY,GAAG,OAAO,CAAC;AAC7B,IAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC;IAAkC,gCAAQ;IAkBxC,sBAAY,IAAa,EAAE,IAAwB,EAAE,GAAqB;QAA1E,YACE,kBAAM,GAAG,CAAC,SAqHX;QAnHC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;SAC/D;QAED,uBAAuB;QACvB,IAAI,GAAG,IAAI,I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ACvB,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QACtB,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QACtB,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;IACH,mBAAC;AAAD,CAAC,AA/PD,CAAkC,mBAAQ,GA+PzC;AA/PY,oCAAY;AAiQzB;;;;GAIG;AACH;IAAyB,8BAAU;IACjC,oBAAY,EAAU;QAAtB,iBAMC;QALO,IAAA,iCAAyD,EAAvD,cAAI,EAAE,wBAAiD,CAAC,CAAC,sBAAsB;QACvF,8FAA8F;QAC9F,IAAM,MAAM,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAChB,QAAA,kBAAW,EAAE,MAAM,QAAA,EAAE,CAAC,SAAC;;IACzB,CAAC;IACH,iBAAC;AAAD,CAAC,AARD,CAAyB,GAAG,CAAC,MAAM,GAQlC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/unixTerminal.test.js b/node_modules/node-pty/lib/unixTerminal.test.js
new file mode 100644 (file)
index 0000000..62799e3
--- /dev/null
@@ -0,0 +1,100 @@
+"use strict";
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var unixTerminal_1 = require("./unixTerminal");
+var assert = require("assert");
+var path = require("path");
+var testUtils_test_1 = require("./testUtils.test");
+var FIXTURES_PATH = path.normalize(path.join(__dirname, '..', 'fixtures', 'utf8-character.txt'));
+if (process.platform !== 'win32') {
+    describe('UnixTerminal', function () {
+        describe('Constructor', function () {
+            it('should set a valid pts name', function () {
+                var term = new unixTerminal_1.UnixTerminal('/bin/bash', [], {});
+                var regExp;
+                if (process.platform === 'linux') {
+                    // https://linux.die.net/man/4/pts
+                    regExp = /^\/dev\/pts\/\d+$/;
+                }
+                if (process.platform === 'darwin') {
+                    // https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man4/pty.4.html
+                    regExp = /^\/dev\/tty[p-sP-S][a-z0-9]+$/;
+                }
+                if (regExp) {
+                    assert.ok(regExp.test(term._pty), '"' + term._pty + '" should match ' + regExp.toString());
+                }
+            });
+        });
+        describe('PtyForkEncodingOption', function () {
+            it('should default to utf8', function (done) {
+                var term = new unixTerminal_1.UnixTerminal('/bin/bash', ['-c', "cat \"" + FIXTURES_PATH + "\""]);
+                term.on('data', function (data) {
+                    assert.equal(typeof data, 'string');
+                    assert.equal(data, '\u00E6');
+                    done();
+                });
+            });
+            it('should return a Buffer when encoding is null', function (done) {
+                var term = new unixTerminal_1.UnixTerminal('/bin/bash', ['-c', "cat \"" + FIXTURES_PATH + "\""], {
+                    encoding: null
+                });
+                term.on('data', function (data) {
+                    assert.equal(typeof data, 'object');
+                    assert.ok(data instanceof Buffer);
+                    assert.equal(0xC3, data[0]);
+                    assert.equal(0xA6, data[1]);
+                    done();
+                });
+            });
+            it('should support other encodings', function (done) {
+                var text = 'test æ!';
+                var term = new unixTerminal_1.UnixTerminal(null, ['-c', 'echo "' + text + '"'], {
+                    encoding: 'base64'
+                });
+                var buffer = '';
+                term.on('data', function (data) {
+                    assert.equal(typeof data, 'string');
+                    buffer += data;
+                });
+                term.on('exit', function () {
+                    assert.equal(Buffer.alloc(8, buffer, 'base64').toString().replace('\r', '').replace('\n', ''), text);
+                    done();
+                });
+            });
+        });
+        describe('open', function () {
+            var term;
+            afterEach(function () {
+                if (term) {
+                    term.slave.destroy();
+                    term.master.destroy();
+                }
+            });
+            it('should open a pty with access to a master and slave socket', function (done) {
+                var doneCalled = false;
+                term = unixTerminal_1.UnixTerminal.open({});
+                var slavebuf = '';
+                term.slave.on('data', function (data) {
+                    slavebuf += data;
+                });
+                var masterbuf = '';
+                term.master.on('data', function (data) {
+                    masterbuf += data;
+                });
+                testUtils_test_1.pollUntil(function () {
+                    if (masterbuf === 'slave\r\nmaster\r\n' && slavebuf === 'master\n') {
+                        done();
+                        return true;
+                    }
+                    return false;
+                }, 200, 10);
+                term.slave.write('slave\n');
+                term.master.write('master\n');
+            });
+        });
+    });
+}
+//# sourceMappingURL=unixTerminal.test.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/unixTerminal.test.js.map b/node_modules/node-pty/lib/unixTerminal.test.js.map
new file mode 100644 (file)
index 0000000..8a360ac
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"unixTerminal.test.js","sourceRoot":"","sources":["../src/unixTerminal.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,+CAA8C;AAC9C,+BAAiC;AACjC,2BAA6B;AAC7B,mDAA6C;AAE7C,IAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,EAAE,oBAAoB,CAAC,CAAC,CAAC;AAEnG,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,QAAQ,CAAC,cAAc,EAAE;QACvB,QAAQ,CAAC,aAAa,EAAE;YACtB,EAAE,CAAC,6BAA6B,EAAE;gBAChC,IAAM,IAAI,GAAG,IAAI,2BAAY,CAAC,WAAW,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;gBACnD,IAAI,MAAM,CAAC;gBACX,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;oBAChC,kCAAkC;oBAClC,MAAM,GAAG,mBAAmB,CAAC;iBAC9B;gBACD,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE;oBACjC,qGAAqG;oBACrG,MAAM,GAAG,+BAA+B,CAAC;iBAC1C;gBACD,IAAI,MAAM,EAAE;oBACV,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAO,IAAK,CAAC,IAAI,CAAC,EAAE,GAAG,GAAS,IAAK,CAAC,IAAI,GAAG,iBAAiB,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC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C,CAAC,CAAC;gBAEH,IAAI,SAAS,GAAG,EAAE,CAAC;gBACnB,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBAC1B,SAAS,IAAI,IAAI,CAAC;gBACpB,CAAC,CAAC,CAAC;gBAEH,0BAAS,CAAC;oBACR,IAAI,SAAS,KAAK,qBAAqB,IAAI,QAAQ,KAAK,UAAU,EAAE;wBAClE,IAAI,EAAE,CAAC;wBACP,OAAO,IAAI,CAAC;qBACb;oBACD,OAAO,KAAK,CAAC;gBACf,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;gBAEZ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;gBAC5B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/utils.js b/node_modules/node-pty/lib/utils.js
new file mode 100644 (file)
index 0000000..89639c4
--- /dev/null
@@ -0,0 +1,16 @@
+"use strict";
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+function assign(target) {
+    var sources = [];
+    for (var _i = 1; _i < arguments.length; _i++) {
+        sources[_i - 1] = arguments[_i];
+    }
+    sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return target[key] = source[key]; }); });
+    return target;
+}
+exports.assign = assign;
+//# sourceMappingURL=utils.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/utils.js.map b/node_modules/node-pty/lib/utils.js.map
new file mode 100644 (file)
index 0000000..bd56943
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,SAAgB,MAAM,CAAC,MAAW;IAAE,iBAAiB;SAAjB,UAAiB,EAAjB,qBAAiB,EAAjB,IAAiB;QAAjB,gCAAiB;;IACnD,OAAO,CAAC,OAAO,CAAC,UAAA,MAAM,IAAI,OAAA,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,UAAA,GAAG,IAAI,OAAA,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,EAAzB,CAAyB,CAAC,EAA7D,CAA6D,CAAC,CAAC;IACzF,OAAO,MAAM,CAAC;AAChB,CAAC;AAHD,wBAGC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsPtyAgent.js b/node_modules/node-pty/lib/windowsPtyAgent.js
new file mode 100644 (file)
index 0000000..4ef3fd6
--- /dev/null
@@ -0,0 +1,310 @@
+"use strict";
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var os = require("os");
+var path = require("path");
+var net_1 = require("net");
+var child_process_1 = require("child_process");
+var conptyNative;
+var winptyNative;
+/**
+ * The amount of time to wait for additional data after the conpty shell process has exited before
+ * shutting down the socket. The timer will be reset if a new data event comes in after the timer
+ * has started.
+ */
+var FLUSH_DATA_INTERVAL = 20;
+/**
+ * This agent sits between the WindowsTerminal class and provides a common interface for both conpty
+ * and winpty.
+ */
+var WindowsPtyAgent = /** @class */ (function () {
+    function WindowsPtyAgent(file, args, env, cwd, cols, rows, debug, _useConpty, conptyInheritCursor) {
+        var _this = this;
+        if (conptyInheritCursor === void 0) { conptyInheritCursor = false; }
+        this._useConpty = _useConpty;
+        if (this._useConpty === undefined || this._useConpty === true) {
+            this._useConpty = this._getWindowsBuildNumber() >= 18309;
+        }
+        if (this._useConpty) {
+            if (!conptyNative) {
+                try {
+                    conptyNative = require('../build/Release/conpty.node');
+                }
+                catch (outerError) {
+                    try {
+                        conptyNative = require('../build/Debug/conpty.node');
+                    }
+                    catch (innerError) {
+                        console.error('innerError', innerError);
+                        // Re-throw the exception from the Release require if the Debug require fails as well
+                        throw outerError;
+                    }
+                }
+            }
+        }
+        else {
+            if (!winptyNative) {
+                try {
+                    winptyNative = require('../build/Release/pty.node');
+                }
+                catch (outerError) {
+                    try {
+                        winptyNative = require('../build/Debug/pty.node');
+                    }
+                    catch (innerError) {
+                        console.error('innerError', innerError);
+                        // Re-throw the exception from the Release require if the Debug require fails as well
+                        throw outerError;
+                    }
+                }
+            }
+        }
+        this._ptyNative = this._useConpty ? conptyNative : winptyNative;
+        // Sanitize input variable.
+        cwd = path.resolve(cwd);
+        // Compose command line
+        var commandLine = argsToCommandLine(file, args);
+        // Open pty session.
+        var term;
+        if (this._useConpty) {
+            term = this._ptyNative.startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor);
+        }
+        else {
+            term = this._ptyNative.startProcess(file, commandLine, env, cwd, cols, rows, debug);
+            this._pid = term.pid;
+            this._innerPid = term.innerPid;
+            this._innerPidHandle = term.innerPidHandle;
+        }
+        // Not available on windows.
+        this._fd = term.fd;
+        // Generated incremental number that has no real purpose besides  using it
+        // as a terminal id.
+        this._pty = term.pty;
+        // Create terminal pipe IPC channel and forward to a local unix socket.
+        this._outSocket = new net_1.Socket();
+        this._outSocket.setEncoding('utf8');
+        this._outSocket.connect(term.conout, function () {
+            // TODO: Emit event on agent instead of socket?
+            // Emit ready event.
+            _this._outSocket.emit('ready_datapipe');
+        });
+        this._inSocket = new net_1.Socket();
+        this._inSocket.setEncoding('utf8');
+        this._inSocket.connect(term.conin);
+        // TODO: Wait for ready event?
+        if (this._useConpty) {
+            var connect = this._ptyNative.connect(this._pty, commandLine, cwd, env, function (c) { return _this._$onProcessExit(c); });
+            this._innerPid = connect.pid;
+        }
+    }
+    Object.defineProperty(WindowsPtyAgent.prototype, "inSocket", {
+        get: function () { return this._inSocket; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(WindowsPtyAgent.prototype, "outSocket", {
+        get: function () { return this._outSocket; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(WindowsPtyAgent.prototype, "fd", {
+        get: function () { return this._fd; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(WindowsPtyAgent.prototype, "innerPid", {
+        get: function () { return this._innerPid; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(WindowsPtyAgent.prototype, "pty", {
+        get: function () { return this._pty; },
+        enumerable: true,
+        configurable: true
+    });
+    WindowsPtyAgent.prototype.resize = function (cols, rows) {
+        if (this._useConpty) {
+            if (this._exitCode !== undefined) {
+                throw new Error('Cannot resize a pty that has already exited');
+            }
+            this._ptyNative.resize(this._pty, cols, rows);
+            return;
+        }
+        this._ptyNative.resize(this._pid, cols, rows);
+    };
+    WindowsPtyAgent.prototype.kill = function () {
+        var _this = this;
+        this._inSocket.readable = false;
+        this._inSocket.writable = false;
+        this._outSocket.readable = false;
+        this._outSocket.writable = false;
+        // Tell the agent to kill the pty, this releases handles to the process
+        if (this._useConpty) {
+            this._getConsoleProcessList().then(function (consoleProcessList) {
+                consoleProcessList.forEach(function (pid) {
+                    try {
+                        process.kill(pid);
+                    }
+                    catch (e) {
+                        // Ignore if process cannot be found (kill ESRCH error)
+                    }
+                });
+                _this._ptyNative.kill(_this._pty);
+            });
+        }
+        else {
+            this._ptyNative.kill(this._pid, this._innerPidHandle);
+            // Since pty.kill closes the handle it will kill most processes by itself
+            // and process IDs can be reused as soon as all handles to them are
+            // dropped, we want to immediately kill the entire console process list.
+            // If we do not force kill all processes here, node servers in particular
+            // seem to become detached and remain running (see
+            // Microsoft/vscode#26807).
+            var processList = this._ptyNative.getProcessList(this._pid);
+            processList.forEach(function (pid) {
+                try {
+                    process.kill(pid);
+                }
+                catch (e) {
+                    // Ignore if process cannot be found (kill ESRCH error)
+                }
+            });
+        }
+    };
+    WindowsPtyAgent.prototype._getConsoleProcessList = function () {
+        var _this = this;
+        return new Promise(function (resolve) {
+            var agent = child_process_1.fork(path.join(__dirname, 'conpty_console_list_agent'), [_this._innerPid.toString()]);
+            agent.on('message', function (message) {
+                clearTimeout(timeout);
+                resolve(message.consoleProcessList);
+            });
+            var timeout = setTimeout(function () {
+                // Something went wrong, just send back the shell PID
+                agent.kill();
+                resolve([_this._innerPid]);
+            }, 5000);
+        });
+    };
+    Object.defineProperty(WindowsPtyAgent.prototype, "exitCode", {
+        get: function () {
+            if (this._useConpty) {
+                return this._exitCode;
+            }
+            return this._ptyNative.getExitCode(this._innerPidHandle);
+        },
+        enumerable: true,
+        configurable: true
+    });
+    WindowsPtyAgent.prototype._getWindowsBuildNumber = function () {
+        var osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
+        var buildNumber = 0;
+        if (osVersion && osVersion.length === 4) {
+            buildNumber = parseInt(osVersion[3]);
+        }
+        return buildNumber;
+    };
+    WindowsPtyAgent.prototype._generatePipeName = function () {
+        return "conpty-" + Math.random() * 10000000;
+    };
+    /**
+     * Triggered from the native side when a contpy process exits.
+     */
+    WindowsPtyAgent.prototype._$onProcessExit = function (exitCode) {
+        var _this = this;
+        this._exitCode = exitCode;
+        this._flushDataAndCleanUp();
+        this._outSocket.on('data', function () { return _this._flushDataAndCleanUp(); });
+    };
+    WindowsPtyAgent.prototype._flushDataAndCleanUp = function () {
+        var _this = this;
+        if (this._closeTimeout) {
+            clearTimeout(this._closeTimeout);
+        }
+        this._closeTimeout = setTimeout(function () { return _this._cleanUpProcess(); }, FLUSH_DATA_INTERVAL);
+    };
+    WindowsPtyAgent.prototype._cleanUpProcess = function () {
+        this._inSocket.readable = false;
+        this._inSocket.writable = false;
+        this._outSocket.readable = false;
+        this._outSocket.writable = false;
+        this._outSocket.destroy();
+    };
+    return WindowsPtyAgent;
+}());
+exports.WindowsPtyAgent = WindowsPtyAgent;
+// Convert argc/argv into a Win32 command-line following the escaping convention
+// documented on MSDN (e.g. see CommandLineToArgvW documentation). Copied from
+// winpty project.
+function argsToCommandLine(file, args) {
+    if (isCommandLine(args)) {
+        if (args.length === 0) {
+            return file;
+        }
+        return argsToCommandLine(file, []) + " " + args;
+    }
+    var argv = [file];
+    Array.prototype.push.apply(argv, args);
+    var result = '';
+    for (var argIndex = 0; argIndex < argv.length; argIndex++) {
+        if (argIndex > 0) {
+            result += ' ';
+        }
+        var arg = argv[argIndex];
+        // if it is empty or it contains whitespace and is not already quoted
+        var hasLopsidedEnclosingQuote = xOr((arg[0] !== '"'), (arg[arg.length - 1] !== '"'));
+        var hasNoEnclosingQuotes = ((arg[0] !== '"') && (arg[arg.length - 1] !== '"'));
+        var quote = arg === '' ||
+            (arg.indexOf(' ') !== -1 ||
+                arg.indexOf('\t') !== -1) &&
+                ((arg.length > 1) &&
+                    (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
+        if (quote) {
+            result += '\"';
+        }
+        var bsCount = 0;
+        for (var i = 0; i < arg.length; i++) {
+            var p = arg[i];
+            if (p === '\\') {
+                bsCount++;
+            }
+            else if (p === '"') {
+                result += repeatText('\\', bsCount * 2 + 1);
+                result += '"';
+                bsCount = 0;
+            }
+            else {
+                result += repeatText('\\', bsCount);
+                bsCount = 0;
+                result += p;
+            }
+        }
+        if (quote) {
+            result += repeatText('\\', bsCount * 2);
+            result += '\"';
+        }
+        else {
+            result += repeatText('\\', bsCount);
+        }
+    }
+    return result;
+}
+exports.argsToCommandLine = argsToCommandLine;
+function isCommandLine(args) {
+    return typeof args === 'string';
+}
+function repeatText(text, count) {
+    var result = '';
+    for (var i = 0; i < count; i++) {
+        result += text;
+    }
+    return result;
+}
+function xOr(arg1, arg2) {
+    return ((arg1 && !arg2) || (!arg1 && arg2));
+}
+//# sourceMappingURL=windowsPtyAgent.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsPtyAgent.js.map b/node_modules/node-pty/lib/windowsPtyAgent.js.map
new file mode 100644 (file)
index 0000000..b8d1b05
--- /d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;AAED,SAAS,GAAG,CAAC,IAAa,EAAE,IAAa;IACvC,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC;AAC9C,CAAC"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsPtyAgent.test.js b/node_modules/node-pty/lib/windowsPtyAgent.test.js
new file mode 100644 (file)
index 0000000..15bbf5b
--- /dev/null
@@ -0,0 +1,90 @@
+"use strict";
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var assert = require("assert");
+var windowsPtyAgent_1 = require("./windowsPtyAgent");
+function check(file, args, expected) {
+    assert.equal(windowsPtyAgent_1.argsToCommandLine(file, args), expected);
+}
+if (process.platform === 'win32') {
+    describe('argsToCommandLine', function () {
+        describe('Plain strings', function () {
+            it('doesn\'t quote plain string', function () {
+                check('asdf', [], 'asdf');
+            });
+            it('doesn\'t escape backslashes', function () {
+                check('\\asdf\\qwer\\', [], '\\asdf\\qwer\\');
+            });
+            it('doesn\'t escape multiple backslashes', function () {
+                check('asdf\\\\qwer', [], 'asdf\\\\qwer');
+            });
+            it('adds backslashes before quotes', function () {
+                check('"asdf"qwer"', [], '\\"asdf\\"qwer\\"');
+            });
+            it('escapes backslashes before quotes', function () {
+                check('asdf\\"qwer', [], 'asdf\\\\\\"qwer');
+            });
+        });
+        describe('Quoted strings', function () {
+            it('quotes string with spaces', function () {
+                check('asdf qwer', [], '"asdf qwer"');
+            });
+            it('quotes empty string', function () {
+                check('', [], '""');
+            });
+            it('quotes string with tabs', function () {
+                check('asdf\tqwer', [], '"asdf\tqwer"');
+            });
+            it('escapes only the last backslash', function () {
+                check('\\asdf \\qwer\\', [], '"\\asdf \\qwer\\\\"');
+            });
+            it('doesn\'t escape multiple backslashes', function () {
+                check('asdf \\\\qwer', [], '"asdf \\\\qwer"');
+            });
+            it('escapes backslashes before quotes', function () {
+                check('asdf \\"qwer', [], '"asdf \\\\\\"qwer"');
+            });
+            it('escapes multiple backslashes at the end', function () {
+                check('asdf qwer\\\\', [], '"asdf qwer\\\\\\\\"');
+            });
+        });
+        describe('Multiple arguments', function () {
+            it('joins arguments with spaces', function () {
+                check('asdf', ['qwer zxcv', '', '"'], 'asdf "qwer zxcv" "" \\"');
+            });
+            it('array argument all in quotes', function () {
+                check('asdf', ['"surounded by quotes"'], 'asdf \\"surounded by quotes\\"');
+            });
+            it('array argument quotes in the middle', function () {
+                check('asdf', ['quotes "in the" middle'], 'asdf "quotes \\"in the\\" middle"');
+            });
+            it('array argument quotes near start', function () {
+                check('asdf', ['"quotes" near start'], 'asdf "\\"quotes\\" near start"');
+            });
+            it('array argument quotes near end', function () {
+                check('asdf', ['quotes "near end"'], 'asdf "quotes \\"near end\\""');
+            });
+        });
+        describe('Args as CommandLine', function () {
+            it('should handle empty string', function () {
+                check('file', '', 'file');
+            });
+            it('should not change args', function () {
+                check('file', 'foo bar baz', 'file foo bar baz');
+                check('file', 'foo \\ba"r \baz', 'file foo \\ba"r \baz');
+            });
+        });
+        describe('Real-world cases', function () {
+            it('quotes within quotes', function () {
+                check('cmd.exe', ['/c', 'powershell -noexit -command \'Set-location \"C:\\user\"\''], 'cmd.exe /c "powershell -noexit -command \'Set-location \\\"C:\\user\\"\'"');
+            });
+            it('space within quotes', function () {
+                check('cmd.exe', ['/k', '"C:\\Users\\alros\\Desktop\\test script.bat"'], 'cmd.exe /k \\"C:\\Users\\alros\\Desktop\\test script.bat\\"');
+            });
+        });
+    });
+}
+//# sourceMappingURL=windowsPtyAgent.test.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsPtyAgent.test.js.map b/node_modules/node-pty/lib/windowsPtyAgent.test.js.map
new file mode 100644 (file)
index 0000000..f92251a
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"windowsPtyAgent.test.js","sourceRoot":"","sources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AC;YACH,EAAE,CAAC,gCAAgC,EAAE;gBACnC,KAAK,CAAC,MAAM,EAAE,CAAC,mBAAmB,CAAC,EAAE,8BAA8B,CAAC,CAAC;YACvE,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,qBAAqB,EAAE;YAC9B,EAAE,CAAC,4BAA4B,EAAE;gBAC/B,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,wBAAwB,EAAE;gBAC3B,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,kBAAkB,CAAC,CAAC;gBACjD,KAAK,CAAC,MAAM,EAAE,iBAAiB,EAAE,sBAAsB,CAAC,CAAC;YAC3D,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,kBAAkB,EAAE;YAC3B,EAAE,CAAC,sBAAsB,EAAE;gBACzB,KAAK,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,2DAA2D,CAAC,EAAE,2EAA2E,CAAC,CAAC;YACrK,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,qBAAqB,EAAE;gBACxB,KAAK,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,8CAA8C,CAAC,EAAE,6DAA6D,CAAC,CAAC;YAC1I,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsTerminal.js b/node_modules/node-pty/lib/windowsTerminal.js
new file mode 100644 (file)
index 0000000..0f14f3d
--- /dev/null
@@ -0,0 +1,181 @@
+"use strict";
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+var __extends = (this && this.__extends) || (function () {
+    var extendStatics = function (d, b) {
+        extendStatics = Object.setPrototypeOf ||
+            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+        return extendStatics(d, b);
+    };
+    return function (d, b) {
+        extendStatics(d, b);
+        function __() { this.constructor = d; }
+        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+    };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var terminal_1 = require("./terminal");
+var windowsPtyAgent_1 = require("./windowsPtyAgent");
+var utils_1 = require("./utils");
+var DEFAULT_FILE = 'cmd.exe';
+var DEFAULT_NAME = 'Windows Shell';
+var WindowsTerminal = /** @class */ (function (_super) {
+    __extends(WindowsTerminal, _super);
+    function WindowsTerminal(file, args, opt) {
+        var _this = _super.call(this, opt) || this;
+        // Initialize arguments
+        args = args || [];
+        file = file || DEFAULT_FILE;
+        opt = opt || {};
+        opt.env = opt.env || process.env;
+        if (opt.encoding) {
+            console.warn('Setting encoding on Windows is not supported');
+        }
+        var env = utils_1.assign({}, opt.env);
+        _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
+        _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
+        var cwd = opt.cwd || process.cwd();
+        var name = opt.name || env.TERM || DEFAULT_NAME;
+        var parsedEnv = _this._parseEnv(env);
+        // If the terminal is ready
+        _this._isReady = false;
+        // Functions that need to run after `ready` event is emitted.
+        _this._deferreds = [];
+        // Create new termal.
+        _this._agent = new windowsPtyAgent_1.WindowsPtyAgent(file, args, parsedEnv, cwd, _this._cols, _this._rows, false, opt.useConpty, opt.conptyInheritCursor);
+        _this._socket = _this._agent.outSocket;
+        // Not available until `ready` event emitted.
+        _this._pid = _this._agent.innerPid;
+        _this._fd = _this._agent.fd;
+        _this._pty = _this._agent.pty;
+        // The forked windows terminal is not available until `ready` event is
+        // emitted.
+        _this._socket.on('ready_datapipe', function () {
+            // These events needs to be forwarded.
+            ['connect', 'data', 'end', 'timeout', 'drain'].forEach(function (event) {
+                _this._socket.on(event, function () {
+                    // Wait until the first data event is fired then we can run deferreds.
+                    if (!_this._isReady && event === 'data') {
+                        // Terminal is now ready and we can avoid having to defer method
+                        // calls.
+                        _this._isReady = true;
+                        // Execute all deferred methods
+                        _this._deferreds.forEach(function (fn) {
+                            // NB! In order to ensure that `this` has all its references
+                            // updated any variable that need to be available in `this` before
+                            // the deferred is run has to be declared above this forEach
+                            // statement.
+                            fn.run();
+                        });
+                        // Reset
+                        _this._deferreds = [];
+                    }
+                });
+            });
+            // Shutdown if `error` event is emitted.
+            _this._socket.on('error', function (err) {
+                // Close terminal session.
+                _this._close();
+                // EIO, happens when someone closes our child process: the only process
+                // in the terminal.
+                // node < 0.6.14: errno 5
+                // node >= 0.6.14: read EIO
+                if (err.code) {
+                    if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO'))
+                        return;
+                }
+                // Throw anything else.
+                if (_this.listeners('error').length < 2) {
+                    throw err;
+                }
+            });
+            // Cleanup after the socket is closed.
+            _this._socket.on('close', function () {
+                _this.emit('exit', _this._agent.exitCode);
+                _this._close();
+            });
+        });
+        _this._file = file;
+        _this._name = name;
+        _this._readable = true;
+        _this._writable = true;
+        _this._forwardEvents();
+        return _this;
+    }
+    WindowsTerminal.prototype._write = function (data) {
+        this._defer(this._doWrite, data);
+    };
+    WindowsTerminal.prototype._doWrite = function (data) {
+        this._agent.inSocket.write(data);
+    };
+    /**
+     * openpty
+     */
+    WindowsTerminal.open = function (options) {
+        throw new Error('open() not supported on windows, use Fork() instead.');
+    };
+    /**
+     * TTY
+     */
+    WindowsTerminal.prototype.resize = function (cols, rows) {
+        var _this = this;
+        if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
+            throw new Error('resizing must be done using positive cols and rows');
+        }
+        this._defer(function () {
+            _this._agent.resize(cols, rows);
+            _this._cols = cols;
+            _this._rows = rows;
+        });
+    };
+    WindowsTerminal.prototype.destroy = function () {
+        var _this = this;
+        this._defer(function () {
+            _this.kill();
+        });
+    };
+    WindowsTerminal.prototype.kill = function (signal) {
+        var _this = this;
+        this._defer(function () {
+            if (signal) {
+                throw new Error('Signals not supported on windows.');
+            }
+            _this._close();
+            _this._agent.kill();
+        });
+    };
+    WindowsTerminal.prototype._defer = function (deferredFn, arg) {
+        var _this = this;
+        // If the terminal is ready, execute.
+        if (this._isReady) {
+            deferredFn.call(this, arg);
+            return;
+        }
+        // Queue until terminal is ready.
+        this._deferreds.push({
+            run: function () { return deferredFn.call(_this, arg); }
+        });
+    };
+    Object.defineProperty(WindowsTerminal.prototype, "process", {
+        get: function () { return this._name; },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(WindowsTerminal.prototype, "master", {
+        get: function () { throw new Error('master is not supported on Windows'); },
+        enumerable: true,
+        configurable: true
+    });
+    Object.defineProperty(WindowsTerminal.prototype, "slave", {
+        get: function () { throw new Error('slave is not supported on Windows'); },
+        enumerable: true,
+        configurable: true
+    });
+    return WindowsTerminal;
+}(terminal_1.Terminal));
+exports.WindowsTerminal = WindowsTerminal;
+//# sourceMappingURL=windowsTerminal.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsTerminal.js.map b/node_modules/node-pty/lib/windowsTerminal.js.map
new file mode 100644 (file)
index 0000000..30b49af
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"windowsTerminal.js","sourceRoot":"","sources":["../src/windowsTerminal.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;;;;;;;;;;AAGH,uCAAkE;AAClE,qDAAoD;AAGpD,iCAAiC;AAEjC,IAAM,YAAY,GAAG,SAAS,CAAC;AAC/B,IAAM,YAAY,GAAG,eAAe,CAAC;AAErC;IAAqC,mCAAQ;IAK3C,yBAAY,IAAa,EAAE,IAAwB,EAAE,GAA4B;QAAjF,YACE,kBAAM,GAAG,CAAC,SAmGX;QAjGC,uBAAuB;QACvB,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QA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C,CAAC,CAAC,CAAC,CAAC;;;OAAA;IACtF,sBAAC;AAAD,CAAC,AA1KD,CAAqC,mBAAQ,GA0K5C;AA1KY,0CAAe"}
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsTerminal.test.js b/node_modules/node-pty/lib/windowsTerminal.test.js
new file mode 100644 (file)
index 0000000..1a638e4
--- /dev/null
@@ -0,0 +1,195 @@
+"use strict";
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+var fs = require("fs");
+var assert = require("assert");
+var windowsTerminal_1 = require("./windowsTerminal");
+var path = require("path");
+var psList = require("ps-list");
+function pollForProcessState(desiredState, intervalMs, timeoutMs) {
+    if (intervalMs === void 0) { intervalMs = 100; }
+    if (timeoutMs === void 0) { timeoutMs = 2000; }
+    return new Promise(function (resolve) {
+        var tries = 0;
+        var interval = setInterval(function () {
+            psList({ all: true }).then(function (ps) {
+                var success = true;
+                var pids = Object.keys(desiredState).map(function (k) { return parseInt(k, 10); });
+                pids.forEach(function (pid) {
+                    if (desiredState[pid]) {
+                        if (!ps.some(function (p) { return p.pid === pid; })) {
+                            success = false;
+                        }
+                    }
+                    else {
+                        if (ps.some(function (p) { return p.pid === pid; })) {
+                            success = false;
+                        }
+                    }
+                });
+                if (success) {
+                    clearInterval(interval);
+                    resolve();
+                    return;
+                }
+                tries++;
+                if (tries * intervalMs >= timeoutMs) {
+                    clearInterval(interval);
+                    var processListing = pids.map(function (k) { return k + ": " + desiredState[k]; }).join('\n');
+                    assert.fail("Bad process state, expected:\n" + processListing);
+                    resolve();
+                }
+            });
+        }, intervalMs);
+    });
+}
+function pollForProcessTreeSize(pid, size, intervalMs, timeoutMs) {
+    if (intervalMs === void 0) { intervalMs = 100; }
+    if (timeoutMs === void 0) { timeoutMs = 2000; }
+    return new Promise(function (resolve) {
+        var tries = 0;
+        var interval = setInterval(function () {
+            psList({ all: true }).then(function (ps) {
+                var openList = [];
+                openList.push(ps.filter(function (p) { return p.pid === pid; }).map(function (p) {
+                    return { name: p.name, pid: p.pid };
+                })[0]);
+                var list = [];
+                var _loop_1 = function () {
+                    var current = openList.shift();
+                    ps.filter(function (p) { return p.ppid === current.pid; }).map(function (p) {
+                        return { name: p.name, pid: p.pid };
+                    }).forEach(function (p) { return openList.push(p); });
+                    list.push(current);
+                };
+                while (openList.length) {
+                    _loop_1();
+                }
+                var success = list.length === size;
+                if (success) {
+                    clearInterval(interval);
+                    resolve(list);
+                    return;
+                }
+                tries++;
+                if (tries * intervalMs >= timeoutMs) {
+                    clearInterval(interval);
+                    assert.fail("Bad process state, expected: " + size + ", actual: " + list.length);
+                    resolve();
+                }
+            });
+        }, intervalMs);
+    });
+}
+if (process.platform === 'win32') {
+    describe('WindowsTerminal', function () {
+        describe('kill', function () {
+            it('should not crash parent process', function (done) {
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
+                term.kill();
+                // Add done call to deferred function queue to ensure the kill call has completed
+                term._defer(done);
+            });
+            it('should kill the process tree', function (done) {
+                this.timeout(5000);
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
+                // Start sub-processes
+                term.write('powershell.exe\r');
+                term.write('notepad.exe\r');
+                term.write('node.exe\r');
+                pollForProcessTreeSize(term.pid, 4, 500, 5000).then(function (list) {
+                    assert.equal(list[0].name, 'cmd.exe');
+                    assert.equal(list[1].name, 'powershell.exe');
+                    assert.equal(list[2].name, 'notepad.exe');
+                    assert.equal(list[3].name, 'node.exe');
+                    term.kill();
+                    var desiredState = {};
+                    desiredState[list[0].pid] = false;
+                    desiredState[list[1].pid] = false;
+                    desiredState[list[2].pid] = true;
+                    desiredState[list[3].pid] = false;
+                    pollForProcessState(desiredState).then(function () {
+                        // Kill notepad before done
+                        process.kill(list[2].pid);
+                        done();
+                    });
+                });
+            });
+        });
+        describe('resize', function () {
+            it('should throw a non-native exception when resizing an invalid value', function () {
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
+                assert.throws(function () { return term.resize(-1, -1); });
+                assert.throws(function () { return term.resize(0, 0); });
+                assert.doesNotThrow(function () { return term.resize(1, 1); });
+            });
+            it('should throw an non-native exception when resizing a killed terminal', function (done) {
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', [], {});
+                term._defer(function () {
+                    term.on('exit', function () {
+                        assert.throws(function () { return term.resize(1, 1); });
+                        done();
+                    });
+                    term.destroy();
+                });
+            });
+        });
+        describe('Args as CommandLine', function () {
+            it('should not fail running a file containing a space in the path', function (done) {
+                var spaceFolder = path.resolve(__dirname, '..', 'fixtures', 'space folder');
+                if (!fs.existsSync(spaceFolder)) {
+                    fs.mkdirSync(spaceFolder);
+                }
+                var cmdCopiedPath = path.resolve(spaceFolder, 'cmd.exe');
+                var data = fs.readFileSync(process.env.windir + "\\System32\\cmd.exe");
+                fs.writeFileSync(cmdCopiedPath, data);
+                if (!fs.existsSync(cmdCopiedPath)) {
+                    // Skip test if git bash isn't installed
+                    return;
+                }
+                var term = new windowsTerminal_1.WindowsTerminal(cmdCopiedPath, '/c echo "hello world"', {});
+                var result = '';
+                term.on('data', function (data) {
+                    result += data;
+                });
+                term.on('exit', function () {
+                    assert.ok(result.indexOf('hello world') >= 1);
+                    done();
+                });
+            });
+        });
+        describe('env', function () {
+            it('should set environment variables of the shell', function (done) {
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', '/C echo %FOO%', { env: { FOO: 'BAR' } });
+                var result = '';
+                term.on('data', function (data) {
+                    result += data;
+                });
+                term.on('exit', function () {
+                    assert.ok(result.indexOf('BAR') >= 0);
+                    done();
+                });
+            });
+        });
+        describe('On close', function () {
+            it('should return process zero exit codes', function (done) {
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', '/C exit');
+                term.on('exit', function (code) {
+                    assert.equal(code, 0);
+                    done();
+                });
+            });
+            it('should return process non-zero exit codes', function (done) {
+                var term = new windowsTerminal_1.WindowsTerminal('cmd.exe', '/C exit 2');
+                term.on('exit', function (code) {
+                    assert.equal(code, 2);
+                    done();
+                });
+            });
+        });
+    });
+}
+//# sourceMappingURL=windowsTerminal.test.js.map
\ No newline at end of file
diff --git a/node_modules/node-pty/lib/windowsTerminal.test.js.map b/node_modules/node-pty/lib/windowsTerminal.test.js.map
new file mode 100644 (file)
index 0000000..6eaac58
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"file":"windowsTerminal.test.js","sourceRoot":"","sources":["../src/windowsTerminal.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,uBAAyB;AACzB,+BAAiC;AACjC,qDAAoD;AACpD,2BAA6B;AAC7B,gCAAkC;AAYlC,SAAS,mBAAmB,CAAC,YAA2B,EAAE,UAAwB,EAAE,SAAwB;IAAlD,2BAAA,EAAA,gBAAwB;IAAE,0BAAA,EAAA,gBAAwB;IAC1G,OAAO,IAAI,OAAO,CAAO,UAAA,OAAO;QAC9B,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAM,QAAQ,GAAG,WAAW,CAAC;YAC3B,MAAM,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,UAAA,EAAE;gBAC3B,IAAI,OAAO,GAAG,IAAI,CAAC;gBACnB,IAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,EAAf,CAAe,CAAC,CAAC;gBACjE,IAAI,CAAC,OAAO,CAAC,UAAA,GAAG;oBACd,IAAI,YAAY,CAAC,GAAG,CAAC,EAAE;wBACrB,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,GAAG,KAAK,GAAG,EAAb,CAAa,CAAC,EAAE;4BAChC,OAAO,GAAG,KAAK,CAAC;yBACjB;qBACF;yBAAM;wBACL,IAAI,EAAE,CAAC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H,EAAE,CAAC,2CAA2C,EAAE,UAAC,IAAI;gBACnD,IAAM,IAAI,GAAG,IAAI,iCAAe,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;gBACzD,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,UAAC,IAAI;oBACnB,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;oBACtB,IAAI,EAAE,CAAC;gBACT,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ"}
\ No newline at end of file
diff --git a/node_modules/node-pty/node_modules/nan/CHANGELOG.md b/node_modules/node-pty/node_modules/nan/CHANGELOG.md
new file mode 100644 (file)
index 0000000..7cdfbe7
--- /dev/null
@@ -0,0 +1,529 @@
+# NAN ChangeLog
+
+**Version 2.14.0: current Node 12.2.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1**
+
+### 2.14.0 May 16 2019
+
+  - Feature: Add missing methods to Nan::Maybe<T> (#852) 4e962489fb84a184035b9fa74f245f650249aca6
+
+### 2.13.2 Mar 24 2019
+
+  - Bugfix: remove usage of deprecated `IsNearDeath` (#842) fbaf42252af279c3d867c6b193571f9711c39847
+
+### 2.13.1 Mar 14 2019
+
+  - Bugfix: check V8 version directly instead of inferring from NMV (#840) 12f9df9f393285de8fb4a8cd01478dc4fe3b089d
+
+### 2.13.0 Mar 13 2019
+
+  - Feature: add support for node master (#831) 113c0282072e7ff4f9dfc98b432fd894b798c2c
+
+### 2.12.1 Dec 18 2018
+
+  - Bugfix: Fix build breakage with Node.js 10.0.0-10.9.0. (#833) 625e90e8fef8d39ffa7247250a76a100b2487474
+
+### 2.12.0 Dec 16 2018
+
+  - Bugfix: Add scope.Escape() to Call() (#817) 2e5ed4fc3a8ac80a6ef1f2a55099ab3ac8800dc6
+  - Bugfix: Fix Node.js v10.12.0 deprecation warnings. 509859cc23b1770376b56550a027840a2ce0f73d
+  - Feature: Allow SetWeak() for non-object persistent handles. (#824) e6ef6a48e7e671fe3e4b7dddaa8912a3f8262ecd
+
+### 2.11.1 Sep 29 2018
+
+  - Fix: adapt to V8 7.0 24a22c3b25eeeec2016c6ec239bdd6169e985447
+
+### 2.11.0 Aug 25 2018
+
+  - Removal: remove `FunctionCallbackInfo::Callee` for nodejs `>= 10` 1a56c0a6efd4fac944cb46c30912a8e023bda7d4
+  - Bugfix: Fix `AsyncProgressWorkerBase::WorkProgress` sends invalid data b0c764d1dab11e9f8b37ffb81e2560a4498aad5e
+  - Feature: Introduce `GetCurrentEventLoop` b4911b0bb1f6d47d860e10ec014d941c51efac5e
+  - Feature: Add `NAN_MODULE_WORKER_ENABLED` macro as a replacement for `NAN_MODULE` b058fb047d18a58250e66ae831444441c1f2ac7a
+
+### 2.10.0 Mar 16 2018
+
+  - Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950
+  - Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452
+  - Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b
+  - Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a
+
+### 2.9.2 Feb 22 2018
+
+  - Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b
+
+### 2.9.1 Feb 22 2018
+
+  - Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4
+  - Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2
+
+### 2.9.0 Feb 22 2018
+
+  - Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309
+  - Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o
+  - Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee
+  - Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4
+  - Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606
+  - Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c
+  - Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b
+
+### 2.8.0 Nov 15 2017
+
+  - Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
+  - Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb
+  - Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
+  - Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900
+  - Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
+
+### 2.7.0 Aug 30 2017
+
+  - Feature: Add `Nan::To<v8::Function>()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b
+  - Bugfix: Fix ternary in `Nan::MaybeLocal<T>::FromMaybe<S>()`. 79a26f7d362e756a9524e672a82c3d603b542867
+
+### 2.6.2 Apr 12 2017
+
+  - Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d
+
+### 2.6.1 Apr 6 2017
+
+  - Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51
+
+### 2.6.0 Apr 6 2017
+
+  - Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5
+
+### 2.5.1 Jan 23 2017
+
+  - Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0
+  - Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112
+  - Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50
+
+### 2.5.0 Dec 21 2016
+
+  - Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178
+  - Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018
+
+### 2.4.0 Jul 10 2016
+
+  - Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649
+  - Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0
+  - Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2
+
+### 2.3.5 May 31 2016
+
+  - Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909
+
+### 2.3.4 May 31 2016
+
+  - Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9
+  - Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246
+  - Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc
+  - Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8
+
+### 2.3.3 May 4 2016
+
+  - Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8
+
+### 2.3.2 Apr 27 2016
+
+  - Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52
+
+### 2.3.1 Apr 27 2016
+
+  - Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e
+
+### 2.3.0 Apr 27 2016
+
+  - Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38
+  - Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece
+
+### 2.2.1 Mar 29 2016
+
+  - Bugfix: Use NewFromUnsigned in ReturnValue<T>::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58
+  - Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9
+
+### 2.2.0 Jan 9 2016
+
+  - Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6
+  - Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec
+  - Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9
+  - Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b
+
+### 2.1.0 Oct 8 2015
+
+  - Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c
+  - Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555
+  - Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d
+  - Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b
+  - Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537
+  - Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff
+  - Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f
+
+### 2.0.9 Sep 8 2015
+
+  - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7
+
+### 2.0.8 Aug 28 2015
+
+  - Work around duplicate linking bug in clang 11902da
+
+### 2.0.7 Aug 26 2015
+
+  - Build: Repackage
+
+### 2.0.6 Aug 26 2015
+
+  - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1
+  - Bugfix: Remove unused static std::map instances 525bddc
+  - Bugfix: Make better use of maybe versions of APIs bfba85b
+  - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d
+
+### 2.0.5 Aug 10 2015
+
+  - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1
+  - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d
+
+### 2.0.4 Aug 6 2015
+
+  - Build: Repackage
+
+### 2.0.3 Aug 6 2015
+
+  - Bugfix: Don't use clang++ / g++ syntax extension. 231450e
+
+### 2.0.2 Aug 6 2015
+
+  - Build: Repackage
+
+### 2.0.1 Aug 6 2015
+
+  - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687
+  - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601
+  - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f
+  - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed
+
+### 2.0.0 Jul 31 2015
+
+  - Change: Renamed identifiers with leading underscores       b5932b4
+  - Change: Replaced NanObjectWrapHandle with class NanObjectWrap      464f1e1
+  - Change: Replace NanScope and NanEscpableScope macros with classes  47751c4
+  - Change: Rename NanNewBufferHandle to NanNewBuffer  6745f99
+  - Change: Rename NanBufferUse to NanNewBuffer        3e8b0a5
+  - Change: Rename NanNewBuffer to NanCopyBuffer       d6af78d
+  - Change: Remove Nan prefix from all names   72d1f67
+  - Change: Update Buffer API for new upstream changes d5d3291
+  - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope    21a7a6a
+  - Change: Get rid of Handles  e6c0daf
+  - Feature: Support io.js 3 with V8 4.4
+  - Feature: Introduce NanPersistent   7fed696
+  - Feature: Introduce NanGlobal       4408da1
+  - Feature: Added NanTryCatch 10f1ca4
+  - Feature: Update for V8 v4.3        4b6404a
+  - Feature: Introduce NanNewOneByteString     c543d32
+  - Feature: Introduce namespace Nan   67ed1b1
+  - Removal: Remove NanLocker and NanUnlocker  dd6e401
+  - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9
+  - Removal: Remove NanReturn* macros  d90a25c
+  - Removal: Remove HasInstance        e8f84fe
+
+
+### 1.9.0 Jul 31 2015
+
+  - Feature: Added `NanFatalException` 81d4a2c
+  - Feature: Added more error types 4265f06
+  - Feature: Added dereference and function call operators to NanCallback c4b2ed0
+  - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c
+  - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6
+  - Feature: Added NanErrnoException dd87d9e
+  - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130
+  - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c
+  - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b
+
+### 1.8.4 Apr 26 2015
+
+  - Build: Repackage
+
+### 1.8.3 Apr 26 2015
+
+  - Bugfix: Include missing header 1af8648
+
+### 1.8.2 Apr 23 2015
+
+  - Build: Repackage
+
+### 1.8.1 Apr 23 2015
+
+  - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3
+
+### 1.8.0 Apr 23 2015
+
+  - Feature: Allow primitives with NanReturnValue 2e4475e
+  - Feature: Added comparison operators to NanCallback 55b075e
+  - Feature: Backport thread local storage 15bb7fa
+  - Removal: Remove support for signatures with arguments 8a2069d
+  - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59
+
+### 1.7.0 Feb 28 2015
+
+  - Feature: Made NanCallback::Call accept optional target 8d54da7
+  - Feature: Support atom-shell 0.21 0b7f1bb
+
+### 1.6.2 Feb 6 2015
+
+  - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639
+
+### 1.6.1 Jan 23 2015
+
+  - Build: version bump
+
+### 1.5.3 Jan 23 2015
+
+  - Build: repackage
+
+### 1.6.0 Jan 23 2015
+
+ - Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af
+ - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179
+ - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9
+
+### 1.5.2 Jan 23 2015
+
+  - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4
+  - Bugfix: Readded missing String constructors 18d828f
+  - Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b
+  - Bugfix: Fix uv_work_cb versioning 997e4ae
+  - Bugfix: Add function factory and test 4eca89c
+  - Bugfix: Add object template factory and test cdcb951
+  - Correctness: Lifted an io.js related typedef c9490be
+  - Correctness: Make explicit downcasts of String lengths 00074e6
+  - Windows: Limit the scope of disabled warning C4530 83d7deb
+
+### 1.5.1 Jan 15 2015
+
+  - Build: version bump
+
+### 1.4.3 Jan 15 2015
+
+  - Build: version bump
+
+### 1.4.2 Jan 15 2015
+
+  - Feature: Support io.js 0dbc5e8
+
+### 1.5.0 Jan 14 2015
+
+ - Feature: Support io.js b003843
+ - Correctness: Improved NanNew internals 9cd4f6a
+ - Feature: Implement progress to NanAsyncWorker 8d6a160
+
+### 1.4.1 Nov 8 2014
+
+ - Bugfix: Handle DEBUG definition correctly
+ - Bugfix: Accept int as Boolean
+
+### 1.4.0 Nov 1 2014
+
+ - Feature: Added NAN_GC_CALLBACK 6a5c245
+ - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8
+ - Correctness: Added constness to references in NanHasInstance 02c61cd
+ - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6
+ - Windoze: Shut Visual Studio up when compiling 8d558c1
+ - License: Switch to plain MIT from custom hacked MIT license 11de983
+ - Build: Added test target to Makefile e232e46
+ - Performance: Removed superfluous scope in NanAsyncWorker f4b7821
+ - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208
+ - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450
+
+### 1.3.0 Aug 2 2014
+
+ - Added NanNew<v8::String, std::string>(std::string)
+ - Added NanNew<v8::String, std::string&>(std::string&)
+ - Added NanAsciiString helper class
+ - Added NanUtf8String helper class
+ - Added NanUcs2String helper class
+ - Deprecated NanRawString()
+ - Deprecated NanCString()
+ - Added NanGetIsolateData(v8::Isolate *isolate)
+ - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv)
+ - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv)
+ - Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv)
+ - Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
+ - Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
+ - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value)
+ - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
+
+### 1.2.0 Jun 5 2014
+
+ - Add NanSetPrototypeTemplate
+ - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class,
+     introduced _NanWeakCallbackDispatcher
+ - Removed -Wno-unused-local-typedefs from test builds
+ - Made test builds Windows compatible ('Sleep()')
+
+### 1.1.2 May 28 2014
+
+ - Release to fix more stuff-ups in 1.1.1
+
+### 1.1.1 May 28 2014
+
+ - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0
+
+### 1.1.0 May 25 2014
+
+ - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead
+ - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]),
+     (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*,
+     v8::String::ExternalAsciiStringResource*
+ - Deprecate NanSymbol()
+ - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker
+
+### 1.0.0 May 4 2014
+
+ - Heavy API changes for V8 3.25 / Node 0.11.13
+ - Use cpplint.py
+ - Removed NanInitPersistent
+ - Removed NanPersistentToLocal
+ - Removed NanFromV8String
+ - Removed NanMakeWeak
+ - Removed NanNewLocal
+ - Removed NAN_WEAK_CALLBACK_OBJECT
+ - Removed NAN_WEAK_CALLBACK_DATA
+ - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions
+ - Introduce NanUndefined, NanNull, NanTrue and NanFalse
+ - Introduce NanEscapableScope and NanEscapeScope
+ - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node)
+ - Introduce NanMakeCallback for node::MakeCallback
+ - Introduce NanSetTemplate
+ - Introduce NanGetCurrentContext
+ - Introduce NanCompileScript and NanRunScript
+ - Introduce NanAdjustExternalMemory
+ - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback
+ - Introduce NanGetHeapStatistics
+ - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent()
+
+### 0.8.0 Jan 9 2014
+
+ - NanDispose -> NanDisposePersistent, deprecate NanDispose
+ - Extract _NAN_*_RETURN_TYPE, pull up NAN_*()
+
+### 0.7.1 Jan 9 2014
+
+ - Fixes to work against debug builds of Node
+ - Safer NanPersistentToLocal (avoid reinterpret_cast)
+ - Speed up common NanRawString case by only extracting flattened string when necessary
+
+### 0.7.0 Dec 17 2013
+
+ - New no-arg form of NanCallback() constructor.
+ - NanCallback#Call takes Handle rather than Local
+ - Removed deprecated NanCallback#Run method, use NanCallback#Call instead
+ - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS
+ - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call()
+ - Introduce NanRawString() for char* (or appropriate void*) from v8::String
+     (replacement for NanFromV8String)
+ - Introduce NanCString() for null-terminated char* from v8::String
+
+### 0.6.0 Nov 21 2013
+
+ - Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of
+     v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9
+
+### 0.5.2 Nov 16 2013
+
+ - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public
+
+### 0.5.1 Nov 12 2013
+
+ - Use node::MakeCallback() instead of direct v8::Function::Call()
+
+### 0.5.0 Nov 11 2013
+
+ - Added @TooTallNate as collaborator
+ - New, much simpler, "include_dirs" for binding.gyp
+ - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros
+
+### 0.4.4 Nov 2 2013
+
+ - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+
+
+### 0.4.3 Nov 2 2013
+
+ - Include node_object_wrap.h, removed from node.h for Node 0.11.8.
+
+### 0.4.2 Nov 2 2013
+
+ - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for
+     Node 0.11.8 release.
+
+### 0.4.1 Sep 16 2013
+
+ - Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8
+
+### 0.4.0 Sep 2 2013
+
+ - Added NAN_INLINE and NAN_DEPRECATED and made use of them
+ - Added NanError, NanTypeError and NanRangeError
+ - Cleaned up code
+
+### 0.3.2 Aug 30 2013
+
+ - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent
+     in NanAsyncWorker
+
+### 0.3.1 Aug 20 2013
+
+ - fix "not all control paths return a value" compile warning on some platforms
+
+### 0.3.0 Aug 19 2013
+
+ - Made NAN work with NPM
+ - Lots of fixes to NanFromV8String, pulling in features from new Node core
+ - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API
+ - Added optional error number argument for NanThrowError()
+ - Added NanInitPersistent()
+ - Added NanReturnNull() and NanReturnEmptyString()
+ - Added NanLocker and NanUnlocker
+ - Added missing scopes
+ - Made sure to clear disposed Persistent handles
+ - Changed NanAsyncWorker to allocate error messages on the heap
+ - Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>)
+ - Fixed leak in NanAsyncWorker when errmsg is used
+
+### 0.2.2 Aug 5 2013
+
+ - Fixed usage of undefined variable with node::BASE64 in NanFromV8String()
+
+### 0.2.1 Aug 5 2013
+
+ - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for
+     NanFromV8String()
+
+### 0.2.0 Aug 5 2013
+
+ - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR,
+     NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY
+ - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS,
+     _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS,
+     _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS,
+     _NAN_PROPERTY_QUERY_ARGS
+ - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer
+ - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT,
+     NAN_WEAK_CALLBACK_DATA, NanMakeWeak
+ - Renamed THROW_ERROR to _NAN_THROW_ERROR
+ - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*)
+ - Added NanBufferUse(char*, uint32_t)
+ - Added NanNewContextHandle(v8::ExtensionConfiguration*,
+       v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>)
+ - Fixed broken NanCallback#GetFunction()
+ - Added optional encoding and size arguments to NanFromV8String()
+ - Added NanGetPointerSafe() and NanSetPointerSafe()
+ - Added initial test suite (to be expanded)
+ - Allow NanUInt32OptionValue to convert any Number object
+
+### 0.1.0 Jul 21 2013
+
+ - Added `NAN_GETTER`, `NAN_SETTER`
+ - Added `NanThrowError` with single Local<Value> argument
+ - Added `NanNewBufferHandle` with single uint32_t argument
+ - Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)`
+ - Added `Local<Function> NanCallback#GetFunction()`
+ - Added `NanCallback#Call(int, Local<Value>[])`
+ - Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call
diff --git a/node_modules/node-pty/node_modules/nan/LICENSE.md b/node_modules/node-pty/node_modules/nan/LICENSE.md
new file mode 100644 (file)
index 0000000..dddd13d
--- /dev/null
@@ -0,0 +1,13 @@
+The MIT License (MIT)
+=====================
+
+Copyright (c) 2018 NAN contributors
+-----------------------------------
+
+*NAN contributors listed at <https://github.com/nodejs/nan#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.
diff --git a/node_modules/node-pty/node_modules/nan/README.md b/node_modules/node-pty/node_modules/nan/README.md
new file mode 100644 (file)
index 0000000..3389ef5
--- /dev/null
@@ -0,0 +1,456 @@
+Native Abstractions for Node.js
+===============================
+
+**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 and 12.**
+
+***Current version: 2.14.0***
+
+*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
+
+[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/)
+
+[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](https://travis-ci.org/nodejs/nan)
+[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan)
+
+Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
+
+This project also contains some helper utilities that make addon development a bit more pleasant.
+
+ * **[News & Updates](#news)**
+ * **[Usage](#usage)**
+ * **[Example](#example)**
+ * **[API](#api)**
+ * **[Tests](#tests)**
+ * **[Known issues](#issues)**
+ * **[Governance & Contributing](#governance)**
+
+<a name="news"></a>
+
+## News & Updates
+
+<a name="usage"></a>
+
+## Usage
+
+Simply add **NAN** as a dependency in the *package.json* of your Node addon:
+
+``` bash
+$ npm install --save nan
+```
+
+Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
+
+``` python
+"include_dirs" : [
+    "<!(node -e \"require('nan')\")"
+]
+```
+
+This works like a `-I<path-to-NAN>` when compiling your addon.
+
+<a name="example"></a>
+
+## Example
+
+Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**.
+
+Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
+
+For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
+
+Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
+
+Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure.
+
+<a name="api"></a>
+
+## API
+
+Additional to the NAN documentation below, please consult:
+
+* [The V8 Getting Started * Guide](https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding)
+* [The V8 Embedders * Guide](https://github.com/v8/v8/wiki/Embedder%27s%20Guide)
+* [V8 API Documentation](https://v8docs.nodesource.com/)
+* [Node Add-on Documentation](https://nodejs.org/api/addons.html)
+
+<!-- START API -->
+
+### JavaScript-accessible methods
+
+A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
+
+In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
+
+* **Method argument types**
+ - <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
+ - <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
+ - <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
+* **Method declarations**
+ - <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
+ - <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
+ - <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
+ - <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
+ - <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
+ - <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
+* Method and template helpers
+ - <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
+ - <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
+
+### Scopes
+
+A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
+
+A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
+
+The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
+
+ - <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
+ - <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
+
+Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
+
+### Persistent references
+
+An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
+
+Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
+
+ - <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
+ - <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
+ - <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
+ - <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
+ - <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
+ - <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
+ - <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
+
+Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
+
+### New
+
+NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
+
+ - <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
+ - <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
+ - <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
+ - <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
+ - <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
+ - <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
+
+
+### Converters
+
+NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
+
+ - <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
+
+### Maybe Types
+
+The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
+
+* **Maybe Types**
+  - <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
+* **Maybe Helpers**
+  - <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
+  - <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
+  - <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
+
+### Script
+
+NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
+
+ - <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
+ - <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
+
+
+### JSON
+
+The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
+
+ - <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
+ - <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
+
+Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
+
+### Errors
+
+NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
+
+Note that an Error object is simply a specialized form of `v8::Value`.
+
+Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
+
+ - <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
+ - <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
+ - <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
+ - <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
+ - <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
+
+
+### Buffers
+
+NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
+
+ - <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
+ - <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
+ - <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
+
+### Nan::Callback
+
+`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
+
+ - <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
+
+### Asynchronous work helpers
+
+`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
+
+ - <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
+ - <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
+ - <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
+ - <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
+
+### Strings & Bytes
+
+Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
+
+ - <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
+ - <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
+ - <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
+ - <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
+
+
+### Object Wrappers
+
+The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
+
+ - <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
+
+
+### V8 internals
+
+The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
+
+ - <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
+ - <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
+
+
+### Miscellaneous V8 Helpers
+
+ - <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
+ - <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
+ - <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
+ - <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
+ - <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
+
+
+### Miscellaneous Node Helpers
+
+ - <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
+ - <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
+ - <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
+ - <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
+
+<!-- END API -->
+
+
+<a name="tests"></a>
+
+### Tests
+
+To run the NAN tests do:
+
+``` sh
+npm install
+npm run-script rebuild-tests
+npm test
+```
+
+Or just:
+
+``` sh
+npm install
+make test
+```
+
+<a name="issues"></a>
+
+## Known issues
+
+### Compiling against Node.js 0.12 on OSX
+
+With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12
+do not compile anymore. The error looks something like:
+
+```
+❯   CXX(target) Release/obj.target/accessors/cpp/accessors.o
+In file included from ../cpp/accessors.cpp:9:
+In file included from ../../nan.h:51:
+In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61:
+/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope'
+  return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
+                                        ~~~~~~~~~~~~~^~~~~~~~~~~~
+```
+
+This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make
+`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore
+this patch cannot be released by either project in an official release.
+
+For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support
+that configuration, you will need to either get an older compiler, or apply a source patch to the version
+of V8 headers as a workaround.
+
+<a name="governance"></a>
+
+## Governance & Contributing
+
+NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api)
+
+### Addon API Working Group (WG)
+
+The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
+
+Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects.
+
+The WG has final authority over this project including:
+
+* Technical direction
+* Project governance and process (including this policy)
+* Contribution policy
+* GitHub repository hosting
+* Maintaining the list of additional Collaborators
+
+For the current list of WG members, see the project [README.md](./README.md#collaborators).
+
+Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
+
+_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
+
+For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
+
+### Consensus Seeking Process
+
+The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
+
+Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
+
+If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
+
+<a id="developers-certificate-of-origin"></a>
+
+## Developer's Certificate of Origin 1.1
+
+By making a contribution to this project, I certify that:
+
+* (a) The contribution was created in whole or in part by me and I
+  have the right to submit it under the open source license
+  indicated in the file; or
+
+* (b) The contribution is based upon previous work that, to the best
+  of my knowledge, is covered under an appropriate open source
+  license and I have the right under that license to submit that
+  work with modifications, whether created in whole or in part
+  by me, under the same open source license (unless I am
+  permitted to submit under a different license), as indicated
+  in the file; or
+
+* (c) The contribution was provided directly to me by some other
+  person who certified (a), (b) or (c) and I have not modified
+  it.
+
+* (d) I understand and agree that this project and the contribution
+  are public and that a record of the contribution (including all
+  personal information I submit with it, including my sign-off) is
+  maintained indefinitely and may be redistributed consistent with
+  this project or the open source license(s) involved.
+
+<a name="collaborators"></a>
+
+### WG Members / Collaborators
+
+<table><tbody>
+<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
+<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
+<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
+<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
+<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
+<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
+<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr>
+<tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr>
+</tbody></table>
+
+## Licence &amp; copyright
+
+Copyright (c) 2018 NAN WG Members / Collaborators (listed above).
+
+Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
diff --git a/node_modules/node-pty/node_modules/nan/doc/asyncworker.md b/node_modules/node-pty/node_modules/nan/doc/asyncworker.md
new file mode 100644 (file)
index 0000000..04231f8
--- /dev/null
@@ -0,0 +1,146 @@
+## Asynchronous work helpers
+
+`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
+
+ - <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
+ - <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
+ - <a href="#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
+ - <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
+
+<a name="api_nan_async_worker"></a>
+### Nan::AsyncWorker
+
+`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress.
+
+This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the
+correct async context. To be able to identify the async resources created by this class in async-hooks, provide a
+`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid
+collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation.  The `resource_name` needs to stay valid for the lifetime of the worker instance.
+
+Definition:
+
+```c++
+class AsyncWorker {
+ public:
+  explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker");
+
+  virtual ~AsyncWorker();
+
+  virtual void WorkComplete();
+
+  void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value);
+
+  void SaveToPersistent(const v8::Local<v8::String> &key,
+                        const v8::Local<v8::Value> &value);
+
+  void SaveToPersistent(uint32_t index,
+                        const v8::Local<v8::Value> &value);
+
+  v8::Local<v8::Value> GetFromPersistent(const char *key) const;
+
+  v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const;
+
+  v8::Local<v8::Value> GetFromPersistent(uint32_t index) const;
+
+  virtual void Execute() = 0;
+
+  uv_work_t request;
+
+  virtual void Destroy();
+
+ protected:
+  Persistent<v8::Object> persistentHandle;
+
+  Callback *callback;
+
+  virtual void HandleOKCallback();
+
+  virtual void HandleErrorCallback();
+
+  void SetErrorMessage(const char *msg);
+
+  const char* ErrorMessage();
+};
+```
+
+<a name="api_nan_async_progress_worker"></a>
+### Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker
+
+`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
+
+Previously the definition of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `<char>` for compatibility.
+
+`Nan::AsyncProgressWorkerBase` &amp; `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar.  The last event sent before the main thread is woken will be delivered.
+
+Definition:
+
+```c++
+template<class T>
+class AsyncProgressWorkerBase<T> : public AsyncWorker {
+ public:
+  explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...);
+
+  virtual ~AsyncProgressWorkerBase();
+
+  void WorkProgress();
+
+  class ExecutionProgress {
+   public:
+    void Signal() const;
+    void Send(const T* data, size_t count) const;
+  };
+
+  virtual void Execute(const ExecutionProgress& progress) = 0;
+
+  virtual void HandleProgressCallback(const T *data, size_t count) = 0;
+
+  virtual void Destroy();
+};
+
+typedef AsyncProgressWorkerBase<T> AsyncProgressWorker;
+```
+
+<a name="api_nan_async_progress_queue_worker"></a>
+### Nan::AsyncProgressQueueWorker
+
+`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
+
+`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread.
+
+Definition:
+
+```c++
+template<class T>
+class AsyncProgressQueueWorker<T> : public AsyncWorker {
+ public:
+  explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker");
+
+  virtual ~AsyncProgressQueueWorker();
+
+  void WorkProgress();
+
+  class ExecutionProgress {
+   public:
+    void Send(const T* data, size_t count) const;
+  };
+
+  virtual void Execute(const ExecutionProgress& progress) = 0;
+
+  virtual void HandleProgressCallback(const T *data, size_t count) = 0;
+
+  virtual void Destroy();
+};
+```
+
+<a name="api_nan_async_queue_worker"></a>
+### Nan::AsyncQueueWorker
+
+`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`.
+
+Definition:
+
+```c++
+void AsyncQueueWorker(AsyncWorker *);
+```
+
+[AsyncResource]: node_misc.md#api_nan_asyncresource
diff --git a/node_modules/node-pty/node_modules/nan/doc/buffers.md b/node_modules/node-pty/node_modules/nan/doc/buffers.md
new file mode 100644 (file)
index 0000000..8d8d25c
--- /dev/null
@@ -0,0 +1,54 @@
+## Buffers
+
+NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
+
+ - <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
+ - <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
+ - <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
+
+<a name="api_nan_new_buffer"></a>
+### Nan::NewBuffer()
+
+Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`.
+
+Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management.
+When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`.
+You _must not_ free the memory space manually once you have created a `Buffer` in this way.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size)
+Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size)
+Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data,
+                                           size_t length,
+                                           Nan::FreeCallback callback,
+                                           void *hint)
+```
+
+
+<a name="api_nan_copy_buffer"></a>
+### Nan::CopyBuffer()
+
+Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`.
+
+Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size)
+```
+
+
+<a name="api_nan_free_callback"></a>
+### Nan::FreeCallback()
+
+A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer).
+The supplied callback will be invoked when the `Buffer` undergoes garbage collection.
+
+Signature:
+
+```c++
+typedef void (*FreeCallback)(char *data, void *hint);
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/callback.md b/node_modules/node-pty/node_modules/nan/doc/callback.md
new file mode 100644 (file)
index 0000000..f7af0bf
--- /dev/null
@@ -0,0 +1,76 @@
+## Nan::Callback
+
+`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
+
+ - <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a>
+
+<a name="api_nan_callback"></a>
+### Nan::Callback
+
+```c++
+class Callback {
+ public:
+  Callback();
+
+  explicit Callback(const v8::Local<v8::Function> &fn);
+
+  ~Callback();
+
+  bool operator==(const Callback &other) const;
+
+  bool operator!=(const Callback &other) const;
+
+  v8::Local<v8::Function> operator*() const;
+
+  MaybeLocal<v8::Value> operator()(AsyncResource* async_resource,
+                                   v8::Local<v8::Object> target,
+                                   int argc = 0,
+                                   v8::Local<v8::Value> argv[] = 0) const;
+
+  MaybeLocal<v8::Value> operator()(AsyncResource* async_resource,
+                                   int argc = 0,
+                                   v8::Local<v8::Value> argv[] = 0) const;
+
+  void SetFunction(const v8::Local<v8::Function> &fn);
+
+  v8::Local<v8::Function> GetFunction() const;
+
+  bool IsEmpty() const;
+
+  void Reset(const v8::Local<v8::Function> &fn);
+
+  void Reset();
+
+  MaybeLocal<v8::Value> Call(v8::Local<v8::Object> target,
+                            int argc,
+                            v8::Local<v8::Value> argv[],
+                            AsyncResource* async_resource) const;
+  MaybeLocal<v8::Value> Call(int argc,
+                             v8::Local<v8::Value> argv[],
+                             AsyncResource* async_resource) const;
+
+  // Deprecated versions. Use the versions that accept an async_resource instead
+  // as they run the callback in the correct async context as specified by the
+  // resource. If you want to call a synchronous JS function (i.e. on a
+  // non-empty JS stack), you can use Nan::Call instead.
+  v8::Local<v8::Value> operator()(v8::Local<v8::Object> target,
+                                  int argc = 0,
+                                  v8::Local<v8::Value> argv[] = 0) const;
+
+  v8::Local<v8::Value> operator()(int argc = 0,
+                                  v8::Local<v8::Value> argv[] = 0) const;
+  v8::Local<v8::Value> Call(v8::Local<v8::Object> target,
+                            int argc,
+                            v8::Local<v8::Value> argv[]) const;
+
+  v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const;
+};
+```
+
+Example usage:
+
+```c++
+v8::Local<v8::Function> function;
+Nan::Callback callback(function);
+callback.Call(0, 0);
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/converters.md b/node_modules/node-pty/node_modules/nan/doc/converters.md
new file mode 100644 (file)
index 0000000..d20861b
--- /dev/null
@@ -0,0 +1,41 @@
+## Converters
+
+NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
+
+ - <a href="#api_nan_to"><b><code>Nan::To()</code></b></a>
+
+<a name="api_nan_to"></a>
+### Nan::To()
+
+Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly.
+
+See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types.
+
+Signatures:
+
+```c++
+// V8 types
+Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val);
+Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val);
+Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val);
+Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val);
+Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val);
+Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val);
+Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val);
+
+// Native types
+Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val);
+Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val);
+Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val);
+Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val);
+Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val);
+```
+
+### Example
+
+```c++
+v8::Local<v8::Value> val;
+Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val);
+Nan::Maybe<double> d = Nan::To<double>(val);
+```
+
diff --git a/node_modules/node-pty/node_modules/nan/doc/errors.md b/node_modules/node-pty/node_modules/nan/doc/errors.md
new file mode 100644 (file)
index 0000000..8127a54
--- /dev/null
@@ -0,0 +1,226 @@
+## Errors
+
+NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
+
+Note that an Error object is simply a specialized form of `v8::Value`.
+
+Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
+
+ - <a href="#api_nan_error"><b><code>Nan::Error()</code></b></a>
+ - <a href="#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
+ - <a href="#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
+ - <a href="#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
+ - <a href="#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
+ - <a href="#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
+ - <a href="#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
+ - <a href="#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
+ - <a href="#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
+ - <a href="#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
+ - <a href="#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
+ - <a href="#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
+ - <a href="#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
+
+
+<a name="api_nan_error"></a>
+### Nan::Error()
+
+Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
+
+Note that an Error object is simply a specialized form of `v8::Value`.
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::Error(const char *msg);
+v8::Local<v8::Value> Nan::Error(v8::Local<v8::String> msg);
+```
+
+
+<a name="api_nan_range_error"></a>
+### Nan::RangeError()
+
+Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
+
+Note that an RangeError object is simply a specialized form of `v8::Value`.
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::RangeError(const char *msg);
+v8::Local<v8::Value> Nan::RangeError(v8::Local<v8::String> msg);
+```
+
+
+<a name="api_nan_reference_error"></a>
+### Nan::ReferenceError()
+
+Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
+
+Note that an ReferenceError object is simply a specialized form of `v8::Value`.
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::ReferenceError(const char *msg);
+v8::Local<v8::Value> Nan::ReferenceError(v8::Local<v8::String> msg);
+```
+
+
+<a name="api_nan_syntax_error"></a>
+### Nan::SyntaxError()
+
+Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
+
+Note that an SyntaxError object is simply a specialized form of `v8::Value`.
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::SyntaxError(const char *msg);
+v8::Local<v8::Value> Nan::SyntaxError(v8::Local<v8::String> msg);
+```
+
+
+<a name="api_nan_type_error"></a>
+### Nan::TypeError()
+
+Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.11/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
+
+Note that an TypeError object is simply a specialized form of `v8::Value`.
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::TypeError(const char *msg);
+v8::Local<v8::Value> Nan::TypeError(v8::Local<v8::String> msg);
+```
+
+
+<a name="api_nan_throw_error"></a>
+### Nan::ThrowError()
+
+Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created.
+
+Signature:
+
+```c++
+void Nan::ThrowError(const char *msg);
+void Nan::ThrowError(v8::Local<v8::String> msg);
+void Nan::ThrowError(v8::Local<v8::Value> error);
+```
+
+
+<a name="api_nan_throw_range_error"></a>
+### Nan::ThrowRangeError()
+
+Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created.
+
+Signature:
+
+```c++
+void Nan::ThrowRangeError(const char *msg);
+void Nan::ThrowRangeError(v8::Local<v8::String> msg);
+void Nan::ThrowRangeError(v8::Local<v8::Value> error);
+```
+
+
+<a name="api_nan_throw_reference_error"></a>
+### Nan::ThrowReferenceError()
+
+Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created.
+
+Signature:
+
+```c++
+void Nan::ThrowReferenceError(const char *msg);
+void Nan::ThrowReferenceError(v8::Local<v8::String> msg);
+void Nan::ThrowReferenceError(v8::Local<v8::Value> error);
+```
+
+
+<a name="api_nan_throw_syntax_error"></a>
+### Nan::ThrowSyntaxError()
+
+Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created.
+
+Signature:
+
+```c++
+void Nan::ThrowSyntaxError(const char *msg);
+void Nan::ThrowSyntaxError(v8::Local<v8::String> msg);
+void Nan::ThrowSyntaxError(v8::Local<v8::Value> error);
+```
+
+
+<a name="api_nan_throw_type_error"></a>
+### Nan::ThrowTypeError()
+
+Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created.
+
+Signature:
+
+```c++
+void Nan::ThrowTypeError(const char *msg);
+void Nan::ThrowTypeError(v8::Local<v8::String> msg);
+void Nan::ThrowTypeError(v8::Local<v8::Value> error);
+```
+
+<a name="api_nan_fatal_exception"></a>
+### Nan::FatalException()
+
+Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch).
+
+Signature:
+
+```c++
+void Nan::FatalException(const Nan::TryCatch& try_catch);
+```
+
+<a name="api_nan_errno_exception"></a>
+### Nan::ErrnoException()
+
+Replaces `node::ErrnoException()` which has a different API across supported versions of Node. 
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::ErrnoException(int errorno,
+                                         const char* syscall = NULL,
+                                         const char* message = NULL,
+                                         const char* path = NULL);
+```
+
+
+<a name="api_nan_try_catch"></a>
+### Nan::TryCatch
+
+A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/node-8.11/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`.
+
+Signature:
+
+```c++
+class Nan::TryCatch {
+ public:
+  Nan::TryCatch();
+
+  bool HasCaught() const;
+
+  bool CanContinue() const;
+
+  v8::Local<v8::Value> ReThrow();
+
+  v8::Local<v8::Value> Exception() const;
+
+  // Nan::MaybeLocal for older versions of V8
+  v8::MaybeLocal<v8::Value> StackTrace() const;
+
+  v8::Local<v8::Message> Message() const;
+
+  void Reset();
+
+  void SetVerbose(bool value);
+
+  void SetCaptureMessage(bool value);
+};
+```
+
diff --git a/node_modules/node-pty/node_modules/nan/doc/json.md b/node_modules/node-pty/node_modules/nan/doc/json.md
new file mode 100644 (file)
index 0000000..4fa78db
--- /dev/null
@@ -0,0 +1,62 @@
+## JSON
+
+The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
+
+ - <a href="#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
+ - <a href="#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
+
+Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
+
+<a name="api_nan_json_parse"></a>
+
+### Nan::JSON.Parse
+
+A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504).
+
+Definition:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::JSON::Parse(v8::Local<v8::String> json_string);
+```
+
+Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`.
+
+Example:
+
+```c++
+v8::Local<v8::String> json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked();
+
+Nan::JSON NanJSON;
+Nan::MaybeLocal<v8::Value> result = NanJSON.Parse(json_string);
+if (!result.IsEmpty()) {
+  v8::Local<v8::Value> val = result.ToLocalChecked();
+}
+```
+
+<a name="api_nan_json_stringify"></a>
+
+### Nan::JSON.Stringify
+
+A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860).
+
+Definition:
+
+```c++
+Nan::MaybeLocal<v8::String> Nan::JSON::Stringify(v8::Local<v8::Object> json_object, v8::Local<v8::String> gap = v8::Local<v8::String>());
+```
+
+Use `JSON.Stringify(value)` to stringify a `v8::Object`.
+
+Example:
+
+```c++
+// using `v8::Local<v8::Value> val` from the `JSON::Parse` example
+v8::Local<v8::Object> obj = Nan::To<v8::Object>(val).ToLocalChecked();
+
+Nan::JSON NanJSON;
+Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj);
+if (!result.IsEmpty()) {
+  v8::Local<v8::String> stringified = result.ToLocalChecked();
+}
+```
+
diff --git a/node_modules/node-pty/node_modules/nan/doc/maybe_types.md b/node_modules/node-pty/node_modules/nan/doc/maybe_types.md
new file mode 100644 (file)
index 0000000..1a9fabf
--- /dev/null
@@ -0,0 +1,583 @@
+## Maybe Types
+
+The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
+
+* **Maybe Types**
+  - <a href="#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
+  - <a href="#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
+  - <a href="#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
+  - <a href="#api_nan_just"><b><code>Nan::Just</code></b></a>
+* **Maybe Helpers**
+  - <a href="#api_nan_call"><b><code>Nan::Call()</code></b></a>
+  - <a href="#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
+  - <a href="#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
+  - <a href="#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
+  - <a href="#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
+  - <a href="#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
+  - <a href="#api_nan_set"><b><code>Nan::Set()</code></b></a>
+  - <a href="#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
+  - <a href="#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
+  - <a href="#api_nan_get"><b><code>Nan::Get()</code></b></a>
+  - <a href="#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
+  - <a href="#api_nan_has"><b><code>Nan::Has()</code></b></a>
+  - <a href="#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
+  - <a href="#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
+  - <a href="#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
+  - <a href="#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
+  - <a href="#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
+  - <a href="#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
+  - <a href="#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
+  - <a href="#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
+  - <a href="#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
+  - <a href="#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
+  - <a href="#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
+  - <a href="#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
+  - <a href="#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
+  - <a href="#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
+  - <a href="#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
+  - <a href="#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
+  - <a href="#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
+  - <a href="#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
+  - <a href="#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
+  - <a href="#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
+  - <a href="#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
+  - <a href="#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
+  - <a href="#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
+
+<a name="api_nan_maybe_local"></a>
+### Nan::MaybeLocal
+
+A `Nan::MaybeLocal<T>` is a wrapper around [`v8::Local<T>`](https://v8docs.nodesource.com/node-8.11/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local<T>` is empty before it can be used.
+
+If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned.
+
+Definition:
+
+```c++
+template<typename T> class Nan::MaybeLocal {
+ public:
+  MaybeLocal();
+
+  template<typename S> MaybeLocal(v8::Local<S> that);
+
+  bool IsEmpty() const;
+
+  template<typename S> bool ToLocal(v8::Local<S> *out);
+
+  // Will crash if the MaybeLocal<> is empty.
+  v8::Local<T> ToLocalChecked();
+
+  template<typename S> v8::Local<S> FromMaybe(v8::Local<S> default_value) const;
+};
+```
+
+See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/node-8.11/d8/d7d/classv8_1_1_maybe_local.html) for further details.
+
+<a name="api_nan_maybe"></a>
+### Nan::Maybe
+
+A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
+
+If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned.
+
+Definition:
+
+```c++
+template<typename T> class Nan::Maybe {
+ public:
+  bool IsNothing() const;
+  bool IsJust() const;
+
+  // Will crash if the Maybe<> is nothing.
+  T FromJust();
+
+  T FromMaybe(const T& default_value);
+
+  bool operator==(const Maybe &other);
+
+  bool operator!=(const Maybe &other);
+};
+```
+
+See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/node-8.11/d9/d4b/classv8_1_1_maybe.html) for further details.
+
+<a name="api_nan_nothing"></a>
+### Nan::Nothing
+
+Construct an empty `Nan::Maybe` type representing _nothing_.
+
+```c++
+template<typename T> Nan::Maybe<T> Nan::Nothing();
+```
+
+<a name="api_nan_just"></a>
+### Nan::Just
+
+Construct a `Nan::Maybe` type representing _just_ a value.
+
+```c++
+template<typename T> Nan::Maybe<T> Nan::Just(const T &t);
+```
+
+<a name="api_nan_call"></a>
+### Nan::Call()
+
+A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/node-8.11/d5/d54/classv8_1_1_function.html#a9c3d0e4e13ddd7721fce238aa5b94a11) in a way compatible across supported versions of V8.
+
+For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::Call(v8::Local<v8::Function> fun, v8::Local<v8::Object> recv, int argc, v8::Local<v8::Value> argv[]);
+Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, v8::Local<v8::Object> recv,
+ int argc, v8::Local<v8::Value> argv[]);
+Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, int argc, v8::Local<v8::Value> argv[]);
+```
+
+
+<a name="api_nan_to_detail_string"></a>
+### Nan::ToDetailString()
+
+A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/node-8.11/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::String> Nan::ToDetailString(v8::Local<v8::Value> val);
+```
+
+
+<a name="api_nan_to_array_index"></a>
+### Nan::ToArrayIndex()
+
+A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/node-8.11/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Uint32> Nan::ToArrayIndex(v8::Local<v8::Value> val);
+```
+
+
+<a name="api_nan_equals"></a>
+### Nan::Equals()
+
+A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/node-8.11/dc/d0a/classv8_1_1_value.html#a08fba1d776a59bbf6864b25f9152c64b) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b));
+```
+
+
+<a name="api_nan_new_instance"></a>
+### Nan::NewInstance()
+
+A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/node-8.11/d5/d54/classv8_1_1_function.html#ae477558b10c14b76ed00e8dbab44ce5b) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h);
+Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h, int argc, v8::Local<v8::Value> argv[]);
+Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::ObjectTemplate> h);
+```
+
+
+<a name="api_nan_get_function"></a>
+### Nan::GetFunction()
+
+A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/node-8.11/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Function> Nan::GetFunction(v8::Local<v8::FunctionTemplate> t);
+```
+
+
+<a name="api_nan_set"></a>
+### Nan::Set()
+
+A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
+                          v8::Local<v8::Value> key,
+                          v8::Local<v8::Value> value)
+Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
+                          uint32_t index,
+                          v8::Local<v8::Value> value);
+```
+
+
+<a name="api_nan_define_own_property"></a>
+### Nan::DefineOwnProperty()
+
+A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::DefineOwnProperty(v8::Local<v8::Object> obj,
+                                        v8::Local<v8::String> key,
+                                        v8::Local<v8::Value> value,
+                                        v8::PropertyAttribute attribs = v8::None);
+```
+
+
+<a name="api_nan_force_set"></a>
+### <del>Nan::ForceSet()</del>
+
+Deprecated, use <a href="#api_nan_define_own_property"><code>Nan::DefineOwnProperty()</code></a>.
+
+<del>A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/node-0.12/db/d85/classv8_1_1_object.html#acfbdfd7427b516ebdb5c47c4df5ed96c) in a way compatible across supported versions of V8.</del>
+
+Signature:
+
+```c++
+NAN_DEPRECATED Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object> obj,
+                                              v8::Local<v8::Value> key,
+                                              v8::Local<v8::Value> value,
+                                              v8::PropertyAttribute attribs = v8::None);
+```
+
+
+<a name="api_nan_get"></a>
+### Nan::Get()
+
+A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj,
+                                    v8::Local<v8::Value> key);
+Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, uint32_t index);
+```
+
+
+<a name="api_nan_get_property_attribute"></a>
+### Nan::GetPropertyAttributes()
+
+A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<v8::PropertyAttribute> Nan::GetPropertyAttributes(
+    v8::Local<v8::Object> obj,
+    v8::Local<v8::Value> key);
+```
+
+
+<a name="api_nan_has"></a>
+### Nan::Has()
+
+A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, v8::Local<v8::String> key);
+Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, uint32_t index);
+```
+
+
+<a name="api_nan_delete"></a>
+### Nan::Delete()
+
+A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a48e4a19b2cedff867eecc73ddb7d377f) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj,
+                             v8::Local<v8::String> key);
+Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, uint32_t index);
+```
+
+
+<a name="api_nan_get_property_names"></a>
+### Nan::GetPropertyNames()
+
+A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Array> Nan::GetPropertyNames(v8::Local<v8::Object> obj);
+```
+
+
+<a name="api_nan_get_own_property_names"></a>
+### Nan::GetOwnPropertyNames()
+
+A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Array> Nan::GetOwnPropertyNames(v8::Local<v8::Object> obj);
+```
+
+
+<a name="api_nan_set_prototype"></a>
+### Nan::SetPrototype()
+
+A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::SetPrototype(v8::Local<v8::Object> obj,
+                                   v8::Local<v8::Value> prototype);
+```
+
+
+<a name="api_nan_object_proto_to_string"></a>
+### Nan::ObjectProtoToString()
+
+A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::String> Nan::ObjectProtoToString(v8::Local<v8::Object> obj);
+```
+
+
+<a name="api_nan_has_own_property"></a>
+### Nan::HasOwnProperty()
+
+A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::HasOwnProperty(v8::Local<v8::Object> obj,
+                                     v8::Local<v8::String> key);
+```
+
+
+<a name="api_nan_has_real_named_property"></a>
+### Nan::HasRealNamedProperty()
+
+A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::HasRealNamedProperty(v8::Local<v8::Object> obj,
+                                           v8::Local<v8::String> key);
+```
+
+
+<a name="api_nan_has_real_indexed_property"></a>
+### Nan::HasRealIndexedProperty()
+
+A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::HasRealIndexedProperty(v8::Local<v8::Object> obj,
+                                             uint32_t index);
+```
+
+
+<a name="api_nan_has_real_named_callback_property"></a>
+### Nan::HasRealNamedCallbackProperty()
+
+A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::HasRealNamedCallbackProperty(
+    v8::Local<v8::Object> obj,
+    v8::Local<v8::String> key);
+```
+
+
+<a name="api_nan_get_real_named_property_in_prototype_chain"></a>
+### Nan::GetRealNamedPropertyInPrototypeChain()
+
+A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::GetRealNamedPropertyInPrototypeChain(
+    v8::Local<v8::Object> obj,
+    v8::Local<v8::String> key);
+```
+
+
+<a name="api_nan_get_real_named_property"></a>
+### Nan::GetRealNamedProperty()
+
+A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::GetRealNamedProperty(v8::Local<v8::Object> obj,
+                                                     v8::Local<v8::String> key);
+```
+
+
+<a name="api_nan_call_as_function"></a>
+### Nan::CallAsFunction()
+
+A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ad3ffc36f3dfc3592ce2a96bc047ee2cd) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::CallAsFunction(v8::Local<v8::Object> obj,
+                                               v8::Local<v8::Object> recv,
+                                               int argc,
+                                               v8::Local<v8::Value> argv[]);
+```
+
+
+<a name="api_nan_call_as_constructor"></a>
+### Nan::CallAsConstructor()
+
+A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::CallAsConstructor(v8::Local<v8::Object> obj,
+                                                  int argc,
+                                                  v8::Local<v8::Value> argv[]);
+```
+
+
+<a name="api_nan_get_source_line"></a>
+### Nan::GetSourceLine()
+
+A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::String> Nan::GetSourceLine(v8::Local<v8::Message> msg);
+```
+
+
+<a name="api_nan_get_line_number"></a>
+### Nan::GetLineNumber()
+
+A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<int> Nan::GetLineNumber(v8::Local<v8::Message> msg);
+```
+
+
+<a name="api_nan_get_start_column"></a>
+### Nan::GetStartColumn()
+
+A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<int> Nan::GetStartColumn(v8::Local<v8::Message> msg);
+```
+
+
+<a name="api_nan_get_end_column"></a>
+### Nan::GetEndColumn()
+
+A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/node-8.11/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<int> Nan::GetEndColumn(v8::Local<v8::Message> msg);
+```
+
+
+<a name="api_nan_clone_element_at"></a>
+### Nan::CloneElementAt()
+
+A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/node-4.8/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array> array, uint32_t index);
+```
+
+<a name="api_nan_has_private"></a>
+### Nan::HasPrivate()
+
+A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
+```
+
+<a name="api_nan_get_private"></a>
+### Nan::GetPrivate()
+
+A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
+```
+
+<a name="api_nan_set_private"></a>
+### Nan::SetPrivate()
+
+A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value);
+```
+
+<a name="api_nan_delete_private"></a>
+### Nan::DeletePrivate()
+
+A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8.
+
+Signature:
+
+```c++
+Nan::Maybe<bool> Nan::DeletePrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
+```
+
+<a name="api_nan_make_maybe"></a>
+### Nan::MakeMaybe()
+
+Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN.
+
+Synopsis:
+
+```c++
+  MaybeLocal<v8::Number> someNumber = MakeMaybe(New<v8::Number>(3.141592654));
+  MaybeLocal<v8::String> someString = MakeMaybe(New<v8::String>("probably"));
+```
+
+Signature:
+
+```c++
+template <typename T, template <typename> class MaybeMaybe>
+Nan::MaybeLocal<T> Nan::MakeMaybe(MaybeMaybe<T> v);
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/methods.md b/node_modules/node-pty/node_modules/nan/doc/methods.md
new file mode 100644 (file)
index 0000000..b2b26c3
--- /dev/null
@@ -0,0 +1,661 @@
+## JavaScript-accessible methods
+
+A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
+
+In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
+
+* **Method argument types**
+ - <a href="#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
+ - <a href="#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
+ - <a href="#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
+* **Method declarations**
+ - <a href="#api_nan_method"><b>Method declaration</b></a>
+ - <a href="#api_nan_getter"><b>Getter declaration</b></a>
+ - <a href="#api_nan_setter"><b>Setter declaration</b></a>
+ - <a href="#api_nan_property_getter"><b>Property getter declaration</b></a>
+ - <a href="#api_nan_property_setter"><b>Property setter declaration</b></a>
+ - <a href="#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
+ - <a href="#api_nan_property_deleter"><b>Property deleter declaration</b></a>
+ - <a href="#api_nan_property_query"><b>Property query declaration</b></a>
+ - <a href="#api_nan_index_getter"><b>Index getter declaration</b></a>
+ - <a href="#api_nan_index_setter"><b>Index setter declaration</b></a>
+ - <a href="#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
+ - <a href="#api_nan_index_deleter"><b>Index deleter declaration</b></a>
+ - <a href="#api_nan_index_query"><b>Index query declaration</b></a>
+* Method and template helpers
+ - <a href="#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
+ - <a href="#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
+ - <a href="#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
+ - <a href="#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
+ - <a href="#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
+ - <a href="#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
+ - <a href="#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
+ - <a href="#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
+ - <a href="#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
+ - <a href="#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
+
+<a name="api_nan_function_callback_info"></a>
+### Nan::FunctionCallbackInfo
+
+`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.11/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist.
+
+Definition:
+
+```c++
+template<typename T> class FunctionCallbackInfo {
+ public:
+  ReturnValue<T> GetReturnValue() const;
+  v8::Local<v8::Function> Callee(); // NOTE: Not available in NodeJS >= 10.0.0
+  v8::Local<v8::Value> Data();
+  v8::Local<v8::Object> Holder();
+  bool IsConstructCall();
+  int Length() const;
+  v8::Local<v8::Value> operator[](int i) const;
+  v8::Local<v8::Object> This() const;
+  v8::Isolate *GetIsolate() const;
+};
+```
+
+See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.11/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods.
+
+**Note:** `FunctionCallbackInfo::Callee` is removed in Node.js after `10.0.0` because it is was deprecated in V8. Consider using `info.Data()` to pass any information you need.
+
+<a name="api_nan_property_callback_info"></a>
+### Nan::PropertyCallbackInfo
+
+`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.11/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist.
+
+Definition:
+
+```c++
+template<typename T> class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
+ public:
+  ReturnValue<T> GetReturnValue() const;
+  v8::Isolate* GetIsolate() const;
+  v8::Local<v8::Value> Data() const;
+  v8::Local<v8::Object> This() const;
+  v8::Local<v8::Object> Holder() const;
+};
+```
+
+See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.11/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods.
+
+<a name="api_nan_return_value"></a>
+### Nan::ReturnValue
+
+`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.11/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`.
+
+Example usage:
+
+```c++
+void EmptyArray(const Nan::FunctionCallbackInfo<v8::Value>& info) {
+  info.GetReturnValue().Set(Nan::New<v8::Array>());
+}
+```
+
+Definition:
+
+```c++
+template<typename T> class ReturnValue {
+ public:
+  // Handle setters
+  template <typename S> void Set(const v8::Local<S> &handle);
+  template <typename S> void Set(const Nan::Global<S> &handle);
+
+  // Fast primitive setters
+  void Set(bool value);
+  void Set(double i);
+  void Set(int32_t i);
+  void Set(uint32_t i);
+
+  // Fast JS primitive setters
+  void SetNull();
+  void SetUndefined();
+  void SetEmptyString();
+
+  // Convenience getter for isolate
+  v8::Isolate *GetIsolate() const;
+};
+```
+
+See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.11/da/da7/classv8_1_1_return_value.html) for further information on this.
+
+<a name="api_nan_method"></a>
+### Method declaration
+
+JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`:
+
+```c++
+typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
+```
+
+Example:
+
+```c++
+void MethodName(const Nan::FunctionCallbackInfo<v8::Value>& info) {
+  ...
+}
+```
+
+You do not need to declare a new `HandleScope` within a method as one is implicitly created for you.
+
+**Example usage**
+
+```c++
+// .h:
+class Foo : public Nan::ObjectWrap {
+  ...
+
+  static void Bar(const Nan::FunctionCallbackInfo<v8::Value>& info);
+  static void Baz(const Nan::FunctionCallbackInfo<v8::Value>& info);
+}
+
+
+// .cc:
+void Foo::Bar(const Nan::FunctionCallbackInfo<v8::Value>& info) {
+  ...
+}
+
+void Foo::Baz(const Nan::FunctionCallbackInfo<v8::Value>& info) {
+  ...
+}
+```
+
+A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations.
+
+**Example usage with `NAN_METHOD(methodname)`**
+
+```c++
+// .h:
+class Foo : public Nan::ObjectWrap {
+  ...
+
+  static NAN_METHOD(Bar);
+  static NAN_METHOD(Baz);
+}
+
+
+// .cc:
+NAN_METHOD(Foo::Bar) {
+  ...
+}
+
+NAN_METHOD(Foo::Baz) {
+  ...
+}
+```
+
+Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object.
+
+<a name="api_nan_getter"></a>
+### Getter declaration
+
+JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`:
+
+```c++
+typedef void(*GetterCallback)(v8::Local<v8::String>,
+                              const PropertyCallbackInfo<v8::Value>&);
+```
+
+Example:
+
+```c++
+void GetterName(v8::Local<v8::String> property,
+                const Nan::PropertyCallbackInfo<v8::Value>& info) {
+  ...
+}
+```
+
+You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you.
+
+A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
+
+<a name="api_nan_setter"></a>
+### Setter declaration
+
+JavaScript-accessible setters should be declared with the following signature to form a <b><code>Nan::SetterCallback</code></b>:
+
+```c++
+typedef void(*SetterCallback)(v8::Local<v8::String>,
+                              v8::Local<v8::Value>,
+                              const PropertyCallbackInfo<void>&);
+```
+
+Example:
+
+```c++
+void SetterName(v8::Local<v8::String> property,
+                v8::Local<v8::Value> value,
+                const Nan::PropertyCallbackInfo<void>& info) {
+  ...
+}
+```
+
+You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you.
+
+A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
+
+<a name="api_nan_property_getter"></a>
+### Property getter declaration
+
+JavaScript-accessible property getters should be declared with the following signature to form a <b><code>Nan::PropertyGetterCallback</code></b>:
+
+```c++
+typedef void(*PropertyGetterCallback)(v8::Local<v8::String>,
+                                      const PropertyCallbackInfo<v8::Value>&);
+```
+
+Example:
+
+```c++
+void PropertyGetterName(v8::Local<v8::String> property,
+                        const Nan::PropertyCallbackInfo<v8::Value>& info) {
+  ...
+}
+```
+
+You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you.
+
+A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_property_setter"></a>
+### Property setter declaration
+
+JavaScript-accessible property setters should be declared with the following signature to form a <b><code>Nan::PropertySetterCallback</code></b>:
+
+```c++
+typedef void(*PropertySetterCallback)(v8::Local<v8::String>,
+                                      v8::Local<v8::Value>,
+                                      const PropertyCallbackInfo<v8::Value>&);
+```
+
+Example:
+
+```c++
+void PropertySetterName(v8::Local<v8::String> property,
+                        v8::Local<v8::Value> value,
+                        const Nan::PropertyCallbackInfo<v8::Value>& info);
+```
+
+You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you.
+
+A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_property_enumerator"></a>
+### Property enumerator declaration
+
+JavaScript-accessible property enumerators should be declared with the following signature to form a <b><code>Nan::PropertyEnumeratorCallback</code></b>:
+
+```c++
+typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
+```
+
+Example:
+
+```c++
+void PropertyEnumeratorName(const Nan::PropertyCallbackInfo<v8::Array>& info);
+```
+
+You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you.
+
+A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_property_deleter"></a>
+### Property deleter declaration
+
+JavaScript-accessible property deleters should be declared with the following signature to form a <b><code>Nan::PropertyDeleterCallback</code></b>:
+
+```c++
+typedef void(*PropertyDeleterCallback)(v8::Local<v8::String>,
+                                       const PropertyCallbackInfo<v8::Boolean>&);
+```
+
+Example:
+
+```c++
+void PropertyDeleterName(v8::Local<v8::String> property,
+                         const Nan::PropertyCallbackInfo<v8::Boolean>& info);
+```
+
+You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you.
+
+A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_property_query"></a>
+### Property query declaration
+
+JavaScript-accessible property query methods should be declared with the following signature to form a <b><code>Nan::PropertyQueryCallback</code></b>:
+
+```c++
+typedef void(*PropertyQueryCallback)(v8::Local<v8::String>,
+                                     const PropertyCallbackInfo<v8::Integer>&);
+```
+
+Example:
+
+```c++
+void PropertyQueryName(v8::Local<v8::String> property,
+                       const Nan::PropertyCallbackInfo<v8::Integer>& info);
+```
+
+You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you.
+
+A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_index_getter"></a>
+### Index getter declaration
+
+JavaScript-accessible index getter methods should be declared with the following signature to form a <b><code>Nan::IndexGetterCallback</code></b>:
+
+```c++
+typedef void(*IndexGetterCallback)(uint32_t,
+                                   const PropertyCallbackInfo<v8::Value>&);
+```
+
+Example:
+
+```c++
+void IndexGetterName(uint32_t index, const PropertyCallbackInfo<v8::Value>& info);
+```
+
+You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you.
+
+A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_index_setter"></a>
+### Index setter declaration
+
+JavaScript-accessible index setter methods should be declared with the following signature to form a <b><code>Nan::IndexSetterCallback</code></b>:
+
+```c++
+typedef void(*IndexSetterCallback)(uint32_t,
+                                   v8::Local<v8::Value>,
+                                   const PropertyCallbackInfo<v8::Value>&);
+```
+
+Example:
+
+```c++
+void IndexSetterName(uint32_t index,
+                     v8::Local<v8::Value> value,
+                     const PropertyCallbackInfo<v8::Value>& info);
+```
+
+You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you.
+
+A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_index_enumerator"></a>
+### Index enumerator declaration
+
+JavaScript-accessible index enumerator methods should be declared with the following signature to form a <b><code>Nan::IndexEnumeratorCallback</code></b>:
+
+```c++
+typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
+```
+
+Example:
+
+```c++
+void IndexEnumeratorName(const PropertyCallbackInfo<v8::Array>& info);
+```
+
+You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you.
+
+A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_index_deleter"></a>
+### Index deleter declaration
+
+JavaScript-accessible index deleter methods should be declared with the following signature to form a <b><code>Nan::IndexDeleterCallback</code></b>:
+
+```c++
+typedef void(*IndexDeleterCallback)(uint32_t,
+                                    const PropertyCallbackInfo<v8::Boolean>&);
+```
+
+Example:
+
+```c++
+void IndexDeleterName(uint32_t index, const PropertyCallbackInfo<v8::Boolean>& info);
+```
+
+You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you.
+
+A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_index_query"></a>
+### Index query declaration
+
+JavaScript-accessible index query methods should be declared with the following signature to form a <b><code>Nan::IndexQueryCallback</code></b>:
+
+```c++
+typedef void(*IndexQueryCallback)(uint32_t,
+                                  const PropertyCallbackInfo<v8::Integer>&);
+```
+
+Example:
+
+```c++
+void IndexQueryName(uint32_t index, const PropertyCallbackInfo<v8::Integer>& info);
+```
+
+You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you.
+
+A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
+
+Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
+
+<a name="api_nan_set_method"></a>
+### Nan::SetMethod()
+
+Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
+
+Signature:
+
+```c++
+void Nan::SetMethod(v8::Local<v8::Object> recv,
+                    const char *name,
+                    Nan::FunctionCallback callback)
+void Nan::SetMethod(v8::Local<v8::Template> templ,
+                    const char *name,
+                    Nan::FunctionCallback callback)
+```
+
+<a name="api_nan_set_prototype_method"></a>
+### Nan::SetPrototypeMethod()
+
+Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
+
+Signature:
+
+```c++
+void Nan::SetPrototypeMethod(v8::Local<v8::FunctionTemplate> recv,
+                             const char* name,
+                             Nan::FunctionCallback callback)
+```
+
+<a name="api_nan_set_accessor"></a>
+### Nan::SetAccessor()
+
+Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see <a href="#api_nan_getter">Getter declaration</a>) and setters with the `Nan::SetterCallback` signature (see <a href="#api_nan_setter">Setter declaration</a>).
+
+Signature:
+
+```c++
+void SetAccessor(v8::Local<v8::ObjectTemplate> tpl,
+                 v8::Local<v8::String> name,
+                 Nan::GetterCallback getter,
+                 Nan::SetterCallback setter = 0,
+                 v8::Local<v8::Value> data = v8::Local<v8::Value>(),
+                 v8::AccessControl settings = v8::DEFAULT,
+                 v8::PropertyAttribute attribute = v8::None,
+                 imp::Sig signature = imp::Sig());
+bool SetAccessor(v8::Local<v8::Object> obj,
+                 v8::Local<v8::String> name,
+                 Nan::GetterCallback getter,
+                 Nan::SetterCallback setter = 0,
+                 v8::Local<v8::Value> data = v8::Local<v8::Value>(),
+                 v8::AccessControl settings = v8::DEFAULT,
+                 v8::PropertyAttribute attribute = v8::None)
+```
+
+See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ae91b3b56b357f285288c89fbddc46d1b) for further information about how to use `Nan::SetAccessor()`.
+
+<a name="api_nan_set_named_property_handler"></a>
+### Nan::SetNamedPropertyHandler()
+
+Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
+
+* Property getters with the `Nan::PropertyGetterCallback` signature (see <a href="#api_nan_property_getter">Property getter declaration</a>)
+* Property setters with the `Nan::PropertySetterCallback` signature (see <a href="#api_nan_property_setter">Property setter declaration</a>)
+* Property query methods with the `Nan::PropertyQueryCallback` signature (see <a href="#api_nan_property_query">Property query declaration</a>)
+* Property deleters with the `Nan::PropertyDeleterCallback` signature (see <a href="#api_nan_property_deleter">Property deleter declaration</a>)
+* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see <a href="#api_nan_property_enumerator">Property enumerator declaration</a>)
+
+Signature:
+
+```c++
+void SetNamedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
+                             Nan::PropertyGetterCallback getter,
+                             Nan::PropertySetterCallback setter = 0,
+                             Nan::PropertyQueryCallback query = 0,
+                             Nan::PropertyDeleterCallback deleter = 0,
+                             Nan::PropertyEnumeratorCallback enumerator = 0,
+                             v8::Local<v8::Value> data = v8::Local<v8::Value>())
+```
+
+See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#a33b3ebd7de641f6cc6414b7de01fc1c7) for further information about how to use `Nan::SetNamedPropertyHandler()`.
+
+<a name="api_nan_set_indexed_property_handler"></a>
+### Nan::SetIndexedPropertyHandler()
+
+Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
+
+* Indexed property getters with the `Nan::IndexGetterCallback` signature (see <a href="#api_nan_index_getter">Index getter declaration</a>)
+* Indexed property setters with the `Nan::IndexSetterCallback` signature (see <a href="#api_nan_index_setter">Index setter declaration</a>)
+* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see <a href="#api_nan_index_query">Index query declaration</a>)
+* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see <a href="#api_nan_index_deleter">Index deleter declaration</a>)
+* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see <a href="#api_nan_index_enumerator">Index enumerator declaration</a>)
+
+Signature:
+
+```c++
+void SetIndexedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
+                               Nan::IndexGetterCallback getter,
+                               Nan::IndexSetterCallback setter = 0,
+                               Nan::IndexQueryCallback query = 0,
+                               Nan::IndexDeleterCallback deleter = 0,
+                               Nan::IndexEnumeratorCallback enumerator = 0,
+                               v8::Local<v8::Value> data = v8::Local<v8::Value>())
+```
+
+See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`.
+
+<a name="api_nan_set_template"></a>
+### Nan::SetTemplate()
+
+Adds properties on an `Object`'s or `Function`'s template.
+
+Signature:
+
+```c++
+void Nan::SetTemplate(v8::Local<v8::Template> templ,
+                      const char *name,
+                      v8::Local<v8::Data> value);
+void Nan::SetTemplate(v8::Local<v8::Template> templ,
+                      v8::Local<v8::String> name,
+                      v8::Local<v8::Data> value,
+                      v8::PropertyAttribute attributes)
+```
+
+Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.11/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac).
+
+<a name="api_nan_set_prototype_template"></a>
+### Nan::SetPrototypeTemplate()
+
+Adds properties on an `Object`'s or `Function`'s prototype template.
+
+Signature:
+
+```c++
+void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
+                               const char *name,
+                               v8::Local<v8::Data> value);
+void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
+                               v8::Local<v8::String> name,
+                               v8::Local<v8::Data> value,
+                               v8::PropertyAttribute attributes)
+```
+
+Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.11/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
+
+<a name="api_nan_set_instance_template"></a>
+### Nan::SetInstanceTemplate()
+
+Use to add instance properties on `FunctionTemplate`'s.
+
+Signature:
+
+```c++
+void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
+                              const char *name,
+                              v8::Local<v8::Data> value);
+void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
+                              v8::Local<v8::String> name,
+                              v8::Local<v8::Data> value,
+                              v8::PropertyAttribute attributes)
+```
+
+Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.11/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
+
+<a name="api_nan_set_call_handler"></a>
+### Nan::SetCallHandler()
+
+Set the call-handler callback for a `v8::FunctionTemplate`.
+This callback is called whenever the function created from this FunctionTemplate is called.
+
+Signature:
+
+```c++
+void Nan::SetCallHandler(v8::Local<v8::FunctionTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>())
+```
+
+Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.11/d8/d83/classv8_1_1_function_template.html#ab7574b298db3c27fbc2ed465c08ea2f8).
+
+<a name="api_nan_set_call_as_function_handler"></a>
+### Nan::SetCallAsFunctionHandler()
+
+Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function.
+If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function.
+
+Signature:
+
+```c++
+void Nan::SetCallAsFunctionHandler(v8::Local<v8::ObjectTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>())
+```
+
+Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.11/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e).
+
diff --git a/node_modules/node-pty/node_modules/nan/doc/new.md b/node_modules/node-pty/node_modules/nan/doc/new.md
new file mode 100644 (file)
index 0000000..359df43
--- /dev/null
@@ -0,0 +1,147 @@
+## New
+
+NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
+
+ - <a href="#api_nan_new"><b><code>Nan::New()</code></b></a>
+ - <a href="#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
+ - <a href="#api_nan_null"><b><code>Nan::Null()</code></b></a>
+ - <a href="#api_nan_true"><b><code>Nan::True()</code></b></a>
+ - <a href="#api_nan_false"><b><code>Nan::False()</code></b></a>
+ - <a href="#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
+
+
+<a name="api_nan_new"></a>
+### Nan::New()
+
+`Nan::New()` should be used to instantiate new JavaScript objects.
+
+Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation.
+
+Signatures:
+
+Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local<T>`. The following types will be contained within a `Nan::MaybeLocal<T>`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`.
+
+Empty objects:
+
+```c++
+Nan::New<T>();
+```
+
+Generic single and multiple-argument:
+
+```c++
+Nan::New<T>(A0 arg0);
+Nan::New<T>(A0 arg0, A1 arg1);
+Nan::New<T>(A0 arg0, A1 arg1, A2 arg2);
+Nan::New<T>(A0 arg0, A1 arg1, A2 arg2, A3 arg3);
+```
+
+For creating `v8::FunctionTemplate` and `v8::Function` objects:
+
+_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._
+
+```c++
+Nan::New<T>(Nan::FunctionCallback callback,
+            v8::Local<v8::Value> data = v8::Local<v8::Value>());
+Nan::New<T>(Nan::FunctionCallback callback,
+            v8::Local<v8::Value> data = v8::Local<v8::Value>(),
+            A2 a2 = A2());
+```
+
+Native number types:
+
+```c++
+v8::Local<v8::Boolean> Nan::New<T>(bool value);
+v8::Local<v8::Int32> Nan::New<T>(int32_t value);
+v8::Local<v8::Uint32> Nan::New<T>(uint32_t value);
+v8::Local<v8::Number> Nan::New<T>(double value);
+```
+
+String types:
+
+```c++
+Nan::MaybeLocal<v8::String> Nan::New<T>(std::string const& value);
+Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value, int length);
+Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value);
+Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value);
+Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value, int length);
+```
+
+Specialized types:
+
+```c++
+v8::Local<v8::String> Nan::New<T>(v8::String::ExternalStringResource * value);
+v8::Local<v8::String> Nan::New<T>(Nan::ExternalOneByteStringResource * value);
+v8::Local<v8::RegExp> Nan::New<T>(v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
+```
+
+Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/node-8.11/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8.
+
+
+<a name="api_nan_undefined"></a>
+### Nan::Undefined()
+
+A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8.
+
+Signature:
+
+```c++
+v8::Local<v8::Primitive> Nan::Undefined()
+```
+
+<a name="api_nan_null"></a>
+### Nan::Null()
+
+A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8.
+
+Signature:
+
+```c++
+v8::Local<v8::Primitive> Nan::Null()
+```
+
+<a name="api_nan_true"></a>
+### Nan::True()
+
+A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8.
+
+Signature:
+
+```c++
+v8::Local<v8::Boolean> Nan::True()
+```
+
+<a name="api_nan_false"></a>
+### Nan::False()
+
+A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8.
+
+Signature:
+
+```c++
+v8::Local<v8::Boolean> Nan::False()
+```
+
+<a name="api_nan_empty_string"></a>
+### Nan::EmptyString()
+
+Call [`v8::String::Empty`](https://v8docs.nodesource.com/node-8.11/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8.
+
+Signature:
+
+```c++
+v8::Local<v8::String> Nan::EmptyString()
+```
+
+
+<a name="api_nan_new_one_byte_string"></a>
+### Nan::NewOneByteString()
+
+An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/node-8.11/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::String> Nan::NewOneByteString(const uint8_t * value,
+                                                  int length = -1)
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/node_misc.md b/node_modules/node-pty/node_modules/nan/doc/node_misc.md
new file mode 100644 (file)
index 0000000..17578e3
--- /dev/null
@@ -0,0 +1,123 @@
+## Miscellaneous Node Helpers
+
+ - <a href="#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
+ - <a href="#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
+ - <a href="#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
+ - <a href="#api_nan_export"><b><code>Nan::Export()</code></b></a>
+
+<a name="api_nan_asyncresource"></a>
+### Nan::AsyncResource
+
+This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API.
+
+When calling back into JavaScript asynchronously, special care must be taken to ensure that the runtime can properly track
+async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`,
+and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or
+`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms
+such as domains and [async_hooks][] function correctly.
+
+Definition:
+
+```c++
+class AsyncResource {
+ public:
+  AsyncResource(v8::Local<v8::String> name,
+                v8::Local<v8::Object> resource = New<v8::Object>());
+  AsyncResource(const char* name,
+                v8::Local<v8::Object> resource = New<v8::Object>());
+  ~AsyncResource();
+
+  v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
+                                            v8::Local<v8::Function> func,
+                                            int argc,
+                                            v8::Local<v8::Value>* argv);
+  v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
+                                            v8::Local<v8::String> symbol,
+                                            int argc,
+                                            v8::Local<v8::Value>* argv);
+  v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
+                                            const char* method,
+                                            int argc,
+                                            v8::Local<v8::Value>* argv);
+};
+```
+
+* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][]
+  API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend
+  that the name include the name of the owning module as a prefix. For example `mysql` module could use something like
+  `mysql:batch-db-query-resource`.
+* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][]
+  `init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically.
+* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the
+  correct async execution context.
+* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed.
+
+For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the
+[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory.
+
+<a name="api_nan_make_callback"></a>
+### Nan::MakeCallback()
+
+Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+
+has deprecated these legacy APIs as they do not provide a mechanism to preserve
+async context.
+
+We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or
+`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution
+context – something that is essential for functionality like domains, async_hooks and async debugging.
+
+Signatures:
+
+```c++
+NAN_DEPRECATED
+v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
+                                       v8::Local<v8::Function> func,
+                                       int argc,
+                                       v8::Local<v8::Value>* argv);
+NAN_DEPRECATED
+v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
+                                       v8::Local<v8::String> symbol,
+                                       int argc,
+                                       v8::Local<v8::Value>* argv);
+NAN_DEPRECATED
+v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
+                                       const char* method,
+                                       int argc,
+                                       v8::Local<v8::Value>* argv);
+```
+
+
+<a name="api_nan_module_init"></a>
+### NAN_MODULE_INIT()
+
+Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object.
+
+See example below.
+
+<a name="api_nan_export"></a>
+### Nan::Export()
+
+A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript.
+
+Signature:
+
+```c++
+void Export(v8::Local<v8::Object> target, const char *name, Nan::FunctionCallback f)
+```
+
+Also available as the shortcut `NAN_EXPORT` macro.
+
+Example:
+
+```c++
+NAN_METHOD(Foo) {
+  ...
+}
+
+NAN_MODULE_INIT(Init) {
+  NAN_EXPORT(target, Foo);
+}
+```
+
+[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html
+[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations
diff --git a/node_modules/node-pty/node_modules/nan/doc/object_wrappers.md b/node_modules/node-pty/node_modules/nan/doc/object_wrappers.md
new file mode 100644 (file)
index 0000000..08dd6b5
--- /dev/null
@@ -0,0 +1,263 @@
+## Object Wrappers
+
+The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
+
+ - <a href="#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
+
+
+<a name="api_nan_object_wrap"></a>
+### Nan::ObjectWrap()
+
+A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency.
+
+Definition:
+
+```c++
+class ObjectWrap {
+ public:
+  ObjectWrap();
+
+  virtual ~ObjectWrap();
+
+  template <class T>
+  static inline T* Unwrap(v8::Local<v8::Object> handle);
+
+  inline v8::Local<v8::Object> handle();
+
+  inline Nan::Persistent<v8::Object>& persistent();
+
+ protected:
+  inline void Wrap(v8::Local<v8::Object> handle);
+
+  inline void MakeWeak();
+
+  /* Ref() marks the object as being attached to an event loop.
+   * Refed objects will not be garbage collected, even if
+   * all references are lost.
+   */
+  virtual void Ref();
+
+  /* Unref() marks an object as detached from the event loop.  This is its
+   * default state.  When an object with a "weak" reference changes from
+   * attached to detached state it will be freed. Be careful not to access
+   * the object after making this call as it might be gone!
+   * (A "weak reference" means an object that only has a
+   * persistant handle.)
+   *
+   * DO NOT CALL THIS FROM DESTRUCTOR
+   */
+  virtual void Unref();
+
+  int refs_;  // ro
+};
+```
+
+See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details.
+
+### This vs. Holder
+
+When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class.
+The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance.
+In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected.
+However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain.
+In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption.
+
+On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype.
+So either define your accessors on the instance template,
+or use `This()` after verifying that it is indeed a valid object.
+
+### Examples
+
+#### Basic
+
+```c++
+class MyObject : public Nan::ObjectWrap {
+ public:
+  static NAN_MODULE_INIT(Init) {
+    v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
+    tpl->SetClassName(Nan::New("MyObject").ToLocalChecked());
+    tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+    Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle);
+    Nan::SetPrototypeMethod(tpl, "getValue", GetValue);
+
+    constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
+    Nan::Set(target, Nan::New("MyObject").ToLocalChecked(),
+      Nan::GetFunction(tpl).ToLocalChecked());
+  }
+
+ private:
+  explicit MyObject(double value = 0) : value_(value) {}
+  ~MyObject() {}
+
+  static NAN_METHOD(New) {
+    if (info.IsConstructCall()) {
+      double value = info[0]->IsUndefined() ? 0 : Nan::To<double>(info[0]).FromJust();
+      MyObject *obj = new MyObject(value);
+      obj->Wrap(info.This());
+      info.GetReturnValue().Set(info.This());
+    } else {
+      const int argc = 1;
+      v8::Local<v8::Value> argv[argc] = {info[0]};
+      v8::Local<v8::Function> cons = Nan::New(constructor());
+      info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
+    }
+  }
+
+  static NAN_METHOD(GetHandle) {
+    MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder());
+    info.GetReturnValue().Set(obj->handle());
+  }
+
+  static NAN_METHOD(GetValue) {
+    MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder());
+    info.GetReturnValue().Set(obj->value_);
+  }
+
+  static inline Nan::Persistent<v8::Function> & constructor() {
+    static Nan::Persistent<v8::Function> my_constructor;
+    return my_constructor;
+  }
+
+  double value_;
+};
+
+NODE_MODULE(objectwrapper, MyObject::Init)
+```
+
+To use in Javascript:
+
+```Javascript
+var objectwrapper = require('bindings')('objectwrapper');
+
+var obj = new objectwrapper.MyObject(5);
+console.log('Should be 5: ' + obj.getValue());
+```
+
+#### Factory of wrapped objects
+
+```c++
+class MyFactoryObject : public Nan::ObjectWrap {
+ public:
+  static NAN_MODULE_INIT(Init) {
+    v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
+    tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+    Nan::SetPrototypeMethod(tpl, "getValue", GetValue);
+
+    constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
+  }
+
+  static NAN_METHOD(NewInstance) {
+    v8::Local<v8::Function> cons = Nan::New(constructor());
+    double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0;
+    const int argc = 1;
+    v8::Local<v8::Value> argv[1] = {Nan::New(value)};
+    info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
+  }
+
+  // Needed for the next example:
+  inline double value() const {
+    return value_;
+  }
+
+ private:
+  explicit MyFactoryObject(double value = 0) : value_(value) {}
+  ~MyFactoryObject() {}
+
+  static NAN_METHOD(New) {
+    if (info.IsConstructCall()) {
+      double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0;
+      MyFactoryObject * obj = new MyFactoryObject(value);
+      obj->Wrap(info.This());
+      info.GetReturnValue().Set(info.This());
+    } else {
+      const int argc = 1;
+      v8::Local<v8::Value> argv[argc] = {info[0]};
+      v8::Local<v8::Function> cons = Nan::New(constructor());
+      info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
+    }
+  }
+
+  static NAN_METHOD(GetValue) {
+    MyFactoryObject* obj = ObjectWrap::Unwrap<MyFactoryObject>(info.Holder());
+    info.GetReturnValue().Set(obj->value_);
+  }
+
+  static inline Nan::Persistent<v8::Function> & constructor() {
+    static Nan::Persistent<v8::Function> my_constructor;
+    return my_constructor;
+  }
+
+  double value_;
+};
+
+NAN_MODULE_INIT(Init) {
+  MyFactoryObject::Init(target);
+  Nan::Set(target,
+    Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(),
+    Nan::GetFunction(
+      Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked()
+  );
+}
+
+NODE_MODULE(wrappedobjectfactory, Init)
+```
+
+To use in Javascript:
+
+```Javascript
+var wrappedobjectfactory = require('bindings')('wrappedobjectfactory');
+
+var obj = wrappedobjectfactory.newFactoryObjectInstance(10);
+console.log('Should be 10: ' + obj.getValue());
+```
+
+#### Passing wrapped objects around
+
+Use the `MyFactoryObject` class above along with the following:
+
+```c++
+static NAN_METHOD(Sum) {
+  Nan::MaybeLocal<v8::Object> maybe1 = Nan::To<v8::Object>(info[0]);
+  Nan::MaybeLocal<v8::Object> maybe2 = Nan::To<v8::Object>(info[1]);
+
+  // Quick check:
+  if (maybe1.IsEmpty() || maybe2.IsEmpty()) {
+    // return value is undefined by default
+    return;
+  }
+
+  MyFactoryObject* obj1 =
+    Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe1.ToLocalChecked());
+  MyFactoryObject* obj2 =
+    Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe2.ToLocalChecked());
+
+  info.GetReturnValue().Set(Nan::New<v8::Number>(obj1->value() + obj2->value()));
+}
+
+NAN_MODULE_INIT(Init) {
+  MyFactoryObject::Init(target);
+  Nan::Set(target,
+    Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(),
+    Nan::GetFunction(
+      Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked()
+  );
+  Nan::Set(target,
+    Nan::New<v8::String>("sum").ToLocalChecked(),
+    Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Sum)).ToLocalChecked()
+  );
+}
+
+NODE_MODULE(myaddon, Init)
+```
+
+To use in Javascript:
+
+```Javascript
+var myaddon = require('bindings')('myaddon');
+
+var obj1 = myaddon.newFactoryObjectInstance(5);
+var obj2 = myaddon.newFactoryObjectInstance(10);
+console.log('sum of object values: ' + myaddon.sum(obj1, obj2));
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/persistent.md b/node_modules/node-pty/node_modules/nan/doc/persistent.md
new file mode 100644 (file)
index 0000000..bec9c3f
--- /dev/null
@@ -0,0 +1,296 @@
+## Persistent references
+
+An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
+
+Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
+
+ - <a href="#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
+ - <a href="#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
+ - <a href="#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
+ - <a href="#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
+ - <a href="#api_nan_global"><b><code>Nan::Global</code></b></a>
+ - <a href="#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
+ - <a href="#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
+
+Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
+
+<a name="api_nan_persistent_base"></a>
+### Nan::PersistentBase & v8::PersistentBase
+
+A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`.
+
+Definition:
+
+_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_
+
+```c++
+template<typename T> class PersistentBase {
+ public:
+  /**
+   * If non-empty, destroy the underlying storage cell
+   */
+  void Reset();
+
+  /**
+   * If non-empty, destroy the underlying storage cell and create a new one with
+   * the contents of another if it is also non-empty
+   */
+  template<typename S> void Reset(const v8::Local<S> &other);
+
+  /**
+   * If non-empty, destroy the underlying storage cell and create a new one with
+   * the contents of another if it is also non-empty
+   */
+  template<typename S> void Reset(const PersistentBase<S> &other);
+
+  /** Returns true if the handle is empty. */
+  bool IsEmpty() const;
+
+  /**
+   * If non-empty, destroy the underlying storage cell
+   * IsEmpty() will return true after this call.
+   */
+  void Empty();
+
+  template<typename S> bool operator==(const PersistentBase<S> &that);
+
+  template<typename S> bool operator==(const v8::Local<S> &that);
+
+  template<typename S> bool operator!=(const PersistentBase<S> &that);
+
+  template<typename S> bool operator!=(const v8::Local<S> &that);
+
+   /**
+   *  Install a finalization callback on this object.
+   *  NOTE: There is no guarantee as to *when* or even *if* the callback is
+   *  invoked. The invocation is performed solely on a best effort basis.
+   *  As always, GC-based finalization should *not* be relied upon for any
+   *  critical form of resource management! At the moment you can either
+   *  specify a parameter for the callback or the location of two internal
+   *  fields in the dying object.
+   */
+  template<typename P>
+  void SetWeak(P *parameter,
+               typename WeakCallbackInfo<P>::Callback callback,
+               WeakCallbackType type);
+
+  void ClearWeak();
+
+  /**
+   * Marks the reference to this object independent. Garbage collector is free
+   * to ignore any object groups containing this object. Weak callback for an
+   * independent handle should not assume that it will be preceded by a global
+   * GC prologue callback or followed by a global GC epilogue callback.
+   */
+  void MarkIndependent() const;
+
+  bool IsIndependent() const;
+
+  /** Checks if the handle holds the only reference to an object. */
+  bool IsNearDeath() const;
+
+  /** Returns true if the handle's reference is weak.  */
+  bool IsWeak() const
+};
+```
+
+See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/node-8.11/d4/dca/classv8_1_1_persistent_base.html) for further information.
+
+**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object:
+
+```c++
+v8::Local<v8::Object> object = Nan::New(persistent);
+```
+
+<a name="api_nan_non_copyable_persistent_traits"></a>
+### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits
+
+Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version.
+
+Definition:
+
+_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
+
+```c++
+template<typename T> class NonCopyablePersistentTraits {
+ public:
+  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
+
+  static const bool kResetInDestructor = false;
+
+  template<typename S, typename M>
+  static void Copy(const Persistent<S, M> &source,
+                   NonCopyablePersistent *dest);
+
+  template<typename O> static void Uncompilable();
+};
+```
+
+See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.11/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information.
+
+<a name="api_nan_copyable_persistent_traits"></a>
+### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits
+
+A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc..
+
+Definition:
+
+_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
+
+```c++
+template<typename T>
+class CopyablePersistentTraits {
+ public:
+  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
+
+  static const bool kResetInDestructor = true;
+
+  template<typename S, typename M>
+  static void Copy(const Persistent<S, M> &source,
+                   CopyablePersistent *dest);
+};
+```
+
+See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.11/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information.
+
+<a name="api_nan_persistent"></a>
+### Nan::Persistent
+
+A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`.
+
+Definition:
+
+```c++
+template<typename T, typename M = NonCopyablePersistentTraits<T> >
+class Persistent;
+
+template<typename T, typename M> class Persistent : public PersistentBase<T> {
+ public:
+ /**
+  * A Persistent with no storage cell.
+  */
+  Persistent();
+
+  /**
+   * Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a
+   * new storage cell is created pointing to the same object, and no flags are
+   * set.
+   */
+  template<typename S> Persistent(v8::Local<S> that);
+
+  /**
+   * Construct a Persistent from a Persistent. When the Persistent is non-empty,
+   * a new storage cell is created pointing to the same object, and no flags are
+   * set.
+   */
+  Persistent(const Persistent &that);
+
+  /**
+   * The copy constructors and assignment operator create a Persistent exactly
+   * as the Persistent constructor, but the Copy function from the traits class
+   * is called, allowing the setting of flags based on the copied Persistent.
+   */
+  Persistent &operator=(const Persistent &that);
+
+  template <typename S, typename M2>
+  Persistent &operator=(const Persistent<S, M2> &that);
+
+  /**
+   * The destructor will dispose the Persistent based on the kResetInDestructor
+   * flags in the traits class.  Since not calling dispose can result in a
+   * memory leak, it is recommended to always set this flag.
+   */
+  ~Persistent();
+};
+```
+
+See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/node-8.11/d2/d78/classv8_1_1_persistent.html) for further information.
+
+<a name="api_nan_global"></a>
+### Nan::Global
+
+A type of `PersistentBase` which has move semantics.
+
+```c++
+template<typename T> class Global : public PersistentBase<T> {
+ public:
+  /**
+   * A Global with no storage cell.
+   */
+  Global();
+
+  /**
+   * Construct a Global from a v8::Local. When the v8::Local is non-empty, a new
+   * storage cell is created pointing to the same object, and no flags are set.
+   */
+  template<typename S> Global(v8::Local<S> that);
+  /**
+   * Construct a Global from a PersistentBase. When the Persistent is non-empty,
+   * a new storage cell is created pointing to the same object, and no flags are
+   * set.
+   */
+  template<typename S> Global(const PersistentBase<S> &that);
+
+  /**
+   * Pass allows returning globals from functions, etc.
+   */
+  Global Pass();
+};
+```
+
+See the V8 documentation for [`Global`](https://v8docs.nodesource.com/node-8.11/d5/d40/classv8_1_1_global.html) for further information.
+
+<a name="api_nan_weak_callback_info"></a>
+### Nan::WeakCallbackInfo
+
+`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8.
+
+Definition:
+
+```c++
+template<typename T> class WeakCallbackInfo {
+ public:
+  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
+
+  v8::Isolate *GetIsolate() const;
+
+  /**
+   * Get the parameter that was associated with the weak handle.
+   */
+  T *GetParameter() const;
+
+  /**
+   * Get pointer from internal field, index can be 0 or 1.
+   */
+  void *GetInternalField(int index) const;
+};
+```
+
+Example usage:
+
+```c++
+void weakCallback(const WeakCallbackInfo<int> &data) {
+  int *parameter = data.GetParameter();
+  delete parameter;
+}
+
+Persistent<v8::Object> obj;
+int *data = new int(0);
+obj.SetWeak(data, callback, WeakCallbackType::kParameter);
+```
+
+See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/node-8.11/d8/d06/classv8_1_1_weak_callback_info.html) for further information.
+
+<a name="api_nan_weak_callback_type"></a>
+### Nan::WeakCallbackType
+
+Represents the type of a weak callback.
+A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`.
+A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase<v8::Object>` being made weak.
+Note that only `v8::Object`s and derivatives can have internal fields.
+
+Definition:
+
+```c++
+enum class WeakCallbackType { kParameter, kInternalFields };
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/scopes.md b/node_modules/node-pty/node_modules/nan/doc/scopes.md
new file mode 100644 (file)
index 0000000..27ab863
--- /dev/null
@@ -0,0 +1,73 @@
+## Scopes
+
+A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
+
+A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
+
+The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
+
+ - <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
+ - <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
+
+Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
+
+<a name="api_nan_handle_scope"></a>
+### Nan::HandleScope
+
+A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/node-8.11/d3/d95/classv8_1_1_handle_scope.html).
+
+Definition:
+
+```c++
+class Nan::HandleScope {
+ public:
+  Nan::HandleScope();
+  static int NumberOfHandles();
+};
+```
+
+Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself.
+
+Example:
+
+```c++
+// new object is created, it needs a new scope:
+void Pointless() {
+  Nan::HandleScope scope;
+  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
+}
+
+// JavaScript-accessible method already has a HandleScope
+NAN_METHOD(Pointless2) {
+  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
+}
+```
+
+<a name="api_nan_escapable_handle_scope"></a>
+### Nan::EscapableHandleScope
+
+Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it.
+
+Definition:
+
+```c++
+class Nan::EscapableHandleScope {
+ public:
+  Nan::EscapableHandleScope();
+  static int NumberOfHandles();
+  template<typename T> v8::Local<T> Escape(v8::Local<T> value);
+}
+```
+
+Use `Escape(value)` to return the object.
+
+Example:
+
+```c++
+v8::Local<v8::Object> EmptyObj() {
+  Nan::EscapableHandleScope scope;
+  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
+  return scope.Escape(obj);
+}
+```
+
diff --git a/node_modules/node-pty/node_modules/nan/doc/script.md b/node_modules/node-pty/node_modules/nan/doc/script.md
new file mode 100644 (file)
index 0000000..945398f
--- /dev/null
@@ -0,0 +1,38 @@
+## Script
+
+NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
+
+ - <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
+ - <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
+
+
+<a name="api_nan_compile_script"></a>
+### Nan::CompileScript()
+
+A wrapper around [`v8::ScriptCompiler::Compile()`](https://v8docs.nodesource.com/node-8.11/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b).
+
+Note that `Nan::BoundScript` is an alias for `v8::Script`.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(
+    v8::Local<v8::String> s,
+    const v8::ScriptOrigin& origin);
+Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s);
+```
+
+
+<a name="api_nan_run_script"></a>
+### Nan::RunScript()
+
+Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`.
+
+Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8.
+
+Signature:
+
+```c++
+Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script)
+Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script) 
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/string_bytes.md b/node_modules/node-pty/node_modules/nan/doc/string_bytes.md
new file mode 100644 (file)
index 0000000..7c1bd32
--- /dev/null
@@ -0,0 +1,62 @@
+## Strings & Bytes
+
+Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
+
+ - <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
+ - <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
+ - <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
+ - <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
+
+
+<a name="api_nan_encoding"></a>
+### Nan::Encoding
+
+An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node.
+
+Definition:
+
+```c++
+enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER }
+```
+
+
+<a name="api_nan_encode"></a>
+### Nan::Encode()
+
+A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node.
+
+Signature:
+
+```c++
+v8::Local<v8::Value> Nan::Encode(const void *buf,
+                                 size_t len,
+                                 enum Nan::Encoding encoding = BINARY);
+```
+
+
+<a name="api_nan_decode_bytes"></a>
+### Nan::DecodeBytes()
+
+A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node.
+
+Signature:
+
+```c++
+ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val,
+                         enum Nan::Encoding encoding = BINARY);
+```
+
+
+<a name="api_nan_decode_write"></a>
+### Nan::DecodeWrite()
+
+A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node.
+
+Signature:
+
+```c++
+ssize_t Nan::DecodeWrite(char *buf,
+                         size_t len,
+                         v8::Local<v8::Value> val,
+                         enum Nan::Encoding encoding = BINARY);
+```
diff --git a/node_modules/node-pty/node_modules/nan/doc/v8_internals.md b/node_modules/node-pty/node_modules/nan/doc/v8_internals.md
new file mode 100644 (file)
index 0000000..88bd2de
--- /dev/null
@@ -0,0 +1,199 @@
+## V8 internals
+
+The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
+
+ - <a href="#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
+ - <a href="#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
+ - <a href="#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
+ - <a href="#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
+ - <a href="#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
+ - <a href="#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
+ - <a href="#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
+ - <a href="#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
+ - <a href="#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
+ - <a href="#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
+ - <a href="#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
+ - <a href="#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
+ - <a href="#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
+ - <a href="#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
+ - <a href="#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
+
+
+<a name="api_nan_gc_callback"></a>
+### NAN_GC_CALLBACK(callbackname)
+
+Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`.
+
+```c++
+static Nan::Persistent<Function> callback;
+
+NAN_GC_CALLBACK(gcPrologueCallback) {
+  v8::Local<Value> argv[] = { Nan::New("prologue").ToLocalChecked() };
+  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv);
+}
+
+NAN_METHOD(Hook) {
+  callback.Reset(To<Function>(args[0]).ToLocalChecked());
+  Nan::AddGCPrologueCallback(gcPrologueCallback);
+  info.GetReturnValue().Set(info.Holder());
+}
+```
+
+<a name="api_nan_add_gc_epilogue_callback"></a>
+### Nan::AddGCEpilogueCallback()
+
+Signature:
+
+```c++
+void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll)
+```
+
+Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a580f976e4290cead62c2fc4dd396be3e).
+
+<a name="api_nan_remove_gc_epilogue_callback"></a>
+### Nan::RemoveGCEpilogueCallback()
+
+Signature:
+
+```c++
+void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback)
+```
+
+Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#adca9294555a3908e9f23c7bb0f0f284c).
+
+<a name="api_nan_add_gc_prologue_callback"></a>
+### Nan::AddGCPrologueCallback()
+
+Signature:
+
+```c++
+void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback)
+```
+
+Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a6dbef303603ebdb03da6998794ea05b8).
+
+<a name="api_nan_remove_gc_prologue_callback"></a>
+### Nan::RemoveGCPrologueCallback()
+
+Signature:
+
+```c++
+void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback)
+```
+
+Calls V8's [`RemoveGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a5f72c7cda21415ce062bbe5c58abe09e).
+
+<a name="api_nan_get_heap_statistics"></a>
+### Nan::GetHeapStatistics()
+
+Signature:
+
+```c++
+void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics)
+```
+
+Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34).
+
+<a name="api_nan_set_counter_function"></a>
+### Nan::SetCounterFunction()
+
+Signature:
+
+```c++
+void Nan::SetCounterFunction(v8::CounterLookupCallback cb)
+```
+
+Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94).
+
+<a name="api_nan_set_create_histogram_function"></a>
+### Nan::SetCreateHistogramFunction()
+
+Signature:
+
+```c++
+void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb) 
+```
+
+Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732).
+
+<a name="api_nan_set_add_histogram_sample_function"></a>
+### Nan::SetAddHistogramSampleFunction()
+
+Signature:
+
+```c++
+void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) 
+```
+
+Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea).
+
+<a name="api_nan_idle_notification"></a>
+### Nan::IdleNotification()
+
+Signature:
+
+```c++
+bool Nan::IdleNotification(int idle_time_in_ms)
+```
+
+Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version.
+
+<a name="api_nan_low_memory_notification"></a>
+### Nan::LowMemoryNotification()
+
+Signature:
+
+```c++
+void Nan::LowMemoryNotification() 
+```
+
+Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f).
+
+<a name="api_nan_context_disposed_notification"></a>
+### Nan::ContextDisposedNotification()
+
+Signature:
+
+```c++
+void Nan::ContextDisposedNotification()
+```
+
+Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b).
+
+<a name="api_nan_get_internal_field_pointer"></a>
+### Nan::GetInternalFieldPointer()
+
+Gets a pointer to the internal field with at `index` from a V8 `Object` handle.
+
+Signature:
+
+```c++
+void* Nan::GetInternalFieldPointer(v8::Local<v8::Object> object, int index) 
+```
+
+Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#a580ea84afb26c005d6762eeb9e3c308f) depending on the version of V8.
+
+<a name="api_nan_set_internal_field_pointer"></a>
+### Nan::SetInternalFieldPointer()
+
+Sets the value of the internal field at `index` on a V8 `Object` handle.
+
+Signature:
+
+```c++
+void Nan::SetInternalFieldPointer(v8::Local<v8::Object> object, int index, void* value)
+```
+
+Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/node-8.11/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8.
+
+<a name="api_nan_adjust_external_memory"></a>
+### Nan::AdjustExternalMemory()
+
+Signature:
+
+```c++
+int Nan::AdjustExternalMemory(int bytesChange)
+```
+
+Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e).
+
diff --git a/node_modules/node-pty/node_modules/nan/doc/v8_misc.md b/node_modules/node-pty/node_modules/nan/doc/v8_misc.md
new file mode 100644 (file)
index 0000000..8e2db20
--- /dev/null
@@ -0,0 +1,85 @@
+## Miscellaneous V8 Helpers
+
+ - <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
+ - <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
+ - <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
+ - <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
+ - <a href="#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
+
+
+<a name="api_nan_utf8_string"></a>
+### Nan::Utf8String
+
+Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object.
+
+An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/node-8.11/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8.
+
+Definition:
+
+```c++
+class Nan::Utf8String {
+ public:
+  Nan::Utf8String(v8::Local<v8::Value> from);
+
+  int length() const;
+
+  char* operator*();
+  const char* operator*() const;
+};
+```
+
+<a name="api_nan_get_current_context"></a>
+### Nan::GetCurrentContext()
+
+A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8.
+
+Signature:
+
+```c++
+v8::Local<v8::Context> Nan::GetCurrentContext()
+```
+
+<a name="api_nan_set_isolate_data"></a>
+### Nan::SetIsolateData()
+
+A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36).
+
+Signature:
+
+```c++
+void Nan::SetIsolateData(v8::Isolate *isolate, T *data)
+```
+
+
+<a name="api_nan_get_isolate_data"></a>
+### Nan::GetIsolateData()
+
+A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/node-8.11/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257).
+
+Signature:
+
+```c++
+T *Nan::GetIsolateData(v8::Isolate *isolate)
+```
+
+<a name="api_nan_typedarray_contents"></a>
+### Nan::TypedArrayContents<T>
+
+A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++.  If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0.  If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail.
+
+Note that you must store a reference to the `array` object while you are accessing its contents.
+
+Definition:
+
+```c++
+template<typename T>
+class Nan::TypedArrayContents {
+ public:
+  TypedArrayContents(v8::Local<Value> array);
+
+  size_t length() const;
+
+  T* const operator*();
+  const T* const operator*() const;
+};
+```
diff --git a/node_modules/node-pty/node_modules/nan/include_dirs.js b/node_modules/node-pty/node_modules/nan/include_dirs.js
new file mode 100644 (file)
index 0000000..4f1dfb4
--- /dev/null
@@ -0,0 +1 @@
+console.log(require('path').relative('.', __dirname));
diff --git a/node_modules/node-pty/node_modules/nan/nan.h b/node_modules/node-pty/node_modules/nan/nan.h
new file mode 100644 (file)
index 0000000..514115d
--- /dev/null
@@ -0,0 +1,2892 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors:
+ *   - Rod Vagg <https://github.com/rvagg>
+ *   - Benjamin Byholm <https://github.com/kkoopa>
+ *   - Trevor Norris <https://github.com/trevnorris>
+ *   - Nathan Rajlich <https://github.com/TooTallNate>
+ *   - Brett Lawson <https://github.com/brett19>
+ *   - Ben Noordhuis <https://github.com/bnoordhuis>
+ *   - David Siegel <https://github.com/agnat>
+ *   - Michael Ira Krufky <https://github.com/mkrufky>
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ *
+ * Version 2.14.0: current Node 12.2.0, Node 12: 0.12.18, Node 10: 0.10.48, iojs: 3.3.1
+ *
+ * See https://github.com/nodejs/nan for the latest update to this file
+ **********************************************************************************/
+
+#ifndef NAN_H_
+#define NAN_H_
+
+#include <node_version.h>
+
+#define NODE_0_10_MODULE_VERSION 11
+#define NODE_0_12_MODULE_VERSION 14
+#define ATOM_0_21_MODULE_VERSION 41
+#define IOJS_1_0_MODULE_VERSION  42
+#define IOJS_1_1_MODULE_VERSION  43
+#define IOJS_2_0_MODULE_VERSION  44
+#define IOJS_3_0_MODULE_VERSION  45
+#define NODE_4_0_MODULE_VERSION  46
+#define NODE_5_0_MODULE_VERSION  47
+#define NODE_6_0_MODULE_VERSION  48
+#define NODE_7_0_MODULE_VERSION  51
+#define NODE_8_0_MODULE_VERSION  57
+#define NODE_9_0_MODULE_VERSION  59
+#define NODE_10_0_MODULE_VERSION 64
+#define NODE_11_0_MODULE_VERSION 67
+#define NODE_12_0_MODULE_VERSION 72
+
+#ifdef _MSC_VER
+# define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800)
+#else
+# define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L)
+#endif
+
+#if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11
+# error This version of node/NAN/v8 requires a C++11 compiler
+#endif
+
+#include <uv.h>
+#include <node.h>
+#include <node_buffer.h>
+#include <node_object_wrap.h>
+#include <algorithm>
+#include <cstring>
+#include <climits>
+#include <cstdlib>
+#include <utility>
+#if defined(_MSC_VER)
+# pragma warning( push )
+# pragma warning( disable : 4530 )
+# include <queue>
+# include <string>
+# include <vector>
+# pragma warning( pop )
+#else
+# include <queue>
+# include <string>
+# include <vector>
+#endif
+
+// uv helpers
+#ifdef UV_VERSION_MAJOR
+# ifndef UV_VERSION_PATCH
+#  define UV_VERSION_PATCH 0
+# endif
+# define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \
+                         (UV_VERSION_MINOR <<  8) | \
+                         (UV_VERSION_PATCH))
+#else
+# define NAUV_UVVERSION 0x000b00
+#endif
+
+#if NAUV_UVVERSION < 0x000b0b
+# ifdef WIN32
+#  include <windows.h>
+# else
+#  include <pthread.h>
+# endif
+#endif
+
+namespace Nan {
+
+#define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b)
+#define NAN_CONCAT_HELPER(a, b) a##b
+
+#define NAN_INLINE inline  // TODO(bnoordhuis) Remove in v3.0.0.
+
+#if defined(__GNUC__) && \
+    !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
+# define NAN_DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER) && \
+    !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
+# define NAN_DEPRECATED __declspec(deprecated)
+#else
+# define NAN_DEPRECATED
+#endif
+
+#if NAN_HAS_CPLUSPLUS_11
+# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
+# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
+# define NAN_DISALLOW_MOVE(CLASS)                                              \
+    CLASS(CLASS&&) = delete;  /* NOLINT(build/c++11) */                        \
+    void operator=(CLASS&&) = delete;
+#else
+# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&);
+# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&);
+# define NAN_DISALLOW_MOVE(CLASS)
+#endif
+
+#define NAN_DISALLOW_ASSIGN_COPY(CLASS)                                        \
+    NAN_DISALLOW_ASSIGN(CLASS)                                                 \
+    NAN_DISALLOW_COPY(CLASS)
+
+#define NAN_DISALLOW_ASSIGN_MOVE(CLASS)                                        \
+    NAN_DISALLOW_ASSIGN(CLASS)                                                 \
+    NAN_DISALLOW_MOVE(CLASS)
+
+#define NAN_DISALLOW_COPY_MOVE(CLASS)                                          \
+    NAN_DISALLOW_COPY(CLASS)                                                   \
+    NAN_DISALLOW_MOVE(CLASS)
+
+#define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS)                                   \
+    NAN_DISALLOW_ASSIGN(CLASS)                                                 \
+    NAN_DISALLOW_COPY(CLASS)                                                   \
+    NAN_DISALLOW_MOVE(CLASS)
+
+#define TYPE_CHECK(T, S)                                                       \
+    while (false) {                                                            \
+      *(static_cast<T *volatile *>(0)) = static_cast<S*>(0);                   \
+    }
+
+//=== RegistrationFunction =====================================================
+
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+  typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
+#else
+  typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
+#endif
+
+#define NAN_MODULE_INIT(name)                                                  \
+    void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target)
+
+#if NODE_MAJOR_VERSION >= 10 || \
+    NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3
+#define NAN_MODULE_WORKER_ENABLED(module_name, registration)                   \
+    extern "C" NODE_MODULE_EXPORT void                                         \
+      NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)(                 \
+        v8::Local<v8::Object> exports, v8::Local<v8::Value> module,            \
+        v8::Local<v8::Context> context)                                        \
+    {                                                                          \
+        registration(exports);                                                 \
+    }
+#else
+#define NAN_MODULE_WORKER_ENABLED(module_name, registration)                   \
+    NODE_MODULE(module_name, registration)
+#endif
+
+//=== CallbackInfo =============================================================
+
+#include "nan_callbacks.h"  // NOLINT(build/include)
+
+//==============================================================================
+
+#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION)
+typedef v8::Script             UnboundScript;
+typedef v8::Script             BoundScript;
+#else
+typedef v8::UnboundScript      UnboundScript;
+typedef v8::Script             BoundScript;
+#endif
+
+#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION)
+typedef v8::String::ExternalAsciiStringResource
+    ExternalOneByteStringResource;
+#else
+typedef v8::String::ExternalOneByteStringResource
+    ExternalOneByteStringResource;
+#endif
+
+#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
+template<typename T>
+class NonCopyablePersistentTraits :
+    public v8::NonCopyablePersistentTraits<T> {};
+template<typename T>
+class CopyablePersistentTraits :
+    public v8::CopyablePersistentTraits<T> {};
+
+template<typename T>
+class PersistentBase :
+    public v8::PersistentBase<T> {};
+
+template<typename T, typename M = v8::NonCopyablePersistentTraits<T> >
+class Persistent;
+#else
+template<typename T> class NonCopyablePersistentTraits;
+template<typename T> class PersistentBase;
+template<typename T, typename P> class WeakCallbackData;
+template<typename T, typename M = NonCopyablePersistentTraits<T> >
+class Persistent;
+#endif  // NODE_MODULE_VERSION
+
+template<typename T>
+class Maybe {
+ public:
+  inline bool IsNothing() const { return !has_value_; }
+  inline bool IsJust() const { return has_value_; }
+
+  inline T ToChecked() const { return FromJust(); }
+  inline void Check() const { FromJust(); }
+
+  inline bool To(T* out) const {
+    if (IsJust()) *out = value_;
+    return IsJust();
+  }
+
+  inline T FromJust() const {
+#if defined(V8_ENABLE_CHECKS)
+    assert(IsJust() && "FromJust is Nothing");
+#endif  // V8_ENABLE_CHECKS
+    return value_;
+  }
+
+  inline T FromMaybe(const T& default_value) const {
+    return has_value_ ? value_ : default_value;
+  }
+
+  inline bool operator==(const Maybe &other) const {
+    return (IsJust() == other.IsJust()) &&
+        (!IsJust() || FromJust() == other.FromJust());
+  }
+
+  inline bool operator!=(const Maybe &other) const {
+    return !operator==(other);
+  }
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+  // Allow implicit conversions from v8::Maybe<T> to Nan::Maybe<T>.
+  Maybe(const v8::Maybe<T>& that)  // NOLINT(runtime/explicit)
+    : has_value_(that.IsJust())
+    , value_(that.FromMaybe(T())) {}
+#endif
+
+ private:
+  Maybe() : has_value_(false) {}
+  explicit Maybe(const T& t) : has_value_(true), value_(t) {}
+  bool has_value_;
+  T value_;
+
+  template<typename U>
+  friend Maybe<U> Nothing();
+  template<typename U>
+  friend Maybe<U> Just(const U& u);
+};
+
+template<typename T>
+inline Maybe<T> Nothing() {
+  return Maybe<T>();
+}
+
+template<typename T>
+inline Maybe<T> Just(const T& t) {
+  return Maybe<T>(t);
+}
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+# include "nan_maybe_43_inl.h"  // NOLINT(build/include)
+#else
+# include "nan_maybe_pre_43_inl.h"  // NOLINT(build/include)
+#endif
+
+#include "nan_converters.h"  // NOLINT(build/include)
+#include "nan_new.h"  // NOLINT(build/include)
+
+#if NAUV_UVVERSION < 0x000b17
+#define NAUV_WORK_CB(func) \
+    void func(uv_async_t *async, int)
+#else
+#define NAUV_WORK_CB(func) \
+    void func(uv_async_t *async)
+#endif
+
+#if NAUV_UVVERSION >= 0x000b0b
+
+typedef uv_key_t nauv_key_t;
+
+inline int nauv_key_create(nauv_key_t *key) {
+  return uv_key_create(key);
+}
+
+inline void nauv_key_delete(nauv_key_t *key) {
+  uv_key_delete(key);
+}
+
+inline void* nauv_key_get(nauv_key_t *key) {
+  return uv_key_get(key);
+}
+
+inline void nauv_key_set(nauv_key_t *key, void *value) {
+  uv_key_set(key, value);
+}
+
+#else
+
+/* Implement thread local storage for older versions of libuv.
+ * This is essentially a backport of libuv commit 5d2434bf
+ * written by Ben Noordhuis, adjusted for names and inline.
+ */
+
+#ifndef WIN32
+
+typedef pthread_key_t nauv_key_t;
+
+inline int nauv_key_create(nauv_key_t* key) {
+  return -pthread_key_create(key, NULL);
+}
+
+inline void nauv_key_delete(nauv_key_t* key) {
+  if (pthread_key_delete(*key))
+    abort();
+}
+
+inline void* nauv_key_get(nauv_key_t* key) {
+  return pthread_getspecific(*key);
+}
+
+inline void nauv_key_set(nauv_key_t* key, void* value) {
+  if (pthread_setspecific(*key, value))
+    abort();
+}
+
+#else
+
+typedef struct {
+  DWORD tls_index;
+} nauv_key_t;
+
+inline int nauv_key_create(nauv_key_t* key) {
+  key->tls_index = TlsAlloc();
+  if (key->tls_index == TLS_OUT_OF_INDEXES)
+    return UV_ENOMEM;
+  return 0;
+}
+
+inline void nauv_key_delete(nauv_key_t* key) {
+  if (TlsFree(key->tls_index) == FALSE)
+    abort();
+  key->tls_index = TLS_OUT_OF_INDEXES;
+}
+
+inline void* nauv_key_get(nauv_key_t* key) {
+  void* value = TlsGetValue(key->tls_index);
+  if (value == NULL)
+    if (GetLastError() != ERROR_SUCCESS)
+      abort();
+  return value;
+}
+
+inline void nauv_key_set(nauv_key_t* key, void* value) {
+  if (TlsSetValue(key->tls_index, value) == FALSE)
+    abort();
+}
+
+#endif
+#endif
+
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+template<typename T>
+v8::Local<T> New(v8::Handle<T>);
+#endif
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+  typedef v8::WeakCallbackType WeakCallbackType;
+#else
+struct WeakCallbackType {
+  enum E {kParameter, kInternalFields};
+  E type;
+  WeakCallbackType(E other) : type(other) {}  // NOLINT(runtime/explicit)
+  inline bool operator==(E other) { return other == this->type; }
+  inline bool operator!=(E other) { return !operator==(other); }
+};
+#endif
+
+template<typename P> class WeakCallbackInfo;
+
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+# include "nan_persistent_12_inl.h"  // NOLINT(build/include)
+#else
+# include "nan_persistent_pre_12_inl.h"  // NOLINT(build/include)
+#endif
+
+namespace imp {
+  static const size_t kMaxLength = 0x3fffffff;
+  // v8::String::REPLACE_INVALID_UTF8 was introduced
+  // in node.js v0.10.29 and v0.8.27.
+#if NODE_MAJOR_VERSION > 0 || \
+    NODE_MINOR_VERSION > 10 || \
+    NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \
+    NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27
+  static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
+#else
+  static const unsigned kReplaceInvalidUtf8 = 0;
+#endif
+}  // end of namespace imp
+
+//=== HandleScope ==============================================================
+
+class HandleScope {
+  v8::HandleScope scope;
+
+ public:
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  inline HandleScope() : scope(v8::Isolate::GetCurrent()) {}
+  inline static int NumberOfHandles() {
+    return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
+  }
+#else
+  inline HandleScope() : scope() {}
+  inline static int NumberOfHandles() {
+    return v8::HandleScope::NumberOfHandles();
+  }
+#endif
+
+ private:
+  // Make it hard to create heap-allocated or illegal handle scopes by
+  // disallowing certain operations.
+  HandleScope(const HandleScope &);
+  void operator=(const HandleScope &);
+  void *operator new(size_t size);
+  void operator delete(void *, size_t) {
+    abort();
+  }
+};
+
+class EscapableHandleScope {
+ public:
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {}
+
+  inline static int NumberOfHandles() {
+    return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
+  }
+
+  template<typename T>
+  inline v8::Local<T> Escape(v8::Local<T> value) {
+    return scope.Escape(value);
+  }
+
+ private:
+  v8::EscapableHandleScope scope;
+#else
+  inline EscapableHandleScope() : scope() {}
+
+  inline static int NumberOfHandles() {
+    return v8::HandleScope::NumberOfHandles();
+  }
+
+  template<typename T>
+  inline v8::Local<T> Escape(v8::Local<T> value) {
+    return scope.Close(value);
+  }
+
+ private:
+  v8::HandleScope scope;
+#endif
+
+ private:
+  // Make it hard to create heap-allocated or illegal handle scopes by
+  // disallowing certain operations.
+  EscapableHandleScope(const EscapableHandleScope &);
+  void operator=(const EscapableHandleScope &);
+  void *operator new(size_t size);
+  void operator delete(void *, size_t) {
+    abort();
+  }
+};
+
+//=== TryCatch =================================================================
+
+class TryCatch {
+  v8::TryCatch try_catch_;
+  friend void FatalException(const TryCatch&);
+
+ public:
+#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+  TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {}
+#endif
+
+  inline bool HasCaught() const { return try_catch_.HasCaught(); }
+
+  inline bool CanContinue() const { return try_catch_.CanContinue(); }
+
+  inline v8::Local<v8::Value> ReThrow() {
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    return New(try_catch_.ReThrow());
+#else
+    return try_catch_.ReThrow();
+#endif
+  }
+
+  inline v8::Local<v8::Value> Exception() const {
+    return try_catch_.Exception();
+  }
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+  inline v8::MaybeLocal<v8::Value> StackTrace() const {
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+    return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext())
+                            .FromMaybe(v8::Local<v8::Value>()));
+  }
+#else
+  inline MaybeLocal<v8::Value> StackTrace() const {
+    return try_catch_.StackTrace();
+  }
+#endif
+
+  inline v8::Local<v8::Message> Message() const {
+    return try_catch_.Message();
+  }
+
+  inline void Reset() { try_catch_.Reset(); }
+
+  inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); }
+
+  inline void SetCaptureMessage(bool value) {
+    try_catch_.SetCaptureMessage(value);
+  }
+};
+
+v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
+                                  v8::Local<v8::Function> func,
+                                  int argc,
+                                  v8::Local<v8::Value>* argv);
+v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
+                                  v8::Local<v8::String> symbol,
+                                  int argc,
+                                  v8::Local<v8::Value>* argv);
+v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
+                                  const char* method,
+                                  int argc,
+                                  v8::Local<v8::Value>* argv);
+
+// === AsyncResource ===========================================================
+
+class AsyncResource {
+ public:
+  AsyncResource(
+      v8::Local<v8::String> name
+    , v8::Local<v8::Object> resource = New<v8::Object>()) {
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+
+    if (resource.IsEmpty()) {
+      resource = New<v8::Object>();
+    }
+
+    context = node::EmitAsyncInit(isolate, resource, name);
+#endif
+  }
+
+  AsyncResource(
+      const char* name
+    , v8::Local<v8::Object> resource = New<v8::Object>()) {
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+
+    if (resource.IsEmpty()) {
+      resource = New<v8::Object>();
+    }
+
+    v8::Local<v8::String> name_string =
+        New<v8::String>(name).ToLocalChecked();
+    context = node::EmitAsyncInit(isolate, resource, name_string);
+#endif
+  }
+
+  ~AsyncResource() {
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    node::EmitAsyncDestroy(isolate, context);
+#endif
+  }
+
+  inline MaybeLocal<v8::Value> runInAsyncScope(
+      v8::Local<v8::Object> target
+    , v8::Local<v8::Function> func
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
+    return MakeCallback(target, func, argc, argv);
+#else
+    return node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, func, argc, argv, context);
+#endif
+  }
+
+  inline MaybeLocal<v8::Value> runInAsyncScope(
+      v8::Local<v8::Object> target
+    , v8::Local<v8::String> symbol
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
+    return MakeCallback(target, symbol, argc, argv);
+#else
+    return node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, symbol, argc, argv, context);
+#endif
+  }
+
+  inline MaybeLocal<v8::Value> runInAsyncScope(
+      v8::Local<v8::Object> target
+    , const char* method
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
+    return MakeCallback(target, method, argc, argv);
+#else
+    return node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, method, argc, argv, context);
+#endif
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource)
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+  node::async_context context;
+#endif
+};
+
+inline uv_loop_t* GetCurrentEventLoop() {
+#if NODE_MAJOR_VERSION >= 10 || \
+  NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \
+  NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10
+    return node::GetCurrentEventLoop(v8::Isolate::GetCurrent());
+#else
+    return uv_default_loop();
+#endif
+}
+
+//============ =================================================================
+
+/* node 0.12  */
+#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
+  inline
+  void SetCounterFunction(v8::CounterLookupCallback cb) {
+    v8::Isolate::GetCurrent()->SetCounterFunction(cb);
+  }
+
+  inline
+  void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
+    v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb);
+  }
+
+  inline
+  void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
+    v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb);
+  }
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+  inline bool IdleNotification(int idle_time_in_ms) {
+    return v8::Isolate::GetCurrent()->IdleNotificationDeadline(
+        idle_time_in_ms * 0.001);
+  }
+# else
+  inline bool IdleNotification(int idle_time_in_ms) {
+    return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms);
+  }
+#endif
+
+  inline void LowMemoryNotification() {
+    v8::Isolate::GetCurrent()->LowMemoryNotification();
+  }
+
+  inline void ContextDisposedNotification() {
+    v8::Isolate::GetCurrent()->ContextDisposedNotification();
+  }
+#else
+  inline
+  void SetCounterFunction(v8::CounterLookupCallback cb) {
+    v8::V8::SetCounterFunction(cb);
+  }
+
+  inline
+  void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
+    v8::V8::SetCreateHistogramFunction(cb);
+  }
+
+  inline
+  void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
+    v8::V8::SetAddHistogramSampleFunction(cb);
+  }
+
+  inline bool IdleNotification(int idle_time_in_ms) {
+    return v8::V8::IdleNotification(idle_time_in_ms);
+  }
+
+  inline void LowMemoryNotification() {
+    v8::V8::LowMemoryNotification();
+  }
+
+  inline void ContextDisposedNotification() {
+    v8::V8::ContextDisposedNotification();
+  }
+#endif
+
+#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)  // Node 0.12
+  inline v8::Local<v8::Primitive> Undefined() {
+# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent())));
+# else
+    return v8::Undefined(v8::Isolate::GetCurrent());
+# endif
+  }
+
+  inline v8::Local<v8::Primitive> Null() {
+# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent())));
+# else
+    return v8::Null(v8::Isolate::GetCurrent());
+# endif
+  }
+
+  inline v8::Local<v8::Boolean> True() {
+# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::True(v8::Isolate::GetCurrent())));
+# else
+    return v8::True(v8::Isolate::GetCurrent());
+# endif
+  }
+
+  inline v8::Local<v8::Boolean> False() {
+# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::False(v8::Isolate::GetCurrent())));
+# else
+    return v8::False(v8::Isolate::GetCurrent());
+# endif
+  }
+
+  inline v8::Local<v8::String> EmptyString() {
+    return v8::String::Empty(v8::Isolate::GetCurrent());
+  }
+
+  inline int AdjustExternalMemory(int bc) {
+    return static_cast<int>(
+        v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc));
+  }
+
+  inline void SetTemplate(
+      v8::Local<v8::Template> templ
+    , const char *name
+    , v8::Local<v8::Data> value) {
+    templ->Set(v8::Isolate::GetCurrent(), name, value);
+  }
+
+  inline void SetTemplate(
+      v8::Local<v8::Template> templ
+    , v8::Local<v8::String> name
+    , v8::Local<v8::Data> value
+    , v8::PropertyAttribute attributes) {
+    templ->Set(name, value, attributes);
+  }
+
+  inline v8::Local<v8::Context> GetCurrentContext() {
+    return v8::Isolate::GetCurrent()->GetCurrentContext();
+  }
+
+  inline void* GetInternalFieldPointer(
+      v8::Local<v8::Object> object
+    , int index) {
+    return object->GetAlignedPointerFromInternalField(index);
+  }
+
+  inline void SetInternalFieldPointer(
+      v8::Local<v8::Object> object
+    , int index
+    , void* value) {
+    object->SetAlignedPointerInInternalField(index, value);
+  }
+
+# define NAN_GC_CALLBACK(name)                                                 \
+    void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags)
+
+#if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION
+  typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback;
+  typedef v8::Isolate::GCPrologueCallback GCPrologueCallback;
+#else
+  typedef v8::Isolate::GCCallback GCEpilogueCallback;
+  typedef v8::Isolate::GCCallback GCPrologueCallback;
+#endif
+
+  inline void AddGCEpilogueCallback(
+      GCEpilogueCallback callback
+    , v8::GCType gc_type_filter = v8::kGCTypeAll) {
+    v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter);
+  }
+
+  inline void RemoveGCEpilogueCallback(
+      GCEpilogueCallback callback) {
+    v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback);
+  }
+
+  inline void AddGCPrologueCallback(
+      GCPrologueCallback callback
+    , v8::GCType gc_type_filter = v8::kGCTypeAll) {
+    v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter);
+  }
+
+  inline void RemoveGCPrologueCallback(
+      GCPrologueCallback callback) {
+    v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback);
+  }
+
+  inline void GetHeapStatistics(
+      v8::HeapStatistics *heap_statistics) {
+    v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics);
+  }
+
+# define X(NAME)                                                               \
+    inline v8::Local<v8::Value> NAME(const char *msg) {                        \
+      EscapableHandleScope scope;                                              \
+      return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked()));     \
+    }                                                                          \
+                                                                               \
+    inline                                                                     \
+    v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) {                     \
+      return v8::Exception::NAME(msg);                                         \
+    }                                                                          \
+                                                                               \
+    inline void Throw ## NAME(const char *msg) {                               \
+      HandleScope scope;                                                       \
+      v8::Isolate::GetCurrent()->ThrowException(                               \
+          v8::Exception::NAME(New(msg).ToLocalChecked()));                     \
+    }                                                                          \
+                                                                               \
+    inline void Throw ## NAME(v8::Local<v8::String> msg) {                     \
+      HandleScope scope;                                                       \
+      v8::Isolate::GetCurrent()->ThrowException(                               \
+          v8::Exception::NAME(msg));                                           \
+    }
+
+  X(Error)
+  X(RangeError)
+  X(ReferenceError)
+  X(SyntaxError)
+  X(TypeError)
+
+# undef X
+
+  inline void ThrowError(v8::Local<v8::Value> error) {
+    v8::Isolate::GetCurrent()->ThrowException(error);
+  }
+
+  inline MaybeLocal<v8::Object> NewBuffer(
+      char *data
+    , size_t length
+#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
+    , node::Buffer::FreeCallback callback
+#else
+    , node::smalloc::FreeCallback callback
+#endif
+    , void *hint
+  ) {
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(length <= imp::kMaxLength && "too large buffer");
+#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
+    return node::Buffer::New(
+        v8::Isolate::GetCurrent(), data, length, callback, hint);
+#else
+    return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback,
+                             hint);
+#endif
+  }
+
+  inline MaybeLocal<v8::Object> CopyBuffer(
+      const char *data
+    , uint32_t size
+  ) {
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(size <= imp::kMaxLength && "too large buffer");
+#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
+    return node::Buffer::Copy(
+        v8::Isolate::GetCurrent(), data, size);
+#else
+    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
+#endif
+  }
+
+  inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(size <= imp::kMaxLength && "too large buffer");
+#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
+    return node::Buffer::New(
+        v8::Isolate::GetCurrent(), size);
+#else
+    return node::Buffer::New(v8::Isolate::GetCurrent(), size);
+#endif
+  }
+
+  inline MaybeLocal<v8::Object> NewBuffer(
+      char* data
+    , uint32_t size
+  ) {
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(size <= imp::kMaxLength && "too large buffer");
+#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
+    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
+#else
+    return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
+#endif
+  }
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+  inline MaybeLocal<v8::String>
+  NewOneByteString(const uint8_t * value, int length = -1) {
+    return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
+          v8::NewStringType::kNormal, length);
+  }
+
+  inline MaybeLocal<BoundScript> CompileScript(
+      v8::Local<v8::String> s
+    , const v8::ScriptOrigin& origin
+  ) {
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+    v8::ScriptCompiler::Source source(s, origin);
+    return scope.Escape(
+        v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
+            .FromMaybe(v8::Local<BoundScript>()));
+  }
+
+  inline MaybeLocal<BoundScript> CompileScript(
+      v8::Local<v8::String> s
+  ) {
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+    v8::ScriptCompiler::Source source(s);
+    return scope.Escape(
+        v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
+            .FromMaybe(v8::Local<BoundScript>()));
+  }
+
+  inline MaybeLocal<v8::Value> RunScript(
+      v8::Local<UnboundScript> script
+  ) {
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+    return scope.Escape(script->BindToCurrentContext()
+                            ->Run(isolate->GetCurrentContext())
+                            .FromMaybe(v8::Local<v8::Value>()));
+  }
+
+  inline MaybeLocal<v8::Value> RunScript(
+      v8::Local<BoundScript> script
+  ) {
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+    return scope.Escape(script->Run(isolate->GetCurrentContext())
+                            .FromMaybe(v8::Local<v8::Value>()));
+  }
+#else
+  inline MaybeLocal<v8::String>
+  NewOneByteString(const uint8_t * value, int length = -1) {
+    return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
+                                      v8::String::kNormalString, length);
+  }
+
+  inline MaybeLocal<BoundScript> CompileScript(
+      v8::Local<v8::String> s
+    , const v8::ScriptOrigin& origin
+  ) {
+    v8::ScriptCompiler::Source source(s, origin);
+    return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
+  }
+
+  inline MaybeLocal<BoundScript> CompileScript(
+      v8::Local<v8::String> s
+  ) {
+    v8::ScriptCompiler::Source source(s);
+    return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
+  }
+
+  inline MaybeLocal<v8::Value> RunScript(
+      v8::Local<UnboundScript> script
+  ) {
+    EscapableHandleScope scope;
+    return scope.Escape(script->BindToCurrentContext()->Run());
+  }
+
+  inline MaybeLocal<v8::Value> RunScript(
+      v8::Local<BoundScript> script
+  ) {
+    return script->Run();
+  }
+#endif
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
+      v8::Local<v8::Object> target
+    , v8::Local<v8::Function> func
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, func, argc, argv)));
+#else
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource res("nan:makeCallback");
+    return res.runInAsyncScope(target, func, argc, argv)
+        .FromMaybe(v8::Local<v8::Value>());
+# else
+    return node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, func, argc, argv);
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#endif  // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+  }
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
+      v8::Local<v8::Object> target
+    , v8::Local<v8::String> symbol
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, symbol, argc, argv)));
+#else
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource res("nan:makeCallback");
+    return res.runInAsyncScope(target, symbol, argc, argv)
+        .FromMaybe(v8::Local<v8::Value>());
+# else
+    return node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, symbol, argc, argv);
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#endif  // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+  }
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
+      v8::Local<v8::Object> target
+    , const char* method
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    return scope.Escape(New(node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, method, argc, argv)));
+#else
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource res("nan:makeCallback");
+    return res.runInAsyncScope(target, method, argc, argv)
+        .FromMaybe(v8::Local<v8::Value>());
+# else
+    return node::MakeCallback(
+        v8::Isolate::GetCurrent(), target, method, argc, argv);
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#endif  // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+  }
+
+  inline void FatalException(const TryCatch& try_catch) {
+    node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_);
+  }
+
+  inline v8::Local<v8::Value> ErrnoException(
+          int errorno
+       ,  const char* syscall = NULL
+       ,  const char* message = NULL
+       ,  const char* path = NULL) {
+    return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall,
+            message, path);
+  }
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
+          int errorno
+       ,  const char* syscall = NULL
+       ,  const char* message = NULL
+       ,  const char* path = NULL) {
+    return ErrnoException(errorno, syscall, message, path);
+  }
+
+  template<typename T>
+  inline void SetIsolateData(
+      v8::Isolate *isolate
+    , T *data
+  ) {
+      isolate->SetData(0, data);
+  }
+
+  template<typename T>
+  inline T *GetIsolateData(
+      v8::Isolate *isolate
+  ) {
+      return static_cast<T*>(isolate->GetData(0));
+  }
+
+class Utf8String {
+ public:
+  inline explicit Utf8String(v8::Local<v8::Value> from) :
+      length_(0), str_(str_st_) {
+    HandleScope scope;
+    if (!from.IsEmpty()) {
+#if NODE_MAJOR_VERSION >= 10
+      v8::Local<v8::Context> context = GetCurrentContext();
+      v8::Local<v8::String> string =
+          from->ToString(context).FromMaybe(v8::Local<v8::String>());
+#else
+      v8::Local<v8::String> string = from->ToString();
+#endif
+      if (!string.IsEmpty()) {
+        size_t len = 3 * string->Length() + 1;
+        assert(len <= INT_MAX);
+        if (len > sizeof (str_st_)) {
+          str_ = static_cast<char*>(malloc(len));
+          assert(str_ != 0);
+        }
+        const int flags =
+            v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
+#if NODE_MAJOR_VERSION >= 11
+        length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_,
+                                    static_cast<int>(len), 0, flags);
+#else
+        // See https://github.com/nodejs/nan/issues/832.
+        // Disable the warning as there is no way around it.
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+        length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+#endif  // NODE_MAJOR_VERSION < 11
+        str_[length_] = '\0';
+      }
+    }
+  }
+
+  inline int length() const {
+    return length_;
+  }
+
+  inline char* operator*() { return str_; }
+  inline const char* operator*() const { return str_; }
+
+  inline ~Utf8String() {
+    if (str_ != str_st_) {
+      free(str_);
+    }
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
+
+  int length_;
+  char *str_;
+  char str_st_[1024];
+};
+
+#else  // Node 0.8 and 0.10
+  inline v8::Local<v8::Primitive> Undefined() {
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::Undefined()));
+  }
+
+  inline v8::Local<v8::Primitive> Null() {
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::Null()));
+  }
+
+  inline v8::Local<v8::Boolean> True() {
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::True()));
+  }
+
+  inline v8::Local<v8::Boolean> False() {
+    EscapableHandleScope scope;
+    return scope.Escape(New(v8::False()));
+  }
+
+  inline v8::Local<v8::String> EmptyString() {
+    return v8::String::Empty();
+  }
+
+  inline int AdjustExternalMemory(int bc) {
+    return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc));
+  }
+
+  inline void SetTemplate(
+      v8::Local<v8::Template> templ
+    , const char *name
+    , v8::Local<v8::Data> value) {
+    templ->Set(name, value);
+  }
+
+  inline void SetTemplate(
+      v8::Local<v8::Template> templ
+    , v8::Local<v8::String> name
+    , v8::Local<v8::Data> value
+    , v8::PropertyAttribute attributes) {
+    templ->Set(name, value, attributes);
+  }
+
+  inline v8::Local<v8::Context> GetCurrentContext() {
+    return v8::Context::GetCurrent();
+  }
+
+  inline void* GetInternalFieldPointer(
+      v8::Local<v8::Object> object
+    , int index) {
+    return object->GetPointerFromInternalField(index);
+  }
+
+  inline void SetInternalFieldPointer(
+      v8::Local<v8::Object> object
+    , int index
+    , void* value) {
+    object->SetPointerInInternalField(index, value);
+  }
+
+# define NAN_GC_CALLBACK(name)                                                 \
+    void name(v8::GCType type, v8::GCCallbackFlags flags)
+
+  inline void AddGCEpilogueCallback(
+    v8::GCEpilogueCallback callback
+  , v8::GCType gc_type_filter = v8::kGCTypeAll) {
+    v8::V8::AddGCEpilogueCallback(callback, gc_type_filter);
+  }
+  inline void RemoveGCEpilogueCallback(
+    v8::GCEpilogueCallback callback) {
+    v8::V8::RemoveGCEpilogueCallback(callback);
+  }
+  inline void AddGCPrologueCallback(
+    v8::GCPrologueCallback callback
+  , v8::GCType gc_type_filter = v8::kGCTypeAll) {
+    v8::V8::AddGCPrologueCallback(callback, gc_type_filter);
+  }
+  inline void RemoveGCPrologueCallback(
+    v8::GCPrologueCallback callback) {
+    v8::V8::RemoveGCPrologueCallback(callback);
+  }
+  inline void GetHeapStatistics(
+    v8::HeapStatistics *heap_statistics) {
+    v8::V8::GetHeapStatistics(heap_statistics);
+  }
+
+# define X(NAME)                                                               \
+    inline v8::Local<v8::Value> NAME(const char *msg) {                        \
+      EscapableHandleScope scope;                                              \
+      return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked()));     \
+    }                                                                          \
+                                                                               \
+    inline                                                                     \
+    v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) {                     \
+      return v8::Exception::NAME(msg);                                         \
+    }                                                                          \
+                                                                               \
+    inline void Throw ## NAME(const char *msg) {                               \
+      HandleScope scope;                                                       \
+      v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked()));      \
+    }                                                                          \
+                                                                               \
+    inline                                                                     \
+    void Throw ## NAME(v8::Local<v8::String> errmsg) {                         \
+      HandleScope scope;                                                       \
+      v8::ThrowException(v8::Exception::NAME(errmsg));                         \
+    }
+
+  X(Error)
+  X(RangeError)
+  X(ReferenceError)
+  X(SyntaxError)
+  X(TypeError)
+
+# undef X
+
+  inline void ThrowError(v8::Local<v8::Value> error) {
+    v8::ThrowException(error);
+  }
+
+  inline MaybeLocal<v8::Object> NewBuffer(
+      char *data
+    , size_t length
+    , node::Buffer::free_callback callback
+    , void *hint
+  ) {
+    EscapableHandleScope scope;
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(length <= imp::kMaxLength && "too large buffer");
+    return scope.Escape(
+        New(node::Buffer::New(data, length, callback, hint)->handle_));
+  }
+
+  inline MaybeLocal<v8::Object> CopyBuffer(
+      const char *data
+    , uint32_t size
+  ) {
+    EscapableHandleScope scope;
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(size <= imp::kMaxLength && "too large buffer");
+#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
+    return scope.Escape(New(node::Buffer::New(data, size)->handle_));
+#else
+    return scope.Escape(
+        New(node::Buffer::New(const_cast<char *>(data), size)->handle_));
+#endif
+  }
+
+  inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    EscapableHandleScope scope;
+    assert(size <= imp::kMaxLength && "too large buffer");
+    return scope.Escape(New(node::Buffer::New(size)->handle_));
+  }
+
+  inline void FreeData(char *data, void *hint) {
+    (void) hint;  // unused
+    delete[] data;
+  }
+
+  inline MaybeLocal<v8::Object> NewBuffer(
+      char* data
+    , uint32_t size
+  ) {
+    EscapableHandleScope scope;
+    // arbitrary buffer lengths requires
+    // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
+    assert(size <= imp::kMaxLength && "too large buffer");
+    return scope.Escape(
+        New(node::Buffer::New(data, size, FreeData, NULL)->handle_));
+  }
+
+namespace imp {
+inline void
+widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) {
+  size_t len = static_cast<size_t>(l);
+  if (l < 0) {
+    len = strlen(reinterpret_cast<const char*>(s));
+  }
+  assert(len <= INT_MAX && "string too long");
+  ws->resize(len);
+  std::copy(s, s + len, ws->begin());  // NOLINT(build/include_what_you_use)
+}
+}  // end of namespace imp
+
+  inline MaybeLocal<v8::String>
+  NewOneByteString(const uint8_t * value, int length = -1) {
+    std::vector<uint16_t> wideString;  // NOLINT(build/include_what_you_use)
+    imp::widenString(&wideString, value, length);
+    return v8::String::New(wideString.data(),
+                           static_cast<int>(wideString.size()));
+  }
+
+  inline MaybeLocal<BoundScript> CompileScript(
+      v8::Local<v8::String> s
+    , const v8::ScriptOrigin& origin
+  ) {
+    return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin));
+  }
+
+  inline MaybeLocal<BoundScript> CompileScript(
+    v8::Local<v8::String> s
+  ) {
+    return v8::Script::Compile(s);
+  }
+
+  inline
+  MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) {
+    return script->Run();
+  }
+
+  inline v8::Local<v8::Value> MakeCallback(
+      v8::Local<v8::Object> target
+    , v8::Local<v8::Function> func
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+    v8::HandleScope scope;
+    return scope.Close(New(node::MakeCallback(target, func, argc, argv)));
+  }
+
+  inline v8::Local<v8::Value> MakeCallback(
+      v8::Local<v8::Object> target
+    , v8::Local<v8::String> symbol
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+    v8::HandleScope scope;
+    return scope.Close(New(node::MakeCallback(target, symbol, argc, argv)));
+  }
+
+  inline v8::Local<v8::Value> MakeCallback(
+      v8::Local<v8::Object> target
+    , const char* method
+    , int argc
+    , v8::Local<v8::Value>* argv) {
+    v8::HandleScope scope;
+    return scope.Close(New(node::MakeCallback(target, method, argc, argv)));
+  }
+
+  inline void FatalException(const TryCatch& try_catch) {
+    node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_));
+  }
+
+  inline v8::Local<v8::Value> ErrnoException(
+          int errorno
+       ,  const char* syscall = NULL
+       ,  const char* message = NULL
+       ,  const char* path = NULL) {
+    return node::ErrnoException(errorno, syscall, message, path);
+  }
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
+          int errorno
+       ,  const char* syscall = NULL
+       ,  const char* message = NULL
+       ,  const char* path = NULL) {
+    return ErrnoException(errorno, syscall, message, path);
+  }
+
+
+  template<typename T>
+  inline void SetIsolateData(
+      v8::Isolate *isolate
+    , T *data
+  ) {
+      isolate->SetData(data);
+  }
+
+  template<typename T>
+  inline T *GetIsolateData(
+      v8::Isolate *isolate
+  ) {
+      return static_cast<T*>(isolate->GetData());
+  }
+
+class Utf8String {
+ public:
+  inline explicit Utf8String(v8::Local<v8::Value> from) :
+      length_(0), str_(str_st_) {
+    v8::HandleScope scope;
+    if (!from.IsEmpty()) {
+      v8::Local<v8::String> string = from->ToString();
+      if (!string.IsEmpty()) {
+        size_t len = 3 * string->Length() + 1;
+        assert(len <= INT_MAX);
+        if (len > sizeof (str_st_)) {
+          str_ = static_cast<char*>(malloc(len));
+          assert(str_ != 0);
+        }
+        const int flags =
+            v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
+        length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
+        str_[length_] = '\0';
+      }
+    }
+  }
+
+  inline int length() const {
+    return length_;
+  }
+
+  inline char* operator*() { return str_; }
+  inline const char* operator*() const { return str_; }
+
+  inline ~Utf8String() {
+    if (str_ != str_st_) {
+      free(str_);
+    }
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
+
+  int length_;
+  char *str_;
+  char str_st_[1024];
+};
+
+#endif  // NODE_MODULE_VERSION
+
+typedef void (*FreeCallback)(char *data, void *hint);
+
+typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE;
+typedef void NAN_METHOD_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE;
+typedef void NAN_GETTER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE;
+typedef void NAN_SETTER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Value>&
+    NAN_PROPERTY_GETTER_ARGS_TYPE;
+typedef void NAN_PROPERTY_GETTER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Value>&
+    NAN_PROPERTY_SETTER_ARGS_TYPE;
+typedef void NAN_PROPERTY_SETTER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Array>&
+    NAN_PROPERTY_ENUMERATOR_ARGS_TYPE;
+typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Boolean>&
+    NAN_PROPERTY_DELETER_ARGS_TYPE;
+typedef void NAN_PROPERTY_DELETER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Integer>&
+    NAN_PROPERTY_QUERY_ARGS_TYPE;
+typedef void NAN_PROPERTY_QUERY_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE;
+typedef void NAN_INDEX_GETTER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE;
+typedef void NAN_INDEX_SETTER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Array>&
+    NAN_INDEX_ENUMERATOR_ARGS_TYPE;
+typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Boolean>&
+    NAN_INDEX_DELETER_ARGS_TYPE;
+typedef void NAN_INDEX_DELETER_RETURN_TYPE;
+
+typedef const PropertyCallbackInfo<v8::Integer>&
+    NAN_INDEX_QUERY_ARGS_TYPE;
+typedef void NAN_INDEX_QUERY_RETURN_TYPE;
+
+#define NAN_METHOD(name)                                                       \
+    Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info)
+#define NAN_GETTER(name)                                                       \
+    Nan::NAN_GETTER_RETURN_TYPE name(                                          \
+        v8::Local<v8::String> property                                         \
+      , Nan::NAN_GETTER_ARGS_TYPE info)
+#define NAN_SETTER(name)                                                       \
+    Nan::NAN_SETTER_RETURN_TYPE name(                                          \
+        v8::Local<v8::String> property                                         \
+      , v8::Local<v8::Value> value                                             \
+      , Nan::NAN_SETTER_ARGS_TYPE info)
+#define NAN_PROPERTY_GETTER(name)                                              \
+    Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name(                                 \
+        v8::Local<v8::String> property                                         \
+      , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info)
+#define NAN_PROPERTY_SETTER(name)                                              \
+    Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name(                                 \
+        v8::Local<v8::String> property                                         \
+      , v8::Local<v8::Value> value                                             \
+      , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info)
+#define NAN_PROPERTY_ENUMERATOR(name)                                          \
+    Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(                             \
+        Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info)
+#define NAN_PROPERTY_DELETER(name)                                             \
+    Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name(                                \
+        v8::Local<v8::String> property                                         \
+      , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info)
+#define NAN_PROPERTY_QUERY(name)                                               \
+    Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name(                                  \
+        v8::Local<v8::String> property                                         \
+      , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info)
+# define NAN_INDEX_GETTER(name)                                                \
+    Nan::NAN_INDEX_GETTER_RETURN_TYPE name(                                    \
+        uint32_t index                                                         \
+      , Nan::NAN_INDEX_GETTER_ARGS_TYPE info)
+#define NAN_INDEX_SETTER(name)                                                 \
+    Nan::NAN_INDEX_SETTER_RETURN_TYPE name(                                    \
+        uint32_t index                                                         \
+      , v8::Local<v8::Value> value                                             \
+      , Nan::NAN_INDEX_SETTER_ARGS_TYPE info)
+#define NAN_INDEX_ENUMERATOR(name)                                             \
+    Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE                                      \
+    name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info)
+#define NAN_INDEX_DELETER(name)                                                \
+    Nan::NAN_INDEX_DELETER_RETURN_TYPE name(                                   \
+        uint32_t index                                                         \
+      , Nan::NAN_INDEX_DELETER_ARGS_TYPE info)
+#define NAN_INDEX_QUERY(name)                                                  \
+    Nan::NAN_INDEX_QUERY_RETURN_TYPE name(                                     \
+        uint32_t index                                                         \
+      , Nan::NAN_INDEX_QUERY_ARGS_TYPE info)
+
+class Callback {
+ public:
+  Callback() {}
+
+  explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {}
+
+  ~Callback() {
+    handle_.Reset();
+  }
+
+  bool operator==(const Callback &other) const {
+    return handle_ == other.handle_;
+  }
+
+  bool operator!=(const Callback &other) const {
+    return !operator==(other);
+  }
+
+  inline
+  v8::Local<v8::Function> operator*() const { return GetFunction(); }
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
+      v8::Local<v8::Object> target
+    , int argc = 0
+    , v8::Local<v8::Value> argv[] = 0) const {
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource async("nan:Callback:operator()");
+    return Call_(isolate, target, argc, argv, &async)
+        .FromMaybe(v8::Local<v8::Value>());
+# else
+    return Call_(isolate, target, argc, argv);
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#else
+    return Call_(target, argc, argv);
+#endif  //  NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  }
+
+  NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
+      int argc = 0
+    , v8::Local<v8::Value> argv[] = 0) const {
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource async("nan:Callback:operator()");
+    return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
+                              argc, argv, &async)
+                            .FromMaybe(v8::Local<v8::Value>()));
+# else
+    return scope.Escape(
+        Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#else
+    v8::HandleScope scope;
+    return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
+#endif  //  NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  }
+
+  inline MaybeLocal<v8::Value> operator()(
+      AsyncResource* resource
+    , int argc = 0
+    , v8::Local<v8::Value> argv[] = 0) const {
+    return this->Call(argc, argv, resource);
+  }
+
+  inline MaybeLocal<v8::Value> operator()(
+      AsyncResource* resource
+    , v8::Local<v8::Object> target
+    , int argc = 0
+    , v8::Local<v8::Value> argv[] = 0) const {
+    return this->Call(target, argc, argv, resource);
+  }
+
+  // TODO(kkoopa): remove
+  inline void SetFunction(const v8::Local<v8::Function> &fn) {
+    Reset(fn);
+  }
+
+  inline void Reset(const v8::Local<v8::Function> &fn) {
+    handle_.Reset(fn);
+  }
+
+  inline void Reset() {
+    handle_.Reset();
+  }
+
+  inline v8::Local<v8::Function> GetFunction() const {
+    return New(handle_);
+  }
+
+  inline bool IsEmpty() const {
+    return handle_.IsEmpty();
+  }
+
+  // Deprecated: For async callbacks Use the versions that accept an
+  // AsyncResource. If this callback does not correspond to an async resource,
+  // that is, it is a synchronous function call on a non-empty JS stack, you
+  // should Nan::Call instead.
+  NAN_DEPRECATED inline v8::Local<v8::Value>
+  Call(v8::Local<v8::Object> target
+     , int argc
+     , v8::Local<v8::Value> argv[]) const {
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource async("nan:Callback:Call");
+    return Call_(isolate, target, argc, argv, &async)
+        .FromMaybe(v8::Local<v8::Value>());
+# else
+    return Call_(isolate, target, argc, argv);
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#else
+    return Call_(target, argc, argv);
+#endif
+  }
+
+  // Deprecated: For async callbacks Use the versions that accept an
+  // AsyncResource. If this callback does not correspond to an async resource,
+  // that is, it is a synchronous function call on a non-empty JS stack, you
+  // should Nan::Call instead.
+  NAN_DEPRECATED inline v8::Local<v8::Value>
+  Call(int argc, v8::Local<v8::Value> argv[]) const {
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    AsyncResource async("nan:Callback:Call");
+    return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
+                              argc, argv, &async)
+                            .FromMaybe(v8::Local<v8::Value>()));
+# else
+    return scope.Escape(
+        Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
+# endif  // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+#else
+    v8::HandleScope scope;
+    return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
+#endif
+  }
+
+  inline MaybeLocal<v8::Value>
+  Call(v8::Local<v8::Object> target
+     , int argc
+     , v8::Local<v8::Value> argv[]
+     , AsyncResource* resource) const {
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    return Call_(isolate, target, argc, argv, resource);
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    return Call_(isolate, target, argc, argv);
+#else
+    return Call_(target, argc, argv);
+#endif
+  }
+
+  inline MaybeLocal<v8::Value>
+  Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const {
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource);
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+    v8::Isolate *isolate = v8::Isolate::GetCurrent();
+    v8::EscapableHandleScope scope(isolate);
+    return scope.Escape(
+        Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
+#else
+    v8::HandleScope scope;
+    return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
+#endif
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback)
+  Persistent<v8::Function> handle_;
+
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+  MaybeLocal<v8::Value> Call_(v8::Isolate *isolate
+                            , v8::Local<v8::Object> target
+                            , int argc
+                            , v8::Local<v8::Value> argv[]
+                            , AsyncResource* resource) const {
+    EscapableHandleScope scope;
+    v8::Local<v8::Function> func = New(handle_);
+    auto maybe = resource->runInAsyncScope(target, func, argc, argv);
+    v8::Local<v8::Value> local;
+    if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>();
+    return scope.Escape(local);
+  }
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  v8::Local<v8::Value> Call_(v8::Isolate *isolate
+                           , v8::Local<v8::Object> target
+                           , int argc
+                           , v8::Local<v8::Value> argv[]) const {
+    EscapableHandleScope scope;
+
+    v8::Local<v8::Function> callback = New(handle_);
+# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+    return scope.Escape(New(node::MakeCallback(
+        isolate
+      , target
+      , callback
+      , argc
+      , argv
+    )));
+# else
+    return scope.Escape(node::MakeCallback(
+        isolate
+      , target
+      , callback
+      , argc
+      , argv
+    ));
+# endif
+  }
+#else
+  v8::Local<v8::Value> Call_(v8::Local<v8::Object> target
+                           , int argc
+                           , v8::Local<v8::Value> argv[]) const {
+    EscapableHandleScope scope;
+
+    v8::Local<v8::Function> callback = New(handle_);
+    return scope.Escape(New(node::MakeCallback(
+        target
+      , callback
+      , argc
+      , argv
+    )));
+  }
+#endif
+};
+
+inline MaybeLocal<v8::Value> Call(
+    const Nan::Callback& callback
+  , v8::Local<v8::Object> recv
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  return Call(*callback, recv, argc, argv);
+}
+
+inline MaybeLocal<v8::Value> Call(
+    const Nan::Callback& callback
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  v8::Isolate* isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(
+      Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv)
+          .FromMaybe(v8::Local<v8::Value>()));
+#else
+  EscapableHandleScope scope;
+  return scope.Escape(
+      Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv)
+          .FromMaybe(v8::Local<v8::Value>()));
+#endif
+}
+
+inline MaybeLocal<v8::Value> Call(
+    v8::Local<v8::String> symbol
+  , v8::Local<v8::Object> recv
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  EscapableHandleScope scope;
+  v8::Local<v8::Value> fn_v =
+      Get(recv, symbol).FromMaybe(v8::Local<v8::Value>());
+  if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>();
+  v8::Local<v8::Function> fn = fn_v.As<v8::Function>();
+  return scope.Escape(
+      Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline MaybeLocal<v8::Value> Call(
+    const char* method
+  , v8::Local<v8::Object> recv
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  EscapableHandleScope scope;
+  v8::Local<v8::String> method_string =
+      New<v8::String>(method).ToLocalChecked();
+  return scope.Escape(
+      Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
+}
+
+/* abstract */ class AsyncWorker {
+ public:
+  explicit AsyncWorker(Callback *callback_,
+                       const char* resource_name = "nan:AsyncWorker")
+      : callback(callback_), errmsg_(NULL) {
+    request.data = this;
+
+    HandleScope scope;
+    v8::Local<v8::Object> obj = New<v8::Object>();
+    persistentHandle.Reset(obj);
+    async_resource = new AsyncResource(resource_name, obj);
+  }
+
+  virtual ~AsyncWorker() {
+    HandleScope scope;
+
+    if (!persistentHandle.IsEmpty())
+      persistentHandle.Reset();
+    delete callback;
+    delete[] errmsg_;
+    delete async_resource;
+  }
+
+  virtual void WorkComplete() {
+    HandleScope scope;
+
+    if (errmsg_ == NULL)
+      HandleOKCallback();
+    else
+      HandleErrorCallback();
+    delete callback;
+    callback = NULL;
+  }
+
+  inline void SaveToPersistent(
+      const char *key, const v8::Local<v8::Value> &value) {
+    HandleScope scope;
+    Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust();
+  }
+
+  inline void SaveToPersistent(
+      const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) {
+    HandleScope scope;
+    Set(New(persistentHandle), key, value).FromJust();
+  }
+
+  inline void SaveToPersistent(
+      uint32_t index, const v8::Local<v8::Value> &value) {
+    HandleScope scope;
+    Set(New(persistentHandle), index, value).FromJust();
+  }
+
+  inline v8::Local<v8::Value> GetFromPersistent(const char *key) const {
+    EscapableHandleScope scope;
+    return scope.Escape(
+        Get(New(persistentHandle), New(key).ToLocalChecked())
+        .FromMaybe(v8::Local<v8::Value>()));
+  }
+
+  inline v8::Local<v8::Value>
+  GetFromPersistent(const v8::Local<v8::String> &key) const {
+    EscapableHandleScope scope;
+    return scope.Escape(
+        Get(New(persistentHandle), key)
+        .FromMaybe(v8::Local<v8::Value>()));
+  }
+
+  inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const {
+    EscapableHandleScope scope;
+    return scope.Escape(
+        Get(New(persistentHandle), index)
+        .FromMaybe(v8::Local<v8::Value>()));
+  }
+
+  virtual void Execute() = 0;
+
+  uv_work_t request;
+
+  virtual void Destroy() {
+      delete this;
+  }
+
+ protected:
+  Persistent<v8::Object> persistentHandle;
+  Callback *callback;
+  AsyncResource *async_resource;
+
+  virtual void HandleOKCallback() {
+    HandleScope scope;
+
+    callback->Call(0, NULL, async_resource);
+  }
+
+  virtual void HandleErrorCallback() {
+    HandleScope scope;
+
+    v8::Local<v8::Value> argv[] = {
+      v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked())
+    };
+    callback->Call(1, argv, async_resource);
+  }
+
+  void SetErrorMessage(const char *msg) {
+    delete[] errmsg_;
+
+    size_t size = strlen(msg) + 1;
+    errmsg_ = new char[size];
+    memcpy(errmsg_, msg, size);
+  }
+
+  const char* ErrorMessage() const {
+    return errmsg_;
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker)
+  char *errmsg_;
+};
+
+/* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker {
+ public:
+  explicit AsyncBareProgressWorkerBase(
+      Callback *callback_,
+      const char* resource_name = "nan:AsyncBareProgressWorkerBase")
+      : AsyncWorker(callback_, resource_name) {
+    uv_async_init(
+        GetCurrentEventLoop()
+      , &async
+      , AsyncProgress_
+    );
+    async.data = this;
+  }
+
+  virtual ~AsyncBareProgressWorkerBase() {
+  }
+
+  virtual void WorkProgress() = 0;
+
+  virtual void Destroy() {
+      uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_);
+  }
+
+ private:
+  inline static NAUV_WORK_CB(AsyncProgress_) {
+    AsyncBareProgressWorkerBase *worker =
+            static_cast<AsyncBareProgressWorkerBase*>(async->data);
+    worker->WorkProgress();
+  }
+
+  inline static void AsyncClose_(uv_handle_t* handle) {
+    AsyncBareProgressWorkerBase *worker =
+            static_cast<AsyncBareProgressWorkerBase*>(handle->data);
+    delete worker;
+  }
+
+ protected:
+  uv_async_t async;
+};
+
+template<class T>
+/* abstract */
+class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase {
+ public:
+  explicit AsyncBareProgressWorker(
+      Callback *callback_,
+      const char* resource_name = "nan:AsyncBareProgressWorker")
+      : AsyncBareProgressWorkerBase(callback_, resource_name) {
+    uv_mutex_init(&async_lock);
+  }
+
+  virtual ~AsyncBareProgressWorker() {
+    uv_mutex_destroy(&async_lock);
+  }
+
+  class ExecutionProgress {
+    friend class AsyncBareProgressWorker;
+   public:
+    void Signal() const {
+      uv_mutex_lock(&that_->async_lock);
+      uv_async_send(&that_->async);
+      uv_mutex_unlock(&that_->async_lock);
+    }
+
+    void Send(const T* data, size_t count) const {
+      that_->SendProgress_(data, count);
+    }
+
+   private:
+    explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {}
+    NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
+    AsyncBareProgressWorker* const that_;
+  };
+
+  virtual void Execute(const ExecutionProgress& progress) = 0;
+  virtual void HandleProgressCallback(const T *data, size_t size) = 0;
+
+ protected:
+  uv_mutex_t async_lock;
+
+ private:
+  void Execute() /*final override*/ {
+    ExecutionProgress progress(this);
+    Execute(progress);
+  }
+
+  virtual void SendProgress_(const T *data, size_t count) = 0;
+};
+
+template<class T>
+/* abstract */
+class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> {
+ public:
+  explicit AsyncProgressWorkerBase(
+      Callback *callback_,
+      const char* resource_name = "nan:AsyncProgressWorkerBase")
+      : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL),
+        asyncsize_(0) {
+  }
+
+  virtual ~AsyncProgressWorkerBase() {
+    delete[] asyncdata_;
+  }
+
+  void WorkProgress() {
+    uv_mutex_lock(&this->async_lock);
+    T *data = asyncdata_;
+    size_t size = asyncsize_;
+    asyncdata_ = NULL;
+    asyncsize_ = 0;
+    uv_mutex_unlock(&this->async_lock);
+
+    // Don't send progress events after we've already completed.
+    if (this->callback) {
+        this->HandleProgressCallback(data, size);
+    }
+    delete[] data;
+  }
+
+ private:
+  void SendProgress_(const T *data, size_t count) {
+    T *new_data = new T[count];
+    {
+      T *it = new_data;
+      std::copy(data, data + count, it);
+    }
+
+    uv_mutex_lock(&this->async_lock);
+    T *old_data = asyncdata_;
+    asyncdata_ = new_data;
+    asyncsize_ = count;
+    uv_async_send(&this->async);
+    uv_mutex_unlock(&this->async_lock);
+
+    delete[] old_data;
+  }
+
+  T *asyncdata_;
+  size_t asyncsize_;
+};
+
+// This ensures compatibility to the previous un-templated AsyncProgressWorker
+// class definition.
+typedef AsyncProgressWorkerBase<char> AsyncProgressWorker;
+
+template<class T>
+/* abstract */
+class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase {
+ public:
+  explicit AsyncBareProgressQueueWorker(
+      Callback *callback_,
+      const char* resource_name = "nan:AsyncBareProgressQueueWorker")
+      : AsyncBareProgressWorkerBase(callback_, resource_name) {
+  }
+
+  virtual ~AsyncBareProgressQueueWorker() {
+  }
+
+  class ExecutionProgress {
+    friend class AsyncBareProgressQueueWorker;
+   public:
+    void Send(const T* data, size_t count) const {
+      that_->SendProgress_(data, count);
+    }
+
+   private:
+    explicit ExecutionProgress(AsyncBareProgressQueueWorker *that)
+        : that_(that) {}
+    NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
+    AsyncBareProgressQueueWorker* const that_;
+  };
+
+  virtual void Execute(const ExecutionProgress& progress) = 0;
+  virtual void HandleProgressCallback(const T *data, size_t size) = 0;
+
+ private:
+  void Execute() /*final override*/ {
+    ExecutionProgress progress(this);
+    Execute(progress);
+  }
+
+  virtual void SendProgress_(const T *data, size_t count) = 0;
+};
+
+template<class T>
+/* abstract */
+class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> {
+ public:
+  explicit AsyncProgressQueueWorker(
+      Callback *callback_,
+      const char* resource_name = "nan:AsyncProgressQueueWorker")
+      : AsyncBareProgressQueueWorker<T>(callback_) {
+    uv_mutex_init(&async_lock);
+  }
+
+  virtual ~AsyncProgressQueueWorker() {
+    uv_mutex_lock(&async_lock);
+
+    while (!asyncdata_.empty()) {
+      std::pair<T*, size_t> &datapair = asyncdata_.front();
+      T *data = datapair.first;
+
+      asyncdata_.pop();
+
+      delete[] data;
+    }
+
+    uv_mutex_unlock(&async_lock);
+    uv_mutex_destroy(&async_lock);
+  }
+
+  void WorkComplete() {
+    WorkProgress();
+    AsyncWorker::WorkComplete();
+  }
+
+  void WorkProgress() {
+    uv_mutex_lock(&async_lock);
+
+    while (!asyncdata_.empty()) {
+      std::pair<T*, size_t> &datapair = asyncdata_.front();
+
+      T *data = datapair.first;
+      size_t size = datapair.second;
+
+      asyncdata_.pop();
+      uv_mutex_unlock(&async_lock);
+
+      // Don't send progress events after we've already completed.
+      if (this->callback) {
+          this->HandleProgressCallback(data, size);
+      }
+
+      delete[] data;
+
+      uv_mutex_lock(&async_lock);
+    }
+
+    uv_mutex_unlock(&async_lock);
+  }
+
+ private:
+  void SendProgress_(const T *data, size_t count) {
+    T *new_data = new T[count];
+    {
+      T *it = new_data;
+      std::copy(data, data + count, it);
+    }
+
+    uv_mutex_lock(&async_lock);
+    asyncdata_.push(std::pair<T*, size_t>(new_data, count));
+    uv_mutex_unlock(&async_lock);
+
+    uv_async_send(&this->async);
+  }
+
+  uv_mutex_t async_lock;
+  std::queue<std::pair<T*, size_t> > asyncdata_;
+};
+
+inline void AsyncExecute (uv_work_t* req) {
+  AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
+  worker->Execute();
+}
+
+inline void AsyncExecuteComplete (uv_work_t* req) {
+  AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
+  worker->WorkComplete();
+  worker->Destroy();
+}
+
+inline void AsyncQueueWorker (AsyncWorker* worker) {
+  uv_queue_work(
+      GetCurrentEventLoop()
+    , &worker->request
+    , AsyncExecute
+    , reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete)
+  );
+}
+
+namespace imp {
+
+inline
+ExternalOneByteStringResource const*
+GetExternalResource(v8::Local<v8::String> str) {
+#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
+    return str->GetExternalAsciiStringResource();
+#else
+    return str->GetExternalOneByteStringResource();
+#endif
+}
+
+inline
+bool
+IsExternal(v8::Local<v8::String> str) {
+#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
+    return str->IsExternalAscii();
+#else
+    return str->IsExternalOneByte();
+#endif
+}
+
+}  // end of namespace imp
+
+enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
+
+#if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION
+# include "nan_string_bytes.h"  // NOLINT(build/include)
+#endif
+
+inline v8::Local<v8::Value> Encode(
+    const void *buf, size_t len, enum Encoding encoding = BINARY) {
+#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION)
+  v8::Isolate* isolate = v8::Isolate::GetCurrent();
+  node::encoding node_enc = static_cast<node::encoding>(encoding);
+
+  if (encoding == UCS2) {
+    return node::Encode(
+        isolate
+      , reinterpret_cast<const uint16_t *>(buf)
+      , len / 2);
+  } else {
+    return node::Encode(
+        isolate
+      , reinterpret_cast<const char *>(buf)
+      , len
+      , node_enc);
+  }
+#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
+  return node::Encode(
+      v8::Isolate::GetCurrent()
+    , buf, len
+    , static_cast<node::encoding>(encoding));
+#else
+# if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
+  return node::Encode(buf, len, static_cast<node::encoding>(encoding));
+# else
+  return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding);
+# endif
+#endif
+}
+
+inline ssize_t DecodeBytes(
+    v8::Local<v8::Value> val, enum Encoding encoding = BINARY) {
+#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
+  return node::DecodeBytes(
+      v8::Isolate::GetCurrent()
+    , val
+    , static_cast<node::encoding>(encoding));
+#else
+# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
+  if (encoding == BUFFER) {
+    return node::DecodeBytes(val, node::BINARY);
+  }
+# endif
+  return node::DecodeBytes(val, static_cast<node::encoding>(encoding));
+#endif
+}
+
+inline ssize_t DecodeWrite(
+    char *buf
+  , size_t len
+  , v8::Local<v8::Value> val
+  , enum Encoding encoding = BINARY) {
+#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
+  return node::DecodeWrite(
+      v8::Isolate::GetCurrent()
+    , buf
+    , len
+    , val
+    , static_cast<node::encoding>(encoding));
+#else
+# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
+  if (encoding == BUFFER) {
+    return node::DecodeWrite(buf, len, val, node::BINARY);
+  }
+# endif
+  return node::DecodeWrite(
+      buf
+    , len
+    , val
+    , static_cast<node::encoding>(encoding));
+#endif
+}
+
+inline void SetPrototypeTemplate(
+    v8::Local<v8::FunctionTemplate> templ
+  , const char *name
+  , v8::Local<v8::Data> value
+) {
+  HandleScope scope;
+  SetTemplate(templ->PrototypeTemplate(), name, value);
+}
+
+inline void SetPrototypeTemplate(
+    v8::Local<v8::FunctionTemplate> templ
+  , v8::Local<v8::String> name
+  , v8::Local<v8::Data> value
+  , v8::PropertyAttribute attributes
+) {
+  HandleScope scope;
+  SetTemplate(templ->PrototypeTemplate(), name, value, attributes);
+}
+
+inline void SetInstanceTemplate(
+    v8::Local<v8::FunctionTemplate> templ
+  , const char *name
+  , v8::Local<v8::Data> value
+) {
+  HandleScope scope;
+  SetTemplate(templ->InstanceTemplate(), name, value);
+}
+
+inline void SetInstanceTemplate(
+    v8::Local<v8::FunctionTemplate> templ
+  , v8::Local<v8::String> name
+  , v8::Local<v8::Data> value
+  , v8::PropertyAttribute attributes
+) {
+  HandleScope scope;
+  SetTemplate(templ->InstanceTemplate(), name, value, attributes);
+}
+
+namespace imp {
+
+// Note(@agnat): Helper to distinguish different receiver types. The first
+// version deals with receivers derived from v8::Template. The second version
+// handles everything else. The final argument only serves as discriminator and
+// is unused.
+template <typename T>
+inline
+void
+SetMethodAux(T recv,
+             v8::Local<v8::String> name,
+             v8::Local<v8::FunctionTemplate> tpl,
+             v8::Template *) {
+  recv->Set(name, tpl);
+}
+
+template <typename T>
+inline
+void
+SetMethodAux(T recv,
+             v8::Local<v8::String> name,
+             v8::Local<v8::FunctionTemplate> tpl,
+             ...) {
+  Set(recv, name, GetFunction(tpl).ToLocalChecked());
+}
+
+}  // end of namespace imp
+
+template <typename T, template <typename> class HandleType>
+inline void SetMethod(
+    HandleType<T> recv
+  , const char *name
+  , FunctionCallback callback) {
+  HandleScope scope;
+  v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback);
+  v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
+  t->SetClassName(fn_name);
+  // Note(@agnat): Pass an empty T* as discriminator. See note on
+  // SetMethodAux(...) above
+  imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0));
+}
+
+inline void SetPrototypeMethod(
+    v8::Local<v8::FunctionTemplate> recv
+  , const char* name, FunctionCallback callback) {
+  HandleScope scope;
+  v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(
+      callback
+    , v8::Local<v8::Value>()
+    , New<v8::Signature>(recv));
+  v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
+  recv->PrototypeTemplate()->Set(fn_name, t);
+  t->SetClassName(fn_name);
+}
+
+//=== Accessors and Such =======================================================
+
+inline void SetAccessor(
+    v8::Local<v8::ObjectTemplate> tpl
+  , v8::Local<v8::String> name
+  , GetterCallback getter
+  , SetterCallback setter = 0
+  , v8::Local<v8::Value> data = v8::Local<v8::Value>()
+  , v8::AccessControl settings = v8::DEFAULT
+  , v8::PropertyAttribute attribute = v8::None
+  , imp::Sig signature = imp::Sig()) {
+  HandleScope scope;
+
+  imp::NativeGetter getter_ =
+      imp::GetterCallbackWrapper;
+  imp::NativeSetter setter_ =
+      setter ? imp::SetterCallbackWrapper : 0;
+
+  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
+  otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
+  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
+
+  obj->SetInternalField(
+      imp::kGetterIndex
+    , New<v8::External>(reinterpret_cast<void *>(getter)));
+
+  if (setter != 0) {
+    obj->SetInternalField(
+        imp::kSetterIndex
+      , New<v8::External>(reinterpret_cast<void *>(setter)));
+  }
+
+  if (!data.IsEmpty()) {
+    obj->SetInternalField(imp::kDataIndex, data);
+  }
+
+  tpl->SetAccessor(
+      name
+    , getter_
+    , setter_
+    , obj
+    , settings
+    , attribute
+    , signature);
+}
+
+inline bool SetAccessor(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> name
+  , GetterCallback getter
+  , SetterCallback setter = 0
+  , v8::Local<v8::Value> data = v8::Local<v8::Value>()
+  , v8::AccessControl settings = v8::DEFAULT
+  , v8::PropertyAttribute attribute = v8::None) {
+  HandleScope scope;
+
+  imp::NativeGetter getter_ =
+      imp::GetterCallbackWrapper;
+  imp::NativeSetter setter_ =
+      setter ? imp::SetterCallbackWrapper : 0;
+
+  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
+  otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
+  v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked();
+
+  dataobj->SetInternalField(
+      imp::kGetterIndex
+    , New<v8::External>(reinterpret_cast<void *>(getter)));
+
+  if (!data.IsEmpty()) {
+    dataobj->SetInternalField(imp::kDataIndex, data);
+  }
+
+  if (setter) {
+    dataobj->SetInternalField(
+        imp::kSetterIndex
+      , New<v8::External>(reinterpret_cast<void *>(setter)));
+  }
+
+#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
+  return obj->SetAccessor(
+      GetCurrentContext()
+    , name
+    , getter_
+    , setter_
+    , dataobj
+    , settings
+    , attribute).FromMaybe(false);
+#else
+  return obj->SetAccessor(
+      name
+    , getter_
+    , setter_
+    , dataobj
+    , settings
+    , attribute);
+#endif
+}
+
+inline void SetNamedPropertyHandler(
+    v8::Local<v8::ObjectTemplate> tpl
+  , PropertyGetterCallback getter
+  , PropertySetterCallback setter = 0
+  , PropertyQueryCallback query = 0
+  , PropertyDeleterCallback deleter = 0
+  , PropertyEnumeratorCallback enumerator = 0
+  , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
+  HandleScope scope;
+
+  imp::NativePropertyGetter getter_ =
+      imp::PropertyGetterCallbackWrapper;
+  imp::NativePropertySetter setter_ =
+      setter ? imp::PropertySetterCallbackWrapper : 0;
+  imp::NativePropertyQuery query_ =
+      query ? imp::PropertyQueryCallbackWrapper : 0;
+  imp::NativePropertyDeleter *deleter_ =
+      deleter ? imp::PropertyDeleterCallbackWrapper : 0;
+  imp::NativePropertyEnumerator enumerator_ =
+      enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0;
+
+  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
+  otpl->SetInternalFieldCount(imp::kPropertyFieldCount);
+  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
+  obj->SetInternalField(
+      imp::kPropertyGetterIndex
+    , New<v8::External>(reinterpret_cast<void *>(getter)));
+
+  if (setter) {
+    obj->SetInternalField(
+        imp::kPropertySetterIndex
+      , New<v8::External>(reinterpret_cast<void *>(setter)));
+  }
+
+  if (query) {
+    obj->SetInternalField(
+        imp::kPropertyQueryIndex
+      , New<v8::External>(reinterpret_cast<void *>(query)));
+  }
+
+  if (deleter) {
+    obj->SetInternalField(
+        imp::kPropertyDeleterIndex
+      , New<v8::External>(reinterpret_cast<void *>(deleter)));
+  }
+
+  if (enumerator) {
+    obj->SetInternalField(
+        imp::kPropertyEnumeratorIndex
+      , New<v8::External>(reinterpret_cast<void *>(enumerator)));
+  }
+
+  if (!data.IsEmpty()) {
+    obj->SetInternalField(imp::kDataIndex, data);
+  }
+
+#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+  tpl->SetHandler(v8::NamedPropertyHandlerConfiguration(
+      getter_, setter_, query_, deleter_, enumerator_, obj));
+#else
+  tpl->SetNamedPropertyHandler(
+      getter_
+    , setter_
+    , query_
+    , deleter_
+    , enumerator_
+    , obj);
+#endif
+}
+
+inline void SetIndexedPropertyHandler(
+    v8::Local<v8::ObjectTemplate> tpl
+  , IndexGetterCallback getter
+  , IndexSetterCallback setter = 0
+  , IndexQueryCallback query = 0
+  , IndexDeleterCallback deleter = 0
+  , IndexEnumeratorCallback enumerator = 0
+  , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
+  HandleScope scope;
+
+  imp::NativeIndexGetter getter_ =
+      imp::IndexGetterCallbackWrapper;
+  imp::NativeIndexSetter setter_ =
+      setter ? imp::IndexSetterCallbackWrapper : 0;
+  imp::NativeIndexQuery query_ =
+      query ? imp::IndexQueryCallbackWrapper : 0;
+  imp::NativeIndexDeleter deleter_ =
+      deleter ? imp::IndexDeleterCallbackWrapper : 0;
+  imp::NativeIndexEnumerator enumerator_ =
+      enumerator ? imp::IndexEnumeratorCallbackWrapper : 0;
+
+  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
+  otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount);
+  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
+  obj->SetInternalField(
+      imp::kIndexPropertyGetterIndex
+    , New<v8::External>(reinterpret_cast<void *>(getter)));
+
+  if (setter) {
+    obj->SetInternalField(
+        imp::kIndexPropertySetterIndex
+      , New<v8::External>(reinterpret_cast<void *>(setter)));
+  }
+
+  if (query) {
+    obj->SetInternalField(
+        imp::kIndexPropertyQueryIndex
+      , New<v8::External>(reinterpret_cast<void *>(query)));
+  }
+
+  if (deleter) {
+    obj->SetInternalField(
+        imp::kIndexPropertyDeleterIndex
+      , New<v8::External>(reinterpret_cast<void *>(deleter)));
+  }
+
+  if (enumerator) {
+    obj->SetInternalField(
+        imp::kIndexPropertyEnumeratorIndex
+      , New<v8::External>(reinterpret_cast<void *>(enumerator)));
+  }
+
+  if (!data.IsEmpty()) {
+    obj->SetInternalField(imp::kDataIndex, data);
+  }
+
+#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+  tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration(
+      getter_, setter_, query_, deleter_, enumerator_, obj));
+#else
+  tpl->SetIndexedPropertyHandler(
+      getter_
+    , setter_
+    , query_
+    , deleter_
+    , enumerator_
+    , obj);
+#endif
+}
+
+inline void SetCallHandler(
+    v8::Local<v8::FunctionTemplate> tpl
+  , FunctionCallback callback
+  , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
+  HandleScope scope;
+
+  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
+  otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
+  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
+
+  obj->SetInternalField(
+      imp::kFunctionIndex
+    , New<v8::External>(reinterpret_cast<void *>(callback)));
+
+  if (!data.IsEmpty()) {
+    obj->SetInternalField(imp::kDataIndex, data);
+  }
+
+  tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj);
+}
+
+
+inline void SetCallAsFunctionHandler(
+    v8::Local<v8::ObjectTemplate> tpl,
+    FunctionCallback callback,
+    v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
+  HandleScope scope;
+
+  v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
+  otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
+  v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
+
+  obj->SetInternalField(
+      imp::kFunctionIndex
+    , New<v8::External>(reinterpret_cast<void *>(callback)));
+
+  if (!data.IsEmpty()) {
+    obj->SetInternalField(imp::kDataIndex, data);
+  }
+
+  tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj);
+}
+
+//=== Weak Persistent Handling =================================================
+
+#include "nan_weak.h"  // NOLINT(build/include)
+
+//=== ObjectWrap ===============================================================
+
+#include "nan_object_wrap.h"  // NOLINT(build/include)
+
+//=== HiddenValue/Private ======================================================
+
+#include "nan_private.h"  // NOLINT(build/include)
+
+//=== Export ==================================================================
+
+inline
+void
+Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name,
+    FunctionCallback f) {
+  HandleScope scope;
+
+  Set(target, New<v8::String>(name).ToLocalChecked(),
+      GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked());
+}
+
+//=== Tap Reverse Binding =====================================================
+
+struct Tap {
+  explicit Tap(v8::Local<v8::Value> t) : t_() {
+    HandleScope scope;
+
+    t_.Reset(To<v8::Object>(t).ToLocalChecked());
+  }
+
+  ~Tap() { t_.Reset(); }  // not sure if neccessary
+
+  inline void plan(int i) {
+    HandleScope scope;
+    v8::Local<v8::Value> arg = New(i);
+    Call("plan", New(t_), 1, &arg);
+  }
+
+  inline void ok(bool isOk, const char *msg = NULL) {
+    HandleScope scope;
+    v8::Local<v8::Value> args[2];
+    args[0] = New(isOk);
+    if (msg) args[1] = New(msg).ToLocalChecked();
+    Call("ok", New(t_), msg ? 2 : 1, args);
+  }
+
+  inline void pass(const char * msg = NULL) {
+    HandleScope scope;
+    v8::Local<v8::Value> hmsg;
+    if (msg) hmsg = New(msg).ToLocalChecked();
+    Call("pass", New(t_), msg ? 1 : 0, &hmsg);
+  }
+
+  inline void end() {
+    HandleScope scope;
+    Call("end", New(t_), 0, NULL);
+  }
+
+ private:
+  Persistent<v8::Object> t_;
+};
+
+#define NAN_STRINGIZE2(x) #x
+#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x)
+#define NAN_TEST_EXPRESSION(expression) \
+  ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression
+
+#define NAN_EXPORT(target, function) Export(target, #function, function)
+
+#undef TYPE_CHECK
+
+//=== Generic Maybefication ===================================================
+
+namespace imp {
+
+template <typename T> struct Maybefier;
+
+template <typename T> struct Maybefier<v8::Local<T> > {
+  inline static MaybeLocal<T> convert(v8::Local<T> v) {
+    return v;
+  }
+};
+
+template <typename T> struct Maybefier<MaybeLocal<T> > {
+  inline static MaybeLocal<T> convert(MaybeLocal<T> v) {
+    return v;
+  }
+};
+
+}  // end of namespace imp
+
+template <typename T, template <typename> class MaybeMaybe>
+inline MaybeLocal<T>
+MakeMaybe(MaybeMaybe<T> v) {
+  return imp::Maybefier<MaybeMaybe<T> >::convert(v);
+}
+
+//=== TypedArrayContents =======================================================
+
+#include "nan_typedarray_contents.h"  // NOLINT(build/include)
+
+//=== JSON =====================================================================
+
+#include "nan_json.h"  // NOLINT(build/include)
+
+}  // end of namespace Nan
+
+#endif  // NAN_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_callbacks.h b/node_modules/node-pty/node_modules/nan/nan_callbacks.h
new file mode 100644 (file)
index 0000000..53ede84
--- /dev/null
@@ -0,0 +1,88 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_CALLBACKS_H_
+#define NAN_CALLBACKS_H_
+
+template<typename T> class FunctionCallbackInfo;
+template<typename T> class PropertyCallbackInfo;
+template<typename T> class Global;
+
+typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
+typedef void(*GetterCallback)
+    (v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&);
+typedef void(*SetterCallback)(
+    v8::Local<v8::String>,
+    v8::Local<v8::Value>,
+    const PropertyCallbackInfo<void>&);
+typedef void(*PropertyGetterCallback)(
+    v8::Local<v8::String>,
+    const PropertyCallbackInfo<v8::Value>&);
+typedef void(*PropertySetterCallback)(
+    v8::Local<v8::String>,
+    v8::Local<v8::Value>,
+    const PropertyCallbackInfo<v8::Value>&);
+typedef void(*PropertyEnumeratorCallback)
+    (const PropertyCallbackInfo<v8::Array>&);
+typedef void(*PropertyDeleterCallback)(
+    v8::Local<v8::String>,
+    const PropertyCallbackInfo<v8::Boolean>&);
+typedef void(*PropertyQueryCallback)(
+    v8::Local<v8::String>,
+    const PropertyCallbackInfo<v8::Integer>&);
+typedef void(*IndexGetterCallback)(
+    uint32_t,
+    const PropertyCallbackInfo<v8::Value>&);
+typedef void(*IndexSetterCallback)(
+    uint32_t,
+    v8::Local<v8::Value>,
+    const PropertyCallbackInfo<v8::Value>&);
+typedef void(*IndexEnumeratorCallback)
+    (const PropertyCallbackInfo<v8::Array>&);
+typedef void(*IndexDeleterCallback)(
+    uint32_t,
+    const PropertyCallbackInfo<v8::Boolean>&);
+typedef void(*IndexQueryCallback)(
+    uint32_t,
+    const PropertyCallbackInfo<v8::Integer>&);
+
+namespace imp {
+typedef v8::Local<v8::AccessorSignature> Sig;
+
+static const int kDataIndex =                    0;
+
+static const int kFunctionIndex =                1;
+static const int kFunctionFieldCount =           2;
+
+static const int kGetterIndex =                  1;
+static const int kSetterIndex =                  2;
+static const int kAccessorFieldCount =           3;
+
+static const int kPropertyGetterIndex =          1;
+static const int kPropertySetterIndex =          2;
+static const int kPropertyEnumeratorIndex =      3;
+static const int kPropertyDeleterIndex =         4;
+static const int kPropertyQueryIndex =           5;
+static const int kPropertyFieldCount =           6;
+
+static const int kIndexPropertyGetterIndex =     1;
+static const int kIndexPropertySetterIndex =     2;
+static const int kIndexPropertyEnumeratorIndex = 3;
+static const int kIndexPropertyDeleterIndex =    4;
+static const int kIndexPropertyQueryIndex =      5;
+static const int kIndexPropertyFieldCount =      6;
+
+}  // end of namespace imp
+
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+# include "nan_callbacks_12_inl.h"  // NOLINT(build/include)
+#else
+# include "nan_callbacks_pre_12_inl.h"  // NOLINT(build/include)
+#endif
+
+#endif  // NAN_CALLBACKS_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_callbacks_12_inl.h b/node_modules/node-pty/node_modules/nan/nan_callbacks_12_inl.h
new file mode 100644 (file)
index 0000000..c27b18d
--- /dev/null
@@ -0,0 +1,514 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_CALLBACKS_12_INL_H_
+#define NAN_CALLBACKS_12_INL_H_
+
+template<typename T>
+class ReturnValue {
+  v8::ReturnValue<T> value_;
+
+ public:
+  template <class S>
+  explicit inline ReturnValue(const v8::ReturnValue<S> &value) :
+      value_(value) {}
+  template <class S>
+  explicit inline ReturnValue(const ReturnValue<S>& that)
+      : value_(that.value_) {
+    TYPE_CHECK(T, S);
+  }
+
+  // Handle setters
+  template <typename S> inline void Set(const v8::Local<S> &handle) {
+    TYPE_CHECK(T, S);
+    value_.Set(handle);
+  }
+
+  template <typename S> inline void Set(const Global<S> &handle) {
+    TYPE_CHECK(T, S);
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) &&                       \
+  (V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 &&                           \
+  defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8))))
+    value_.Set(handle);
+#else
+    value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle));
+    const_cast<Global<S> &>(handle).Reset();
+#endif
+  }
+
+  // Fast primitive setters
+  inline void Set(bool value) {
+    TYPE_CHECK(T, v8::Boolean);
+    value_.Set(value);
+  }
+
+  inline void Set(double i) {
+    TYPE_CHECK(T, v8::Number);
+    value_.Set(i);
+  }
+
+  inline void Set(int32_t i) {
+    TYPE_CHECK(T, v8::Integer);
+    value_.Set(i);
+  }
+
+  inline void Set(uint32_t i) {
+    TYPE_CHECK(T, v8::Integer);
+    value_.Set(i);
+  }
+
+  // Fast JS primitive setters
+  inline void SetNull() {
+    TYPE_CHECK(T, v8::Primitive);
+    value_.SetNull();
+  }
+
+  inline void SetUndefined() {
+    TYPE_CHECK(T, v8::Primitive);
+    value_.SetUndefined();
+  }
+
+  inline void SetEmptyString() {
+    TYPE_CHECK(T, v8::String);
+    value_.SetEmptyString();
+  }
+
+  // Convenience getter for isolate
+  inline v8::Isolate *GetIsolate() const {
+    return value_.GetIsolate();
+  }
+
+  // Pointer setter: Uncompilable to prevent inadvertent misuse.
+  template<typename S>
+  inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
+};
+
+template<typename T>
+class FunctionCallbackInfo {
+  const v8::FunctionCallbackInfo<T> &info_;
+  const v8::Local<v8::Value> data_;
+
+ public:
+  explicit inline FunctionCallbackInfo(
+      const v8::FunctionCallbackInfo<T> &info
+    , v8::Local<v8::Value> data) :
+          info_(info)
+        , data_(data) {}
+
+  inline ReturnValue<T> GetReturnValue() const {
+    return ReturnValue<T>(info_.GetReturnValue());
+  }
+
+#if NODE_MAJOR_VERSION < 10
+  inline v8::Local<v8::Function> Callee() const { return info_.Callee(); }
+#endif
+  inline v8::Local<v8::Value> Data() const { return data_; }
+  inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
+  inline bool IsConstructCall() const { return info_.IsConstructCall(); }
+  inline int Length() const { return info_.Length(); }
+  inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; }
+  inline v8::Local<v8::Object> This() const { return info_.This(); }
+  inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); }
+
+
+ protected:
+  static const int kHolderIndex = 0;
+  static const int kIsolateIndex = 1;
+  static const int kReturnValueDefaultValueIndex = 2;
+  static const int kReturnValueIndex = 3;
+  static const int kDataIndex = 4;
+  static const int kCalleeIndex = 5;
+  static const int kContextSaveIndex = 6;
+  static const int kArgsLength = 7;
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
+};
+
+template<typename T>
+class PropertyCallbackInfo {
+  const v8::PropertyCallbackInfo<T> &info_;
+  const v8::Local<v8::Value> data_;
+
+ public:
+  explicit inline PropertyCallbackInfo(
+      const v8::PropertyCallbackInfo<T> &info
+    , const v8::Local<v8::Value> data) :
+          info_(info)
+        , data_(data) {}
+
+  inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
+  inline v8::Local<v8::Value> Data() const { return data_; }
+  inline v8::Local<v8::Object> This() const { return info_.This(); }
+  inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
+  inline ReturnValue<T> GetReturnValue() const {
+    return ReturnValue<T>(info_.GetReturnValue());
+  }
+
+ protected:
+  static const int kHolderIndex = 0;
+  static const int kIsolateIndex = 1;
+  static const int kReturnValueDefaultValueIndex = 2;
+  static const int kReturnValueIndex = 3;
+  static const int kDataIndex = 4;
+  static const int kThisIndex = 5;
+  static const int kArgsLength = 6;
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo)
+};
+
+namespace imp {
+static
+void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  FunctionCallback callback = reinterpret_cast<FunctionCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
+  FunctionCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  callback(cbinfo);
+}
+
+typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &);
+
+#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+static
+void GetterCallbackWrapper(
+    v8::Local<v8::Name> property
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  GetterCallback callback = reinterpret_cast<GetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
+  callback(property.As<v8::String>(), cbinfo);
+}
+
+typedef void (*NativeGetter)
+    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void SetterCallbackWrapper(
+    v8::Local<v8::Name> property
+  , v8::Local<v8::Value> value
+  , const v8::PropertyCallbackInfo<void> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<void>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  SetterCallback callback = reinterpret_cast<SetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
+  callback(property.As<v8::String>(), value, cbinfo);
+}
+
+typedef void (*NativeSetter)(
+    v8::Local<v8::Name>
+  , v8::Local<v8::Value>
+  , const v8::PropertyCallbackInfo<void> &);
+#else
+static
+void GetterCallbackWrapper(
+    v8::Local<v8::String> property
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  GetterCallback callback = reinterpret_cast<GetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
+  callback(property, cbinfo);
+}
+
+typedef void (*NativeGetter)
+    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void SetterCallbackWrapper(
+    v8::Local<v8::String> property
+  , v8::Local<v8::Value> value
+  , const v8::PropertyCallbackInfo<void> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<void>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  SetterCallback callback = reinterpret_cast<SetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
+  callback(property, value, cbinfo);
+}
+
+typedef void (*NativeSetter)(
+    v8::Local<v8::String>
+  , v8::Local<v8::Value>
+  , const v8::PropertyCallbackInfo<void> &);
+#endif
+
+#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+static
+void PropertyGetterCallbackWrapper(
+    v8::Local<v8::Name> property
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyGetterIndex)
+              .As<v8::External>()->Value()));
+  callback(property.As<v8::String>(), cbinfo);
+}
+
+typedef void (*NativePropertyGetter)
+    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void PropertySetterCallbackWrapper(
+    v8::Local<v8::Name> property
+  , v8::Local<v8::Value> value
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertySetterIndex)
+              .As<v8::External>()->Value()));
+  callback(property.As<v8::String>(), value, cbinfo);
+}
+
+typedef void (*NativePropertySetter)(
+    v8::Local<v8::Name>
+  , v8::Local<v8::Value>
+  , const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void PropertyEnumeratorCallbackWrapper(
+    const v8::PropertyCallbackInfo<v8::Array> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Array>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyEnumeratorCallback callback =
+      reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyEnumeratorIndex)
+              .As<v8::External>()->Value()));
+  callback(cbinfo);
+}
+
+typedef void (*NativePropertyEnumerator)
+    (const v8::PropertyCallbackInfo<v8::Array> &);
+
+static
+void PropertyDeleterCallbackWrapper(
+    v8::Local<v8::Name> property
+  , const v8::PropertyCallbackInfo<v8::Boolean> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Boolean>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyDeleterIndex)
+              .As<v8::External>()->Value()));
+  callback(property.As<v8::String>(), cbinfo);
+}
+
+typedef void (NativePropertyDeleter)
+    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &);
+
+static
+void PropertyQueryCallbackWrapper(
+    v8::Local<v8::Name> property
+  , const v8::PropertyCallbackInfo<v8::Integer> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Integer>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyQueryIndex)
+              .As<v8::External>()->Value()));
+  callback(property.As<v8::String>(), cbinfo);
+}
+
+typedef void (*NativePropertyQuery)
+    (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &);
+#else
+static
+void PropertyGetterCallbackWrapper(
+    v8::Local<v8::String> property
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyGetterIndex)
+              .As<v8::External>()->Value()));
+  callback(property, cbinfo);
+}
+
+typedef void (*NativePropertyGetter)
+    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void PropertySetterCallbackWrapper(
+    v8::Local<v8::String> property
+  , v8::Local<v8::Value> value
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertySetterIndex)
+              .As<v8::External>()->Value()));
+  callback(property, value, cbinfo);
+}
+
+typedef void (*NativePropertySetter)(
+    v8::Local<v8::String>
+  , v8::Local<v8::Value>
+  , const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void PropertyEnumeratorCallbackWrapper(
+    const v8::PropertyCallbackInfo<v8::Array> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Array>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyEnumeratorCallback callback =
+      reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyEnumeratorIndex)
+              .As<v8::External>()->Value()));
+  callback(cbinfo);
+}
+
+typedef void (*NativePropertyEnumerator)
+    (const v8::PropertyCallbackInfo<v8::Array> &);
+
+static
+void PropertyDeleterCallbackWrapper(
+    v8::Local<v8::String> property
+  , const v8::PropertyCallbackInfo<v8::Boolean> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Boolean>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyDeleterIndex)
+              .As<v8::External>()->Value()));
+  callback(property, cbinfo);
+}
+
+typedef void (NativePropertyDeleter)
+    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &);
+
+static
+void PropertyQueryCallbackWrapper(
+    v8::Local<v8::String> property
+  , const v8::PropertyCallbackInfo<v8::Integer> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Integer>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyQueryIndex)
+              .As<v8::External>()->Value()));
+  callback(property, cbinfo);
+}
+
+typedef void (*NativePropertyQuery)
+    (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &);
+#endif
+
+static
+void IndexGetterCallbackWrapper(
+    uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyGetterIndex)
+              .As<v8::External>()->Value()));
+  callback(index, cbinfo);
+}
+
+typedef void (*NativeIndexGetter)
+    (uint32_t, const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void IndexSetterCallbackWrapper(
+    uint32_t index
+  , v8::Local<v8::Value> value
+  , const v8::PropertyCallbackInfo<v8::Value> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertySetterIndex)
+              .As<v8::External>()->Value()));
+  callback(index, value, cbinfo);
+}
+
+typedef void (*NativeIndexSetter)(
+    uint32_t
+  , v8::Local<v8::Value>
+  , const v8::PropertyCallbackInfo<v8::Value> &);
+
+static
+void IndexEnumeratorCallbackWrapper(
+    const v8::PropertyCallbackInfo<v8::Array> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Array>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(
+              kIndexPropertyEnumeratorIndex).As<v8::External>()->Value()));
+  callback(cbinfo);
+}
+
+typedef void (*NativeIndexEnumerator)
+    (const v8::PropertyCallbackInfo<v8::Array> &);
+
+static
+void IndexDeleterCallbackWrapper(
+    uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Boolean>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyDeleterIndex)
+              .As<v8::External>()->Value()));
+  callback(index, cbinfo);
+}
+
+typedef void (*NativeIndexDeleter)
+    (uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &);
+
+static
+void IndexQueryCallbackWrapper(
+    uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Integer>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyQueryIndex)
+              .As<v8::External>()->Value()));
+  callback(index, cbinfo);
+}
+
+typedef void (*NativeIndexQuery)
+    (uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &);
+}  // end of namespace imp
+
+#endif  // NAN_CALLBACKS_12_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_callbacks_pre_12_inl.h b/node_modules/node-pty/node_modules/nan/nan_callbacks_pre_12_inl.h
new file mode 100644 (file)
index 0000000..c9ba499
--- /dev/null
@@ -0,0 +1,520 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_CALLBACKS_PRE_12_INL_H_
+#define NAN_CALLBACKS_PRE_12_INL_H_
+
+namespace imp {
+template<typename T> class ReturnValueImp;
+}  // end of namespace imp
+
+template<typename T>
+class ReturnValue {
+  v8::Isolate *isolate_;
+  v8::Persistent<T> *value_;
+  friend class imp::ReturnValueImp<T>;
+
+ public:
+  template <class S>
+  explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) :
+      isolate_(isolate), value_(p) {}
+  template <class S>
+  explicit inline ReturnValue(const ReturnValue<S>& that)
+      : isolate_(that.isolate_), value_(that.value_) {
+    TYPE_CHECK(T, S);
+  }
+
+  // Handle setters
+  template <typename S> inline void Set(const v8::Local<S> &handle) {
+    TYPE_CHECK(T, S);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(handle);
+  }
+
+  template <typename S> inline void Set(const Global<S> &handle) {
+    TYPE_CHECK(T, S);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(handle.persistent);
+    const_cast<Global<S> &>(handle).Reset();
+  }
+
+  // Fast primitive setters
+  inline void Set(bool value) {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::Boolean);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::Boolean::New(value));
+  }
+
+  inline void Set(double i) {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::Number);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::Number::New(i));
+  }
+
+  inline void Set(int32_t i) {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::Integer);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::Int32::New(i));
+  }
+
+  inline void Set(uint32_t i) {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::Integer);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::Uint32::NewFromUnsigned(i));
+  }
+
+  // Fast JS primitive setters
+  inline void SetNull() {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::Primitive);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::Null());
+  }
+
+  inline void SetUndefined() {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::Primitive);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::Undefined());
+  }
+
+  inline void SetEmptyString() {
+    v8::HandleScope scope;
+
+    TYPE_CHECK(T, v8::String);
+    value_->Dispose();
+    *value_ = v8::Persistent<T>::New(v8::String::Empty());
+  }
+
+  // Convenience getter for isolate
+  inline v8::Isolate *GetIsolate() const {
+    return isolate_;
+  }
+
+  // Pointer setter: Uncompilable to prevent inadvertent misuse.
+  template<typename S>
+  inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
+};
+
+template<typename T>
+class FunctionCallbackInfo {
+  const v8::Arguments &args_;
+  v8::Local<v8::Value> data_;
+  ReturnValue<T> return_value_;
+  v8::Persistent<T> retval_;
+
+ public:
+  explicit inline FunctionCallbackInfo(
+      const v8::Arguments &args
+    , v8::Local<v8::Value> data) :
+          args_(args)
+        , data_(data)
+        , return_value_(args.GetIsolate(), &retval_)
+        , retval_(v8::Persistent<T>::New(v8::Undefined())) {}
+
+  inline ~FunctionCallbackInfo() {
+    retval_.Dispose();
+    retval_.Clear();
+  }
+
+  inline ReturnValue<T> GetReturnValue() const {
+    return ReturnValue<T>(return_value_);
+  }
+
+  inline v8::Local<v8::Function> Callee() const { return args_.Callee(); }
+  inline v8::Local<v8::Value> Data() const { return data_; }
+  inline v8::Local<v8::Object> Holder() const { return args_.Holder(); }
+  inline bool IsConstructCall() const { return args_.IsConstructCall(); }
+  inline int Length() const { return args_.Length(); }
+  inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; }
+  inline v8::Local<v8::Object> This() const { return args_.This(); }
+  inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); }
+
+
+ protected:
+  static const int kHolderIndex = 0;
+  static const int kIsolateIndex = 1;
+  static const int kReturnValueDefaultValueIndex = 2;
+  static const int kReturnValueIndex = 3;
+  static const int kDataIndex = 4;
+  static const int kCalleeIndex = 5;
+  static const int kContextSaveIndex = 6;
+  static const int kArgsLength = 7;
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
+};
+
+template<typename T>
+class PropertyCallbackInfoBase {
+  const v8::AccessorInfo &info_;
+  const v8::Local<v8::Value> data_;
+
+ public:
+  explicit inline PropertyCallbackInfoBase(
+      const v8::AccessorInfo &info
+    , const v8::Local<v8::Value> data) :
+          info_(info)
+        , data_(data) {}
+
+  inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
+  inline v8::Local<v8::Value> Data() const { return data_; }
+  inline v8::Local<v8::Object> This() const { return info_.This(); }
+  inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
+
+ protected:
+  static const int kHolderIndex = 0;
+  static const int kIsolateIndex = 1;
+  static const int kReturnValueDefaultValueIndex = 2;
+  static const int kReturnValueIndex = 3;
+  static const int kDataIndex = 4;
+  static const int kThisIndex = 5;
+  static const int kArgsLength = 6;
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase)
+};
+
+template<typename T>
+class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
+  ReturnValue<T> return_value_;
+  v8::Persistent<T> retval_;
+
+ public:
+  explicit inline PropertyCallbackInfo(
+      const v8::AccessorInfo &info
+    , const v8::Local<v8::Value> data) :
+          PropertyCallbackInfoBase<T>(info, data)
+        , return_value_(info.GetIsolate(), &retval_)
+        , retval_(v8::Persistent<T>::New(v8::Undefined())) {}
+
+  inline ~PropertyCallbackInfo() {
+    retval_.Dispose();
+    retval_.Clear();
+  }
+
+  inline ReturnValue<T> GetReturnValue() const { return return_value_; }
+};
+
+template<>
+class PropertyCallbackInfo<v8::Array> :
+    public PropertyCallbackInfoBase<v8::Array> {
+  ReturnValue<v8::Array> return_value_;
+  v8::Persistent<v8::Array> retval_;
+
+ public:
+  explicit inline PropertyCallbackInfo(
+      const v8::AccessorInfo &info
+    , const v8::Local<v8::Value> data) :
+          PropertyCallbackInfoBase<v8::Array>(info, data)
+        , return_value_(info.GetIsolate(), &retval_)
+        , retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {}
+
+  inline ~PropertyCallbackInfo() {
+    retval_.Dispose();
+    retval_.Clear();
+  }
+
+  inline ReturnValue<v8::Array> GetReturnValue() const {
+    return return_value_;
+  }
+};
+
+template<>
+class PropertyCallbackInfo<v8::Boolean> :
+    public PropertyCallbackInfoBase<v8::Boolean> {
+  ReturnValue<v8::Boolean> return_value_;
+  v8::Persistent<v8::Boolean> retval_;
+
+ public:
+  explicit inline PropertyCallbackInfo(
+      const v8::AccessorInfo &info
+    , const v8::Local<v8::Value> data) :
+          PropertyCallbackInfoBase<v8::Boolean>(info, data)
+        , return_value_(info.GetIsolate(), &retval_)
+        , retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {}
+
+  inline ~PropertyCallbackInfo() {
+    retval_.Dispose();
+    retval_.Clear();
+  }
+
+  inline ReturnValue<v8::Boolean> GetReturnValue() const {
+    return return_value_;
+  }
+};
+
+template<>
+class PropertyCallbackInfo<v8::Integer> :
+    public PropertyCallbackInfoBase<v8::Integer> {
+  ReturnValue<v8::Integer> return_value_;
+  v8::Persistent<v8::Integer> retval_;
+
+ public:
+  explicit inline PropertyCallbackInfo(
+      const v8::AccessorInfo &info
+    , const v8::Local<v8::Value> data) :
+          PropertyCallbackInfoBase<v8::Integer>(info, data)
+        , return_value_(info.GetIsolate(), &retval_)
+        , retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {}
+
+  inline ~PropertyCallbackInfo() {
+    retval_.Dispose();
+    retval_.Clear();
+  }
+
+  inline ReturnValue<v8::Integer> GetReturnValue() const {
+    return return_value_;
+  }
+};
+
+namespace imp {
+template<typename T>
+class ReturnValueImp : public ReturnValue<T> {
+ public:
+  explicit ReturnValueImp(ReturnValue<T> that) :
+      ReturnValue<T>(that) {}
+  inline v8::Handle<T> Value() {
+      return *ReturnValue<T>::value_;
+  }
+};
+
+static
+v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) {
+  v8::Local<v8::Object> obj = args.Data().As<v8::Object>();
+  FunctionCallback callback = reinterpret_cast<FunctionCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
+  FunctionCallbackInfo<v8::Value>
+      cbinfo(args, obj->GetInternalField(kDataIndex));
+  callback(cbinfo);
+  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &);
+
+static
+v8::Handle<v8::Value> GetterCallbackWrapper(
+    v8::Local<v8::String> property, const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  GetterCallback callback = reinterpret_cast<GetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
+  callback(property, cbinfo);
+  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Value> (*NativeGetter)
+    (v8::Local<v8::String>, const v8::AccessorInfo &);
+
+static
+void SetterCallbackWrapper(
+    v8::Local<v8::String> property
+  , v8::Local<v8::Value> value
+  , const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<void>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  SetterCallback callback = reinterpret_cast<SetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
+  callback(property, value, cbinfo);
+}
+
+typedef void (*NativeSetter)
+    (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Value> PropertyGetterCallbackWrapper(
+    v8::Local<v8::String> property, const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyGetterIndex)
+              .As<v8::External>()->Value()));
+  callback(property, cbinfo);
+  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Value> (*NativePropertyGetter)
+    (v8::Local<v8::String>, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Value> PropertySetterCallbackWrapper(
+    v8::Local<v8::String> property
+  , v8::Local<v8::Value> value
+  , const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertySetterIndex)
+              .As<v8::External>()->Value()));
+  callback(property, value, cbinfo);
+  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Value> (*NativePropertySetter)
+    (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper(
+    const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Array>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyEnumeratorCallback callback =
+      reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyEnumeratorIndex)
+              .As<v8::External>()->Value()));
+  callback(cbinfo);
+  return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Array> (*NativePropertyEnumerator)
+    (const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper(
+    v8::Local<v8::String> property
+  , const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Boolean>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyDeleterIndex)
+              .As<v8::External>()->Value()));
+  callback(property, cbinfo);
+  return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Boolean> (NativePropertyDeleter)
+    (v8::Local<v8::String>, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Integer> PropertyQueryCallbackWrapper(
+    v8::Local<v8::String> property, const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Integer>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kPropertyQueryIndex)
+              .As<v8::External>()->Value()));
+  callback(property, cbinfo);
+  return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Integer> (*NativePropertyQuery)
+    (v8::Local<v8::String>, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Value> IndexGetterCallbackWrapper(
+    uint32_t index, const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyGetterIndex)
+              .As<v8::External>()->Value()));
+  callback(index, cbinfo);
+  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Value> (*NativeIndexGetter)
+    (uint32_t, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Value> IndexSetterCallbackWrapper(
+    uint32_t index
+  , v8::Local<v8::Value> value
+  , const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Value>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertySetterIndex)
+              .As<v8::External>()->Value()));
+  callback(index, value, cbinfo);
+  return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Value> (*NativeIndexSetter)
+    (uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper(
+    const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Array>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyEnumeratorIndex)
+              .As<v8::External>()->Value()));
+  callback(cbinfo);
+  return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Array> (*NativeIndexEnumerator)
+    (const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper(
+    uint32_t index, const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Boolean>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyDeleterIndex)
+              .As<v8::External>()->Value()));
+  callback(index, cbinfo);
+  return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter)
+    (uint32_t, const v8::AccessorInfo &);
+
+static
+v8::Handle<v8::Integer> IndexQueryCallbackWrapper(
+    uint32_t index, const v8::AccessorInfo &info) {
+  v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
+  PropertyCallbackInfo<v8::Integer>
+      cbinfo(info, obj->GetInternalField(kDataIndex));
+  IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
+      reinterpret_cast<intptr_t>(
+          obj->GetInternalField(kIndexPropertyQueryIndex)
+              .As<v8::External>()->Value()));
+  callback(index, cbinfo);
+  return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
+}
+
+typedef v8::Handle<v8::Integer> (*NativeIndexQuery)
+    (uint32_t, const v8::AccessorInfo &);
+}  // end of namespace imp
+
+#endif  // NAN_CALLBACKS_PRE_12_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_converters.h b/node_modules/node-pty/node_modules/nan/nan_converters.h
new file mode 100644 (file)
index 0000000..c0b3272
--- /dev/null
@@ -0,0 +1,72 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_CONVERTERS_H_
+#define NAN_CONVERTERS_H_
+
+namespace imp {
+template<typename T> struct ToFactoryBase {
+  typedef MaybeLocal<T> return_t;
+};
+template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; };
+
+template<typename T> struct ToFactory;
+
+template<>
+struct ToFactory<v8::Function> : ToFactoryBase<v8::Function> {
+  static inline return_t convert(v8::Local<v8::Value> val) {
+    if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal<v8::Function>();
+    return MaybeLocal<v8::Function>(val.As<v8::Function>());
+  }
+};
+
+#define X(TYPE)                                                                \
+    template<>                                                                 \
+    struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> {                     \
+      static inline return_t convert(v8::Local<v8::Value> val);                \
+    };
+
+X(Boolean)
+X(Number)
+X(String)
+X(Object)
+X(Integer)
+X(Uint32)
+X(Int32)
+
+#undef X
+
+#define X(TYPE)                                                                \
+    template<>                                                                 \
+    struct ToFactory<TYPE> : ValueFactoryBase<TYPE> {                          \
+      static inline return_t convert(v8::Local<v8::Value> val);                \
+    };
+
+X(bool)
+X(double)
+X(int64_t)
+X(uint32_t)
+X(int32_t)
+
+#undef X
+}  // end of namespace imp
+
+template<typename T>
+inline
+typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) {
+  return imp::ToFactory<T>::convert(val);
+}
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+# include "nan_converters_43_inl.h"
+#else
+# include "nan_converters_pre_43_inl.h"
+#endif
+
+#endif  // NAN_CONVERTERS_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_converters_43_inl.h b/node_modules/node-pty/node_modules/nan/nan_converters_43_inl.h
new file mode 100644 (file)
index 0000000..41b72de
--- /dev/null
@@ -0,0 +1,68 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_CONVERTERS_43_INL_H_
+#define NAN_CONVERTERS_43_INL_H_
+
+#define X(TYPE)                                                                \
+imp::ToFactory<v8::TYPE>::return_t                                             \
+imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) {                  \
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
+  v8::EscapableHandleScope scope(isolate);                                     \
+  return scope.Escape(                                                         \
+      val->To ## TYPE(isolate->GetCurrentContext())                            \
+          .FromMaybe(v8::Local<v8::TYPE>()));                                  \
+}
+
+X(Number)
+X(String)
+X(Object)
+X(Integer)
+X(Uint32)
+X(Int32)
+// V8 <= 7.0
+#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0)
+X(Boolean)
+#else
+imp::ToFactory<v8::Boolean>::return_t                                          \
+imp::ToFactory<v8::Boolean>::convert(v8::Local<v8::Value> val) {               \
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
+  v8::EscapableHandleScope scope(isolate);                                     \
+  return scope.Escape(val->ToBoolean(isolate));                                \
+}
+#endif
+
+#undef X
+
+#define X(TYPE, NAME)                                                          \
+imp::ToFactory<TYPE>::return_t                                                 \
+imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) {                      \
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
+  v8::HandleScope scope(isolate);                                              \
+  return val->NAME ## Value(isolate->GetCurrentContext());                     \
+}
+
+X(double, Number)
+X(int64_t, Integer)
+X(uint32_t, Uint32)
+X(int32_t, Int32)
+// V8 <= 7.0
+#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0)
+X(bool, Boolean)
+#else
+imp::ToFactory<bool>::return_t                                                 \
+imp::ToFactory<bool>::convert(v8::Local<v8::Value> val) {                      \
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();                            \
+  v8::HandleScope scope(isolate);                                              \
+  return Just<bool>(val->BooleanValue(isolate));                               \
+}
+#endif
+
+#undef X
+
+#endif  // NAN_CONVERTERS_43_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_converters_pre_43_inl.h b/node_modules/node-pty/node_modules/nan/nan_converters_pre_43_inl.h
new file mode 100644 (file)
index 0000000..ae0518a
--- /dev/null
@@ -0,0 +1,42 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_CONVERTERS_PRE_43_INL_H_
+#define NAN_CONVERTERS_PRE_43_INL_H_
+
+#define X(TYPE)                                                                \
+imp::ToFactory<v8::TYPE>::return_t                                             \
+imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) {                  \
+  return val->To ## TYPE();                                                    \
+}
+
+X(Boolean)
+X(Number)
+X(String)
+X(Object)
+X(Integer)
+X(Uint32)
+X(Int32)
+
+#undef X
+
+#define X(TYPE, NAME)                                                          \
+imp::ToFactory<TYPE>::return_t                                                 \
+imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) {                      \
+  return Just(val->NAME ## Value());                                           \
+}
+
+X(bool, Boolean)
+X(double, Number)
+X(int64_t, Integer)
+X(uint32_t, Uint32)
+X(int32_t, Int32)
+
+#undef X
+
+#endif  // NAN_CONVERTERS_PRE_43_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_define_own_property_helper.h b/node_modules/node-pty/node_modules/nan/nan_define_own_property_helper.h
new file mode 100644 (file)
index 0000000..d710ef2
--- /dev/null
@@ -0,0 +1,29 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_
+#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_
+
+namespace imp {
+
+inline Maybe<bool> DefineOwnPropertyHelper(
+    v8::PropertyAttribute current
+  , v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key
+  , v8::Handle<v8::Value> value
+  , v8::PropertyAttribute attribs = v8::None) {
+  return !(current & v8::DontDelete) ||                     // configurable OR
+                  (!(current & v8::ReadOnly) &&             // writable AND
+                   !((attribs ^ current) & ~v8::ReadOnly))  // same excluding RO
+             ? Just<bool>(obj->ForceSet(key, value, attribs))
+             : Nothing<bool>();
+}
+
+}  // end of namespace imp
+
+#endif  // NAN_DEFINE_OWN_PROPERTY_HELPER_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_implementation_12_inl.h b/node_modules/node-pty/node_modules/nan/nan_implementation_12_inl.h
new file mode 100644 (file)
index 0000000..255293a
--- /dev/null
@@ -0,0 +1,430 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_IMPLEMENTATION_12_INL_H_
+#define NAN_IMPLEMENTATION_12_INL_H_
+//==============================================================================
+// node v0.11 implementation
+//==============================================================================
+
+namespace imp {
+
+//=== Array ====================================================================
+
+Factory<v8::Array>::return_t
+Factory<v8::Array>::New() {
+  return v8::Array::New(v8::Isolate::GetCurrent());
+}
+
+Factory<v8::Array>::return_t
+Factory<v8::Array>::New(int length) {
+  return v8::Array::New(v8::Isolate::GetCurrent(), length);
+}
+
+//=== Boolean ==================================================================
+
+Factory<v8::Boolean>::return_t
+Factory<v8::Boolean>::New(bool value) {
+  return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
+}
+
+//=== Boolean Object ===========================================================
+
+Factory<v8::BooleanObject>::return_t
+Factory<v8::BooleanObject>::New(bool value) {
+#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
+  return v8::BooleanObject::New(
+    v8::Isolate::GetCurrent(), value).As<v8::BooleanObject>();
+#else
+  return v8::BooleanObject::New(value).As<v8::BooleanObject>();
+#endif
+}
+
+//=== Context ==================================================================
+
+Factory<v8::Context>::return_t
+Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
+                         , v8::Local<v8::ObjectTemplate> tmpl
+                         , v8::Local<v8::Value> obj) {
+  return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj);
+}
+
+//=== Date =====================================================================
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+Factory<v8::Date>::return_t
+Factory<v8::Date>::New(double value) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value)
+      .FromMaybe(v8::Local<v8::Value>()).As<v8::Date>());
+}
+#else
+Factory<v8::Date>::return_t
+Factory<v8::Date>::New(double value) {
+  return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>();
+}
+#endif
+
+//=== External =================================================================
+
+Factory<v8::External>::return_t
+Factory<v8::External>::New(void * value) {
+  return v8::External::New(v8::Isolate::GetCurrent(), value);
+}
+
+//=== Function =================================================================
+
+Factory<v8::Function>::return_t
+Factory<v8::Function>::New( FunctionCallback callback
+                          , v8::Local<v8::Value> data) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
+  tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
+  v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
+
+  obj->SetInternalField(
+      imp::kFunctionIndex
+    , v8::External::New(isolate, reinterpret_cast<void *>(callback)));
+
+  v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
+
+  if (!val.IsEmpty()) {
+    obj->SetInternalField(imp::kDataIndex, val);
+  }
+
+#if NODE_MAJOR_VERSION >= 10
+  v8::Local<v8::Context> context = isolate->GetCurrentContext();
+  v8::Local<v8::Function> function =
+      v8::Function::New(context, imp::FunctionCallbackWrapper, obj)
+      .ToLocalChecked();
+#else
+  v8::Local<v8::Function> function =
+      v8::Function::New(isolate, imp::FunctionCallbackWrapper, obj);
+#endif
+
+  return scope.Escape(function);
+}
+
+//=== Function Template ========================================================
+
+Factory<v8::FunctionTemplate>::return_t
+Factory<v8::FunctionTemplate>::New( FunctionCallback callback
+                                  , v8::Local<v8::Value> data
+                                  , v8::Local<v8::Signature> signature) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  if (callback) {
+    v8::EscapableHandleScope scope(isolate);
+    v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
+    tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
+    v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
+
+    obj->SetInternalField(
+        imp::kFunctionIndex
+      , v8::External::New(isolate, reinterpret_cast<void *>(callback)));
+    v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
+
+    if (!val.IsEmpty()) {
+      obj->SetInternalField(imp::kDataIndex, val);
+    }
+
+    return scope.Escape(v8::FunctionTemplate::New( isolate
+                                    , imp::FunctionCallbackWrapper
+                                    , obj
+                                    , signature));
+  } else {
+    return v8::FunctionTemplate::New(isolate, 0, data, signature);
+  }
+}
+
+//=== Number ===================================================================
+
+Factory<v8::Number>::return_t
+Factory<v8::Number>::New(double value) {
+  return v8::Number::New(v8::Isolate::GetCurrent(), value);
+}
+
+//=== Number Object ============================================================
+
+Factory<v8::NumberObject>::return_t
+Factory<v8::NumberObject>::New(double value) {
+  return v8::NumberObject::New( v8::Isolate::GetCurrent()
+                              , value).As<v8::NumberObject>();
+}
+
+//=== Integer, Int32 and Uint32 ================================================
+
+template <typename T>
+typename IntegerFactory<T>::return_t
+IntegerFactory<T>::New(int32_t value) {
+  return To<T>(T::New(v8::Isolate::GetCurrent(), value));
+}
+
+template <typename T>
+typename IntegerFactory<T>::return_t
+IntegerFactory<T>::New(uint32_t value) {
+  return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
+}
+
+Factory<v8::Uint32>::return_t
+Factory<v8::Uint32>::New(int32_t value) {
+  return To<v8::Uint32>(
+      v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
+}
+
+Factory<v8::Uint32>::return_t
+Factory<v8::Uint32>::New(uint32_t value) {
+  return To<v8::Uint32>(
+      v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
+}
+
+//=== Object ===================================================================
+
+Factory<v8::Object>::return_t
+Factory<v8::Object>::New() {
+  return v8::Object::New(v8::Isolate::GetCurrent());
+}
+
+//=== Object Template ==========================================================
+
+Factory<v8::ObjectTemplate>::return_t
+Factory<v8::ObjectTemplate>::New() {
+  return v8::ObjectTemplate::New(v8::Isolate::GetCurrent());
+}
+
+//=== RegExp ===================================================================
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+Factory<v8::RegExp>::return_t
+Factory<v8::RegExp>::New(
+    v8::Local<v8::String> pattern
+  , v8::RegExp::Flags flags) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(
+      v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags)
+          .FromMaybe(v8::Local<v8::RegExp>()));
+}
+#else
+Factory<v8::RegExp>::return_t
+Factory<v8::RegExp>::New(
+    v8::Local<v8::String> pattern
+  , v8::RegExp::Flags flags) {
+  return v8::RegExp::New(pattern, flags);
+}
+#endif
+
+//=== Script ===================================================================
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+Factory<v8::Script>::return_t
+Factory<v8::Script>::New( v8::Local<v8::String> source) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  v8::ScriptCompiler::Source src(source);
+  return scope.Escape(
+      v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src)
+          .FromMaybe(v8::Local<v8::Script>()));
+}
+
+Factory<v8::Script>::return_t
+Factory<v8::Script>::New( v8::Local<v8::String> source
+                        , v8::ScriptOrigin const& origin) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  v8::ScriptCompiler::Source src(source, origin);
+  return scope.Escape(
+      v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src)
+          .FromMaybe(v8::Local<v8::Script>()));
+}
+#else
+Factory<v8::Script>::return_t
+Factory<v8::Script>::New( v8::Local<v8::String> source) {
+  v8::ScriptCompiler::Source src(source);
+  return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
+}
+
+Factory<v8::Script>::return_t
+Factory<v8::Script>::New( v8::Local<v8::String> source
+                        , v8::ScriptOrigin const& origin) {
+  v8::ScriptCompiler::Source src(source, origin);
+  return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
+}
+#endif
+
+//=== Signature ================================================================
+
+Factory<v8::Signature>::return_t
+Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
+  return v8::Signature::New(v8::Isolate::GetCurrent(), receiver);
+}
+
+//=== String ===================================================================
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New() {
+  return v8::String::Empty(v8::Isolate::GetCurrent());
+}
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+Factory<v8::String>::return_t
+Factory<v8::String>::New(const char * value, int length) {
+  return v8::String::NewFromUtf8(
+      v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(std::string const& value) {
+  assert(value.size() <= INT_MAX && "string too long");
+  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
+      value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size()));
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(const uint16_t * value, int length) {
+  return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
+        v8::NewStringType::kNormal, length);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
+  return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(ExternalOneByteStringResource * value) {
+  return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value);
+}
+#else
+Factory<v8::String>::return_t
+Factory<v8::String>::New(const char * value, int length) {
+  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value,
+                                 v8::String::kNormalString, length);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(
+    std::string const& value) /* NOLINT(build/include_what_you_use) */ {
+  assert(value.size() <= INT_MAX && "string too long");
+  return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(),
+                                 v8::String::kNormalString,
+                                 static_cast<int>(value.size()));
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(const uint16_t * value, int length) {
+  return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
+                                    v8::String::kNormalString, length);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
+  return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(ExternalOneByteStringResource * value) {
+  return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
+}
+#endif
+
+//=== String Object ============================================================
+
+// See https://github.com/nodejs/nan/pull/811#discussion_r224594980.
+// Disable the warning as there is no way around it.
+// TODO(bnoordhuis) Use isolate-based version in Node.js v12.
+Factory<v8::StringObject>::return_t
+Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
+// V8 > 7.0
+#if V8_MAJOR_VERSION > 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION > 0)
+  return v8::StringObject::New(v8::Isolate::GetCurrent(), value)
+      .As<v8::StringObject>();
+#else
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+  return v8::StringObject::New(value).As<v8::StringObject>();
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+#endif
+}
+
+//=== Unbound Script ===========================================================
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+Factory<v8::UnboundScript>::return_t
+Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
+  v8::ScriptCompiler::Source src(source);
+  return v8::ScriptCompiler::CompileUnboundScript(
+      v8::Isolate::GetCurrent(), &src);
+}
+
+Factory<v8::UnboundScript>::return_t
+Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
+                               , v8::ScriptOrigin const& origin) {
+  v8::ScriptCompiler::Source src(source, origin);
+  return v8::ScriptCompiler::CompileUnboundScript(
+      v8::Isolate::GetCurrent(), &src);
+}
+#else
+Factory<v8::UnboundScript>::return_t
+Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
+  v8::ScriptCompiler::Source src(source);
+  return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
+}
+
+Factory<v8::UnboundScript>::return_t
+Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
+                               , v8::ScriptOrigin const& origin) {
+  v8::ScriptCompiler::Source src(source, origin);
+  return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
+}
+#endif
+
+}  // end of namespace imp
+
+//=== Presistents and Handles ==================================================
+
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+template <typename T>
+inline v8::Local<T> New(v8::Handle<T> h) {
+  return v8::Local<T>::New(v8::Isolate::GetCurrent(), h);
+}
+#endif
+
+template <typename T, typename M>
+inline v8::Local<T> New(v8::Persistent<T, M> const& p) {
+  return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
+}
+
+template <typename T, typename M>
+inline v8::Local<T> New(Persistent<T, M> const& p) {
+  return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
+}
+
+template <typename T>
+inline v8::Local<T> New(Global<T> const& p) {
+  return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
+}
+
+#endif  // NAN_IMPLEMENTATION_12_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_implementation_pre_12_inl.h b/node_modules/node-pty/node_modules/nan/nan_implementation_pre_12_inl.h
new file mode 100644 (file)
index 0000000..1472421
--- /dev/null
@@ -0,0 +1,263 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_
+#define NAN_IMPLEMENTATION_PRE_12_INL_H_
+
+//==============================================================================
+// node v0.10 implementation
+//==============================================================================
+
+namespace imp {
+
+//=== Array ====================================================================
+
+Factory<v8::Array>::return_t
+Factory<v8::Array>::New() {
+  return v8::Array::New();
+}
+
+Factory<v8::Array>::return_t
+Factory<v8::Array>::New(int length) {
+  return v8::Array::New(length);
+}
+
+//=== Boolean ==================================================================
+
+Factory<v8::Boolean>::return_t
+Factory<v8::Boolean>::New(bool value) {
+  return v8::Boolean::New(value)->ToBoolean();
+}
+
+//=== Boolean Object ===========================================================
+
+Factory<v8::BooleanObject>::return_t
+Factory<v8::BooleanObject>::New(bool value) {
+  return v8::BooleanObject::New(value).As<v8::BooleanObject>();
+}
+
+//=== Context ==================================================================
+
+Factory<v8::Context>::return_t
+Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
+                         , v8::Local<v8::ObjectTemplate> tmpl
+                         , v8::Local<v8::Value> obj) {
+  v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj);
+  v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx);
+  ctx.Dispose();
+  return lctx;
+}
+
+//=== Date =====================================================================
+
+Factory<v8::Date>::return_t
+Factory<v8::Date>::New(double value) {
+  return v8::Date::New(value).As<v8::Date>();
+}
+
+//=== External =================================================================
+
+Factory<v8::External>::return_t
+Factory<v8::External>::New(void * value) {
+  return v8::External::New(value);
+}
+
+//=== Function =================================================================
+
+Factory<v8::Function>::return_t
+Factory<v8::Function>::New( FunctionCallback callback
+                          , v8::Local<v8::Value> data) {
+  v8::HandleScope scope;
+
+  return scope.Close(Factory<v8::FunctionTemplate>::New(
+                         callback, data, v8::Local<v8::Signature>())
+                         ->GetFunction());
+}
+
+
+//=== FunctionTemplate =========================================================
+
+Factory<v8::FunctionTemplate>::return_t
+Factory<v8::FunctionTemplate>::New( FunctionCallback callback
+                                  , v8::Local<v8::Value> data
+                                  , v8::Local<v8::Signature> signature) {
+  if (callback) {
+    v8::HandleScope scope;
+
+    v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New();
+    tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
+    v8::Local<v8::Object> obj = tpl->NewInstance();
+
+    obj->SetInternalField(
+        imp::kFunctionIndex
+      , v8::External::New(reinterpret_cast<void *>(callback)));
+
+    v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data);
+
+    if (!val.IsEmpty()) {
+      obj->SetInternalField(imp::kDataIndex, val);
+    }
+
+    // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find
+    // a way. Have at it though...
+    return scope.Close(
+        v8::FunctionTemplate::New(imp::FunctionCallbackWrapper
+                                 , obj
+                                 , signature));
+  } else {
+    return v8::FunctionTemplate::New(0, data, signature);
+  }
+}
+
+//=== Number ===================================================================
+
+Factory<v8::Number>::return_t
+Factory<v8::Number>::New(double value) {
+  return v8::Number::New(value);
+}
+
+//=== Number Object ============================================================
+
+Factory<v8::NumberObject>::return_t
+Factory<v8::NumberObject>::New(double value) {
+  return v8::NumberObject::New(value).As<v8::NumberObject>();
+}
+
+//=== Integer, Int32 and Uint32 ================================================
+
+template <typename T>
+typename IntegerFactory<T>::return_t
+IntegerFactory<T>::New(int32_t value) {
+  return To<T>(T::New(value));
+}
+
+template <typename T>
+typename IntegerFactory<T>::return_t
+IntegerFactory<T>::New(uint32_t value) {
+  return To<T>(T::NewFromUnsigned(value));
+}
+
+Factory<v8::Uint32>::return_t
+Factory<v8::Uint32>::New(int32_t value) {
+  return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
+}
+
+Factory<v8::Uint32>::return_t
+Factory<v8::Uint32>::New(uint32_t value) {
+  return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
+}
+
+
+//=== Object ===================================================================
+
+Factory<v8::Object>::return_t
+Factory<v8::Object>::New() {
+  return v8::Object::New();
+}
+
+//=== Object Template ==========================================================
+
+Factory<v8::ObjectTemplate>::return_t
+Factory<v8::ObjectTemplate>::New() {
+  return v8::ObjectTemplate::New();
+}
+
+//=== RegExp ===================================================================
+
+Factory<v8::RegExp>::return_t
+Factory<v8::RegExp>::New(
+    v8::Local<v8::String> pattern
+  , v8::RegExp::Flags flags) {
+  return v8::RegExp::New(pattern, flags);
+}
+
+//=== Script ===================================================================
+
+Factory<v8::Script>::return_t
+Factory<v8::Script>::New( v8::Local<v8::String> source) {
+  return v8::Script::New(source);
+}
+Factory<v8::Script>::return_t
+Factory<v8::Script>::New( v8::Local<v8::String> source
+                        , v8::ScriptOrigin const& origin) {
+  return v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin));
+}
+
+//=== Signature ================================================================
+
+Factory<v8::Signature>::return_t
+Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
+  return v8::Signature::New(receiver);
+}
+
+//=== String ===================================================================
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New() {
+  return v8::String::Empty();
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(const char * value, int length) {
+  return v8::String::New(value, length);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(
+    std::string const& value) /* NOLINT(build/include_what_you_use) */ {
+  assert(value.size() <= INT_MAX && "string too long");
+  return v8::String::New(value.data(), static_cast<int>(value.size()));
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(const uint16_t * value, int length) {
+  return v8::String::New(value, length);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
+  return v8::String::NewExternal(value);
+}
+
+Factory<v8::String>::return_t
+Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) {
+  return v8::String::NewExternal(value);
+}
+
+//=== String Object ============================================================
+
+Factory<v8::StringObject>::return_t
+Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
+  return v8::StringObject::New(value).As<v8::StringObject>();
+}
+
+}  // end of namespace imp
+
+//=== Presistents and Handles ==================================================
+
+template <typename T>
+inline v8::Local<T> New(v8::Handle<T> h) {
+  return v8::Local<T>::New(h);
+}
+
+template <typename T>
+inline v8::Local<T> New(v8::Persistent<T> const& p) {
+  return v8::Local<T>::New(p);
+}
+
+template <typename T, typename M>
+inline v8::Local<T> New(Persistent<T, M> const& p) {
+  return v8::Local<T>::New(p.persistent);
+}
+
+template <typename T>
+inline v8::Local<T> New(Global<T> const& p) {
+  return v8::Local<T>::New(p.persistent);
+}
+
+#endif  // NAN_IMPLEMENTATION_PRE_12_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_json.h b/node_modules/node-pty/node_modules/nan/nan_json.h
new file mode 100644 (file)
index 0000000..33ac8ba
--- /dev/null
@@ -0,0 +1,166 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_JSON_H_
+#define NAN_JSON_H_
+
+#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION
+#define NAN_JSON_H_NEED_PARSE 1
+#else
+#define NAN_JSON_H_NEED_PARSE 0
+#endif  // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION
+
+#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION
+#define NAN_JSON_H_NEED_STRINGIFY 0
+#else
+#define NAN_JSON_H_NEED_STRINGIFY 1
+#endif  // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION
+
+class JSON {
+ public:
+  JSON() {
+#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY
+    Nan::HandleScope scope;
+
+    Nan::MaybeLocal<v8::Value> maybe_global_json = Nan::Get(
+      Nan::GetCurrentContext()->Global(),
+      Nan::New("JSON").ToLocalChecked()
+    );
+
+    assert(!maybe_global_json.IsEmpty() && "global JSON is empty");
+    v8::Local<v8::Value> val_global_json = maybe_global_json.ToLocalChecked();
+
+    assert(val_global_json->IsObject() && "global JSON is not an object");
+    Nan::MaybeLocal<v8::Object> maybe_obj_global_json =
+      Nan::To<v8::Object>(val_global_json);
+
+    assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty");
+    v8::Local<v8::Object> global_json = maybe_obj_global_json.ToLocalChecked();
+
+#if NAN_JSON_H_NEED_PARSE
+    Nan::MaybeLocal<v8::Value> maybe_parse_method = Nan::Get(
+      global_json, Nan::New("parse").ToLocalChecked()
+    );
+
+    assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty");
+    v8::Local<v8::Value> parse_method = maybe_parse_method.ToLocalChecked();
+
+    assert(parse_method->IsFunction() && "JSON.parse is not a function");
+    parse_cb_.Reset(parse_method.As<v8::Function>());
+#endif  // NAN_JSON_H_NEED_PARSE
+
+#if NAN_JSON_H_NEED_STRINGIFY
+    Nan::MaybeLocal<v8::Value> maybe_stringify_method = Nan::Get(
+      global_json, Nan::New("stringify").ToLocalChecked()
+    );
+
+    assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty");
+    v8::Local<v8::Value> stringify_method =
+      maybe_stringify_method.ToLocalChecked();
+
+    assert(
+      stringify_method->IsFunction() && "JSON.stringify is not a function"
+    );
+    stringify_cb_.Reset(stringify_method.As<v8::Function>());
+#endif  // NAN_JSON_H_NEED_STRINGIFY
+#endif  // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY
+  }
+
+  inline
+  Nan::MaybeLocal<v8::Value> Parse(v8::Local<v8::String> json_string) {
+    Nan::EscapableHandleScope scope;
+#if NAN_JSON_H_NEED_PARSE
+    return scope.Escape(parse(json_string));
+#else
+    Nan::MaybeLocal<v8::Value> result;
+#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \
+    NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION
+    result = v8::JSON::Parse(json_string);
+#else
+#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION
+    v8::Local<v8::Context> context_or_isolate = Nan::GetCurrentContext();
+#else
+    v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent();
+#endif  // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION
+    result = v8::JSON::Parse(context_or_isolate, json_string);
+#endif  // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION &&
+        // NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION
+    if (result.IsEmpty()) return v8::Local<v8::Value>();
+    return scope.Escape(result.ToLocalChecked());
+#endif  // NAN_JSON_H_NEED_PARSE
+  }
+
+  inline
+  Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object) {
+    Nan::EscapableHandleScope scope;
+    Nan::MaybeLocal<v8::String> result =
+#if NAN_JSON_H_NEED_STRINGIFY
+      Nan::To<v8::String>(stringify(json_object));
+#else
+      v8::JSON::Stringify(Nan::GetCurrentContext(), json_object);
+#endif  // NAN_JSON_H_NEED_STRINGIFY
+    if (result.IsEmpty()) return v8::Local<v8::String>();
+    return scope.Escape(result.ToLocalChecked());
+  }
+
+  inline
+  Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object,
+    v8::Local<v8::String> gap) {
+    Nan::EscapableHandleScope scope;
+    Nan::MaybeLocal<v8::String> result =
+#if NAN_JSON_H_NEED_STRINGIFY
+      Nan::To<v8::String>(stringify(json_object, gap));
+#else
+      v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap);
+#endif  // NAN_JSON_H_NEED_STRINGIFY
+    if (result.IsEmpty()) return v8::Local<v8::String>();
+    return scope.Escape(result.ToLocalChecked());
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON)
+#if NAN_JSON_H_NEED_PARSE
+  Nan::Callback parse_cb_;
+#endif  // NAN_JSON_H_NEED_PARSE
+#if NAN_JSON_H_NEED_STRINGIFY
+  Nan::Callback stringify_cb_;
+#endif  // NAN_JSON_H_NEED_STRINGIFY
+
+#if NAN_JSON_H_NEED_PARSE
+  inline v8::Local<v8::Value> parse(v8::Local<v8::Value> arg) {
+    assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty");
+    AsyncResource resource("nan:JSON.parse");
+    return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local<v8::Value>());
+  }
+#endif  // NAN_JSON_H_NEED_PARSE
+
+#if NAN_JSON_H_NEED_STRINGIFY
+  inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg) {
+    assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty");
+    AsyncResource resource("nan:JSON.stringify");
+    return stringify_cb_.Call(1, &arg, &resource)
+        .FromMaybe(v8::Local<v8::Value>());
+  }
+
+  inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg,
+    v8::Local<v8::String> gap) {
+    assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty");
+
+    v8::Local<v8::Value> argv[] = {
+      arg,
+      Nan::Null(),
+      gap
+    };
+    AsyncResource resource("nan:JSON.stringify");
+    return stringify_cb_.Call(3, argv, &resource)
+        .FromMaybe(v8::Local<v8::Value>());
+  }
+#endif  // NAN_JSON_H_NEED_STRINGIFY
+};
+
+#endif  // NAN_JSON_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_maybe_43_inl.h b/node_modules/node-pty/node_modules/nan/nan_maybe_43_inl.h
new file mode 100644 (file)
index 0000000..c04ce30
--- /dev/null
@@ -0,0 +1,356 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_MAYBE_43_INL_H_
+#define NAN_MAYBE_43_INL_H_
+
+template<typename T>
+using MaybeLocal = v8::MaybeLocal<T>;
+
+inline
+MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(val->ToDetailString(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::String>()));
+}
+
+inline
+MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::Uint32>()));
+}
+
+inline
+Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return a->Equals(isolate->GetCurrentContext(), b);
+}
+
+inline
+MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(h->NewInstance(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::Object>()));
+}
+
+inline
+MaybeLocal<v8::Object> NewInstance(
+      v8::Local<v8::Function> h
+    , int argc
+    , v8::Local<v8::Value> argv[]) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv)
+                          .FromMaybe(v8::Local<v8::Object>()));
+}
+
+inline
+MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(h->NewInstance(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::Object>()));
+}
+
+
+inline MaybeLocal<v8::Function> GetFunction(
+    v8::Local<v8::FunctionTemplate> t) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(t->GetFunction(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::Function>()));
+}
+
+inline Maybe<bool> Set(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::Value> key
+  , v8::Local<v8::Value> value) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->Set(isolate->GetCurrentContext(), key, value);
+}
+
+inline Maybe<bool> Set(
+    v8::Local<v8::Object> obj
+  , uint32_t index
+  , v8::Local<v8::Value> value) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->Set(isolate->GetCurrentContext(), index, value);
+}
+
+#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION
+#include "nan_define_own_property_helper.h"  // NOLINT(build/include)
+#endif
+
+inline Maybe<bool> DefineOwnProperty(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key
+  , v8::Local<v8::Value> value
+  , v8::PropertyAttribute attribs = v8::None) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION
+  return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value,
+                                attribs);
+#else
+  Maybe<v8::PropertyAttribute> maybeCurrent =
+      obj->GetPropertyAttributes(isolate->GetCurrentContext(), key);
+  if (maybeCurrent.IsNothing()) {
+    return Nothing<bool>();
+  }
+  v8::PropertyAttribute current = maybeCurrent.FromJust();
+  return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs);
+#endif
+}
+
+NAN_DEPRECATED inline Maybe<bool> ForceSet(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::Value> key
+  , v8::Local<v8::Value> value
+  , v8::PropertyAttribute attribs = v8::None) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
+  return key->IsName()
+             ? obj->DefineOwnProperty(isolate->GetCurrentContext(),
+                                      key.As<v8::Name>(), value, attribs)
+             : Nothing<bool>();
+#else
+  return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);
+#endif
+}
+
+inline MaybeLocal<v8::Value> Get(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::Value> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(obj->Get(isolate->GetCurrentContext(), key)
+                          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline
+MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(obj->Get(isolate->GetCurrentContext(), index)
+                          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline v8::PropertyAttribute GetPropertyAttributes(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::Value> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key)
+      .FromJust();
+}
+
+inline Maybe<bool> Has(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->Has(isolate->GetCurrentContext(), key);
+}
+
+inline Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->Has(isolate->GetCurrentContext(), index);
+}
+
+inline Maybe<bool> Delete(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->Delete(isolate->GetCurrentContext(), key);
+}
+
+inline
+Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->Delete(isolate->GetCurrentContext(), index);
+}
+
+inline
+MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::Array>()));
+}
+
+inline
+MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::Array>()));
+}
+
+inline Maybe<bool> SetPrototype(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::Value> prototype) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->SetPrototype(isolate->GetCurrentContext(), prototype);
+}
+
+inline MaybeLocal<v8::String> ObjectProtoToString(
+    v8::Local<v8::Object> obj) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::String>()));
+}
+
+inline Maybe<bool> HasOwnProperty(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->HasOwnProperty(isolate->GetCurrentContext(), key);
+}
+
+inline Maybe<bool> HasRealNamedProperty(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key);
+}
+
+inline Maybe<bool> HasRealIndexedProperty(
+    v8::Local<v8::Object> obj
+  , uint32_t index) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index);
+}
+
+inline Maybe<bool> HasRealNamedCallbackProperty(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key);
+}
+
+inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain(
+                             isolate->GetCurrentContext(), key)
+                          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline MaybeLocal<v8::Value> GetRealNamedProperty(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::String> key) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(
+      obj->GetRealNamedProperty(isolate->GetCurrentContext(), key)
+          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline MaybeLocal<v8::Value> CallAsFunction(
+    v8::Local<v8::Object> obj
+  , v8::Local<v8::Object> recv
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(
+      obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv)
+          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline MaybeLocal<v8::Value> CallAsConstructor(
+    v8::Local<v8::Object> obj
+  , int argc, v8::Local<v8::Value> argv[]) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(
+      obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv)
+          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+inline
+MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext())
+                          .FromMaybe(v8::Local<v8::String>()));
+}
+
+inline Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return msg->GetLineNumber(isolate->GetCurrentContext());
+}
+
+inline Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return msg->GetStartColumn(isolate->GetCurrentContext());
+}
+
+inline Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::HandleScope scope(isolate);
+  return msg->GetEndColumn(isolate->GetCurrentContext());
+}
+
+inline MaybeLocal<v8::Object> CloneElementAt(
+    v8::Local<v8::Array> array
+  , uint32_t index) {
+#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  v8::Local<v8::Context> context = isolate->GetCurrentContext();
+  v8::Local<v8::Value> elem;
+  v8::Local<v8::Object> obj;
+  if (!array->Get(context, index).ToLocal(&elem)) {
+    return scope.Escape(obj);
+  }
+  if (!elem->ToObject(context).ToLocal(&obj)) {
+    return scope.Escape(v8::Local<v8::Object>());
+  }
+  return scope.Escape(obj->Clone());
+#else
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index)
+                          .FromMaybe(v8::Local<v8::Object>()));
+#endif
+}
+
+inline MaybeLocal<v8::Value> Call(
+    v8::Local<v8::Function> fun
+  , v8::Local<v8::Object> recv
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv)
+                          .FromMaybe(v8::Local<v8::Value>()));
+}
+
+#endif  // NAN_MAYBE_43_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_maybe_pre_43_inl.h b/node_modules/node-pty/node_modules/nan/nan_maybe_pre_43_inl.h
new file mode 100644 (file)
index 0000000..83325ae
--- /dev/null
@@ -0,0 +1,268 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_MAYBE_PRE_43_INL_H_
+#define NAN_MAYBE_PRE_43_INL_H_
+
+template<typename T>
+class MaybeLocal {
+ public:
+  inline MaybeLocal() : val_(v8::Local<T>()) {}
+
+  template<typename S>
+# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
+  inline
+  MaybeLocal(v8::Local<S> that) : val_(that) {}  // NOLINT(runtime/explicit)
+# else
+  inline
+  MaybeLocal(v8::Local<S> that) :  // NOLINT(runtime/explicit)
+      val_(*reinterpret_cast<v8::Local<T>*>(&that)) {}
+# endif
+
+  inline bool IsEmpty() const { return val_.IsEmpty(); }
+
+  template<typename S>
+  inline bool ToLocal(v8::Local<S> *out) const {
+    *out = val_;
+    return !IsEmpty();
+  }
+
+  inline v8::Local<T> ToLocalChecked() const {
+#if defined(V8_ENABLE_CHECKS)
+    assert(!IsEmpty() && "ToLocalChecked is Empty");
+#endif  // V8_ENABLE_CHECKS
+    return val_;
+  }
+
+  template<typename S>
+  inline v8::Local<S> FromMaybe(v8::Local<S> default_value) const {
+    return IsEmpty() ? default_value : v8::Local<S>(val_);
+  }
+
+ private:
+  v8::Local<T> val_;
+};
+
+inline
+MaybeLocal<v8::String> ToDetailString(v8::Handle<v8::Value> val) {
+  return MaybeLocal<v8::String>(val->ToDetailString());
+}
+
+inline
+MaybeLocal<v8::Uint32> ToArrayIndex(v8::Handle<v8::Value> val) {
+  return MaybeLocal<v8::Uint32>(val->ToArrayIndex());
+}
+
+inline
+Maybe<bool> Equals(v8::Handle<v8::Value> a, v8::Handle<v8::Value>(b)) {
+  return Just<bool>(a->Equals(b));
+}
+
+inline
+MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::Function> h) {
+  return MaybeLocal<v8::Object>(h->NewInstance());
+}
+
+inline
+MaybeLocal<v8::Object> NewInstance(
+      v8::Local<v8::Function> h
+    , int argc
+    , v8::Local<v8::Value> argv[]) {
+  return MaybeLocal<v8::Object>(h->NewInstance(argc, argv));
+}
+
+inline
+MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::ObjectTemplate> h) {
+  return MaybeLocal<v8::Object>(h->NewInstance());
+}
+
+inline
+MaybeLocal<v8::Function> GetFunction(v8::Handle<v8::FunctionTemplate> t) {
+  return MaybeLocal<v8::Function>(t->GetFunction());
+}
+
+inline Maybe<bool> Set(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::Value> key
+  , v8::Handle<v8::Value> value) {
+  return Just<bool>(obj->Set(key, value));
+}
+
+inline Maybe<bool> Set(
+    v8::Handle<v8::Object> obj
+  , uint32_t index
+  , v8::Handle<v8::Value> value) {
+  return Just<bool>(obj->Set(index, value));
+}
+
+#include "nan_define_own_property_helper.h"  // NOLINT(build/include)
+
+inline Maybe<bool> DefineOwnProperty(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key
+  , v8::Handle<v8::Value> value
+  , v8::PropertyAttribute attribs = v8::None) {
+  v8::PropertyAttribute current = obj->GetPropertyAttributes(key);
+  return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs);
+}
+
+NAN_DEPRECATED inline Maybe<bool> ForceSet(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::Value> key
+  , v8::Handle<v8::Value> value
+  , v8::PropertyAttribute attribs = v8::None) {
+  return Just<bool>(obj->ForceSet(key, value, attribs));
+}
+
+inline MaybeLocal<v8::Value> Get(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::Value> key) {
+  return MaybeLocal<v8::Value>(obj->Get(key));
+}
+
+inline MaybeLocal<v8::Value> Get(
+    v8::Handle<v8::Object> obj
+  , uint32_t index) {
+  return MaybeLocal<v8::Value>(obj->Get(index));
+}
+
+inline Maybe<v8::PropertyAttribute> GetPropertyAttributes(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::Value> key) {
+  return Just<v8::PropertyAttribute>(obj->GetPropertyAttributes(key));
+}
+
+inline Maybe<bool> Has(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return Just<bool>(obj->Has(key));
+}
+
+inline Maybe<bool> Has(
+    v8::Handle<v8::Object> obj
+  , uint32_t index) {
+  return Just<bool>(obj->Has(index));
+}
+
+inline Maybe<bool> Delete(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return Just<bool>(obj->Delete(key));
+}
+
+inline Maybe<bool> Delete(
+    v8::Handle<v8::Object> obj
+  , uint32_t index) {
+  return Just<bool>(obj->Delete(index));
+}
+
+inline
+MaybeLocal<v8::Array> GetPropertyNames(v8::Handle<v8::Object> obj) {
+  return MaybeLocal<v8::Array>(obj->GetPropertyNames());
+}
+
+inline
+MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Handle<v8::Object> obj) {
+  return MaybeLocal<v8::Array>(obj->GetOwnPropertyNames());
+}
+
+inline Maybe<bool> SetPrototype(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::Value> prototype) {
+  return Just<bool>(obj->SetPrototype(prototype));
+}
+
+inline MaybeLocal<v8::String> ObjectProtoToString(
+    v8::Handle<v8::Object> obj) {
+  return MaybeLocal<v8::String>(obj->ObjectProtoToString());
+}
+
+inline Maybe<bool> HasOwnProperty(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return Just<bool>(obj->HasOwnProperty(key));
+}
+
+inline Maybe<bool> HasRealNamedProperty(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return Just<bool>(obj->HasRealNamedProperty(key));
+}
+
+inline Maybe<bool> HasRealIndexedProperty(
+    v8::Handle<v8::Object> obj
+  , uint32_t index) {
+  return Just<bool>(obj->HasRealIndexedProperty(index));
+}
+
+inline Maybe<bool> HasRealNamedCallbackProperty(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return Just<bool>(obj->HasRealNamedCallbackProperty(key));
+}
+
+inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return MaybeLocal<v8::Value>(
+      obj->GetRealNamedPropertyInPrototypeChain(key));
+}
+
+inline MaybeLocal<v8::Value> GetRealNamedProperty(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::String> key) {
+  return MaybeLocal<v8::Value>(obj->GetRealNamedProperty(key));
+}
+
+inline MaybeLocal<v8::Value> CallAsFunction(
+    v8::Handle<v8::Object> obj
+  , v8::Handle<v8::Object> recv
+  , int argc
+  , v8::Handle<v8::Value> argv[]) {
+  return MaybeLocal<v8::Value>(obj->CallAsFunction(recv, argc, argv));
+}
+
+inline MaybeLocal<v8::Value> CallAsConstructor(
+    v8::Handle<v8::Object> obj
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  return MaybeLocal<v8::Value>(obj->CallAsConstructor(argc, argv));
+}
+
+inline
+MaybeLocal<v8::String> GetSourceLine(v8::Handle<v8::Message> msg) {
+  return MaybeLocal<v8::String>(msg->GetSourceLine());
+}
+
+inline Maybe<int> GetLineNumber(v8::Handle<v8::Message> msg) {
+  return Just<int>(msg->GetLineNumber());
+}
+
+inline Maybe<int> GetStartColumn(v8::Handle<v8::Message> msg) {
+  return Just<int>(msg->GetStartColumn());
+}
+
+inline Maybe<int> GetEndColumn(v8::Handle<v8::Message> msg) {
+  return Just<int>(msg->GetEndColumn());
+}
+
+inline MaybeLocal<v8::Object> CloneElementAt(
+    v8::Handle<v8::Array> array
+  , uint32_t index) {
+  return MaybeLocal<v8::Object>(array->CloneElementAt(index));
+}
+
+inline MaybeLocal<v8::Value> Call(
+    v8::Local<v8::Function> fun
+  , v8::Local<v8::Object> recv
+  , int argc
+  , v8::Local<v8::Value> argv[]) {
+  return MaybeLocal<v8::Value>(fun->Call(recv, argc, argv));
+}
+
+#endif  // NAN_MAYBE_PRE_43_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_new.h b/node_modules/node-pty/node_modules/nan/nan_new.h
new file mode 100644 (file)
index 0000000..cdf8bbe
--- /dev/null
@@ -0,0 +1,340 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_NEW_H_
+#define NAN_NEW_H_
+
+namespace imp {  // scnr
+
+// TODO(agnat): Generalize
+template <typename T> v8::Local<T> To(v8::Local<v8::Integer> i);
+
+template <>
+inline
+v8::Local<v8::Integer>
+To<v8::Integer>(v8::Local<v8::Integer> i) {
+  return Nan::To<v8::Integer>(i).ToLocalChecked();
+}
+
+template <>
+inline
+v8::Local<v8::Int32>
+To<v8::Int32>(v8::Local<v8::Integer> i) {
+  return Nan::To<v8::Int32>(i).ToLocalChecked();
+}
+
+template <>
+inline
+v8::Local<v8::Uint32>
+To<v8::Uint32>(v8::Local<v8::Integer> i) {
+  return Nan::To<v8::Uint32>(i).ToLocalChecked();
+}
+
+template <typename T> struct FactoryBase {
+  typedef v8::Local<T> return_t;
+};
+
+template <typename T> struct MaybeFactoryBase {
+  typedef MaybeLocal<T> return_t;
+};
+
+template <typename T> struct Factory;
+
+template <>
+struct Factory<v8::Array> : FactoryBase<v8::Array> {
+  static inline return_t New();
+  static inline return_t New(int length);
+};
+
+template <>
+struct Factory<v8::Boolean> : FactoryBase<v8::Boolean> {
+  static inline return_t New(bool value);
+};
+
+template <>
+struct Factory<v8::BooleanObject> : FactoryBase<v8::BooleanObject> {
+  static inline return_t New(bool value);
+};
+
+template <>
+struct Factory<v8::Context> : FactoryBase<v8::Context> {
+  static inline
+  return_t
+  New( v8::ExtensionConfiguration* extensions = NULL
+     , v8::Local<v8::ObjectTemplate> tmpl = v8::Local<v8::ObjectTemplate>()
+     , v8::Local<v8::Value> obj = v8::Local<v8::Value>());
+};
+
+template <>
+struct Factory<v8::Date> : MaybeFactoryBase<v8::Date> {
+  static inline return_t New(double value);
+};
+
+template <>
+struct Factory<v8::External> : FactoryBase<v8::External> {
+  static inline return_t New(void *value);
+};
+
+template <>
+struct Factory<v8::Function> : FactoryBase<v8::Function> {
+  static inline
+  return_t
+  New( FunctionCallback callback
+     , v8::Local<v8::Value> data = v8::Local<v8::Value>());
+};
+
+template <>
+struct Factory<v8::FunctionTemplate> : FactoryBase<v8::FunctionTemplate> {
+  static inline
+  return_t
+  New( FunctionCallback callback = NULL
+     , v8::Local<v8::Value> data = v8::Local<v8::Value>()
+     , v8::Local<v8::Signature> signature = v8::Local<v8::Signature>());
+};
+
+template <>
+struct Factory<v8::Number> : FactoryBase<v8::Number> {
+  static inline return_t New(double value);
+};
+
+template <>
+struct Factory<v8::NumberObject> : FactoryBase<v8::NumberObject> {
+  static inline return_t New(double value);
+};
+
+template <typename T>
+struct IntegerFactory : FactoryBase<T> {
+  typedef typename FactoryBase<T>::return_t return_t;
+  static inline return_t New(int32_t value);
+  static inline return_t New(uint32_t value);
+};
+
+template <>
+struct Factory<v8::Integer> : IntegerFactory<v8::Integer> {};
+
+template <>
+struct Factory<v8::Int32> : IntegerFactory<v8::Int32> {};
+
+template <>
+struct Factory<v8::Uint32> : FactoryBase<v8::Uint32> {
+  static inline return_t New(int32_t value);
+  static inline return_t New(uint32_t value);
+};
+
+template <>
+struct Factory<v8::Object> : FactoryBase<v8::Object> {
+  static inline return_t New();
+};
+
+template <>
+struct Factory<v8::ObjectTemplate> : FactoryBase<v8::ObjectTemplate> {
+  static inline return_t New();
+};
+
+template <>
+struct Factory<v8::RegExp> : MaybeFactoryBase<v8::RegExp> {
+  static inline return_t New(
+      v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
+};
+
+template <>
+struct Factory<v8::Script> : MaybeFactoryBase<v8::Script> {
+  static inline return_t New( v8::Local<v8::String> source);
+  static inline return_t New( v8::Local<v8::String> source
+                            , v8::ScriptOrigin const& origin);
+};
+
+template <>
+struct Factory<v8::Signature> : FactoryBase<v8::Signature> {
+  typedef v8::Local<v8::FunctionTemplate> FTH;
+  static inline return_t New(FTH receiver = FTH());
+};
+
+template <>
+struct Factory<v8::String> : MaybeFactoryBase<v8::String> {
+  static inline return_t New();
+  static inline return_t New(const char *value, int length = -1);
+  static inline return_t New(const uint16_t *value, int length = -1);
+  static inline return_t New(std::string const& value);
+
+  static inline return_t New(v8::String::ExternalStringResource * value);
+  static inline return_t New(ExternalOneByteStringResource * value);
+};
+
+template <>
+struct Factory<v8::StringObject> : FactoryBase<v8::StringObject> {
+  static inline return_t New(v8::Local<v8::String> value);
+};
+
+}  // end of namespace imp
+
+#if (NODE_MODULE_VERSION >= 12)
+
+namespace imp {
+
+template <>
+struct Factory<v8::UnboundScript> : MaybeFactoryBase<v8::UnboundScript> {
+  static inline return_t New( v8::Local<v8::String> source);
+  static inline return_t New( v8::Local<v8::String> source
+                            , v8::ScriptOrigin const& origin);
+};
+
+}  // end of namespace imp
+
+# include "nan_implementation_12_inl.h"
+
+#else  // NODE_MODULE_VERSION >= 12
+
+# include "nan_implementation_pre_12_inl.h"
+
+#endif
+
+//=== API ======================================================================
+
+template <typename T>
+typename imp::Factory<T>::return_t
+New() {
+  return imp::Factory<T>::New();
+}
+
+template <typename T, typename A0>
+typename imp::Factory<T>::return_t
+New(A0 arg0) {
+  return imp::Factory<T>::New(arg0);
+}
+
+template <typename T, typename A0, typename A1>
+typename imp::Factory<T>::return_t
+New(A0 arg0, A1 arg1) {
+  return imp::Factory<T>::New(arg0, arg1);
+}
+
+template <typename T, typename A0, typename A1, typename A2>
+typename imp::Factory<T>::return_t
+New(A0 arg0, A1 arg1, A2 arg2) {
+  return imp::Factory<T>::New(arg0, arg1, arg2);
+}
+
+template <typename T, typename A0, typename A1, typename A2, typename A3>
+typename imp::Factory<T>::return_t
+New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) {
+  return imp::Factory<T>::New(arg0, arg1, arg2, arg3);
+}
+
+// Note(agnat): When passing overloaded function pointers to template functions
+// as generic arguments the compiler needs help in picking the right overload.
+// These two functions handle New<Function> and New<FunctionTemplate> with
+// all argument variations.
+
+// v8::Function and v8::FunctionTemplate with one or two arguments
+template <typename T>
+typename imp::Factory<T>::return_t
+New( FunctionCallback callback
+      , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
+    return imp::Factory<T>::New(callback, data);
+}
+
+// v8::Function and v8::FunctionTemplate with three arguments
+template <typename T, typename A2>
+typename imp::Factory<T>::return_t
+New( FunctionCallback callback
+      , v8::Local<v8::Value> data = v8::Local<v8::Value>()
+      , A2 a2 = A2()) {
+    return imp::Factory<T>::New(callback, data, a2);
+}
+
+// Convenience
+
+#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
+template <typename T> inline v8::Local<T> New(v8::Handle<T> h);
+#endif
+
+#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+template <typename T, typename M>
+    inline v8::Local<T> New(v8::Persistent<T, M> const& p);
+#else
+template <typename T> inline v8::Local<T> New(v8::Persistent<T> const& p);
+#endif
+template <typename T, typename M>
+inline v8::Local<T> New(Persistent<T, M> const& p);
+template <typename T>
+inline v8::Local<T> New(Global<T> const& p);
+
+inline
+imp::Factory<v8::Boolean>::return_t
+New(bool value) {
+  return New<v8::Boolean>(value);
+}
+
+inline
+imp::Factory<v8::Int32>::return_t
+New(int32_t value) {
+  return New<v8::Int32>(value);
+}
+
+inline
+imp::Factory<v8::Uint32>::return_t
+New(uint32_t value) {
+  return New<v8::Uint32>(value);
+}
+
+inline
+imp::Factory<v8::Number>::return_t
+New(double value) {
+  return New<v8::Number>(value);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(std::string const& value) {  // NOLINT(build/include_what_you_use)
+  return New<v8::String>(value);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(const char * value, int length) {
+  return New<v8::String>(value, length);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(const uint16_t * value, int length) {
+  return New<v8::String>(value, length);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(const char * value) {
+  return New<v8::String>(value);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(const uint16_t * value) {
+  return New<v8::String>(value);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(v8::String::ExternalStringResource * value) {
+  return New<v8::String>(value);
+}
+
+inline
+imp::Factory<v8::String>::return_t
+New(ExternalOneByteStringResource * value) {
+  return New<v8::String>(value);
+}
+
+inline
+imp::Factory<v8::RegExp>::return_t
+New(v8::Local<v8::String> pattern, v8::RegExp::Flags flags) {
+  return New<v8::RegExp>(pattern, flags);
+}
+
+#endif  // NAN_NEW_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_object_wrap.h b/node_modules/node-pty/node_modules/nan/nan_object_wrap.h
new file mode 100644 (file)
index 0000000..386affa
--- /dev/null
@@ -0,0 +1,156 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_OBJECT_WRAP_H_
+#define NAN_OBJECT_WRAP_H_
+
+class ObjectWrap {
+ public:
+  ObjectWrap() {
+    refs_ = 0;
+  }
+
+
+  virtual ~ObjectWrap() {
+    if (persistent().IsEmpty()) {
+      return;
+    }
+
+    persistent().ClearWeak();
+    persistent().Reset();
+  }
+
+
+  template <class T>
+  static inline T* Unwrap(v8::Local<v8::Object> object) {
+    assert(!object.IsEmpty());
+    assert(object->InternalFieldCount() > 0);
+    // Cast to ObjectWrap before casting to T.  A direct cast from void
+    // to T won't work right when T has more than one base class.
+    void* ptr = GetInternalFieldPointer(object, 0);
+    ObjectWrap* wrap = static_cast<ObjectWrap*>(ptr);
+    return static_cast<T*>(wrap);
+  }
+
+
+  inline v8::Local<v8::Object> handle() const {
+    return New(handle_);
+  }
+
+
+  inline Persistent<v8::Object>& persistent() {
+    return handle_;
+  }
+
+
+ protected:
+  inline void Wrap(v8::Local<v8::Object> object) {
+    assert(persistent().IsEmpty());
+    assert(object->InternalFieldCount() > 0);
+    SetInternalFieldPointer(object, 0, this);
+    persistent().Reset(object);
+    MakeWeak();
+  }
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+
+  inline void MakeWeak() {
+    persistent().v8::PersistentBase<v8::Object>::SetWeak(
+        this, WeakCallback, v8::WeakCallbackType::kParameter);
+#if NODE_MAJOR_VERSION < 10
+    // FIXME(bnoordhuis) Probably superfluous in older Node.js versions too.
+    persistent().MarkIndependent();
+#endif
+  }
+
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+
+  inline void MakeWeak() {
+    persistent().v8::PersistentBase<v8::Object>::SetWeak(this, WeakCallback);
+    persistent().MarkIndependent();
+  }
+
+#else
+
+  inline void MakeWeak() {
+    persistent().persistent.MakeWeak(this, WeakCallback);
+    persistent().MarkIndependent();
+  }
+
+#endif
+
+  /* Ref() marks the object as being attached to an event loop.
+   * Refed objects will not be garbage collected, even if
+   * all references are lost.
+   */
+  virtual void Ref() {
+    assert(!persistent().IsEmpty());
+    persistent().ClearWeak();
+    refs_++;
+  }
+
+  /* Unref() marks an object as detached from the event loop.  This is its
+   * default state.  When an object with a "weak" reference changes from
+   * attached to detached state it will be freed. Be careful not to access
+   * the object after making this call as it might be gone!
+   * (A "weak reference" means an object that only has a
+   * persistant handle.)
+   *
+   * DO NOT CALL THIS FROM DESTRUCTOR
+   */
+  virtual void Unref() {
+    assert(!persistent().IsEmpty());
+    assert(!persistent().IsWeak());
+    assert(refs_ > 0);
+    if (--refs_ == 0)
+      MakeWeak();
+  }
+
+  int refs_;  // ro
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap)
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+
+  static void
+  WeakCallback(v8::WeakCallbackInfo<ObjectWrap> const& info) {
+    ObjectWrap* wrap = info.GetParameter();
+    assert(wrap->refs_ == 0);
+    wrap->handle_.Reset();
+    delete wrap;
+  }
+
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+
+  static void
+  WeakCallback(v8::WeakCallbackData<v8::Object, ObjectWrap> const& data) {
+    ObjectWrap* wrap = data.GetParameter();
+    assert(wrap->refs_ == 0);
+    assert(wrap->handle_.IsNearDeath());
+    wrap->handle_.Reset();
+    delete wrap;
+  }
+
+#else
+
+  static void WeakCallback(v8::Persistent<v8::Value> value, void *data) {
+    ObjectWrap *wrap = static_cast<ObjectWrap*>(data);
+    assert(wrap->refs_ == 0);
+    assert(wrap->handle_.IsNearDeath());
+    wrap->handle_.Reset();
+    delete wrap;
+  }
+
+#endif
+  Persistent<v8::Object> handle_;
+};
+
+
+#endif  // NAN_OBJECT_WRAP_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_persistent_12_inl.h b/node_modules/node-pty/node_modules/nan/nan_persistent_12_inl.h
new file mode 100644 (file)
index 0000000..d9649e8
--- /dev/null
@@ -0,0 +1,132 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_PERSISTENT_12_INL_H_
+#define NAN_PERSISTENT_12_INL_H_
+
+template<typename T, typename M> class Persistent :
+    public v8::Persistent<T, M> {
+ public:
+  inline Persistent() : v8::Persistent<T, M>() {}
+
+  template<typename S> inline Persistent(v8::Local<S> that) :
+      v8::Persistent<T, M>(v8::Isolate::GetCurrent(), that) {}
+
+  template<typename S, typename M2>
+  inline
+  Persistent(const v8::Persistent<S, M2> &that) :  // NOLINT(runtime/explicit)
+      v8::Persistent<T, M2>(v8::Isolate::GetCurrent(), that) {}
+
+  inline void Reset() { v8::PersistentBase<T>::Reset(); }
+
+  template <typename S>
+  inline void Reset(const v8::Local<S> &other) {
+    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
+  }
+
+  template <typename S>
+  inline void Reset(const v8::PersistentBase<S> &other) {
+    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
+  }
+
+  template<typename P>
+  inline void SetWeak(
+    P *parameter
+    , typename WeakCallbackInfo<P>::Callback callback
+    , WeakCallbackType type);
+
+ private:
+  inline T *operator*() const { return *PersistentBase<T>::persistent; }
+
+  template<typename S, typename M2>
+  inline void Copy(const Persistent<S, M2> &that) {
+    TYPE_CHECK(T, S);
+
+    this->Reset();
+
+    if (!that.IsEmpty()) {
+      this->Reset(that);
+      M::Copy(that, this);
+    }
+  }
+};
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+template<typename T>
+class Global : public v8::Global<T> {
+ public:
+  inline Global() : v8::Global<T>() {}
+
+  template<typename S> inline Global(v8::Local<S> that) :
+    v8::Global<T>(v8::Isolate::GetCurrent(), that) {}
+
+  template<typename S>
+  inline
+  Global(const v8::PersistentBase<S> &that) :  // NOLINT(runtime/explicit)
+      v8::Global<S>(v8::Isolate::GetCurrent(), that) {}
+
+  inline void Reset() { v8::PersistentBase<T>::Reset(); }
+
+  template <typename S>
+  inline void Reset(const v8::Local<S> &other) {
+    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
+  }
+
+  template <typename S>
+  inline void Reset(const v8::PersistentBase<S> &other) {
+    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
+  }
+
+  template<typename P>
+  inline void SetWeak(
+    P *parameter
+    , typename WeakCallbackInfo<P>::Callback callback
+    , WeakCallbackType type) {
+    reinterpret_cast<Persistent<T>*>(this)->SetWeak(
+        parameter, callback, type);
+  }
+};
+#else
+template<typename T>
+class Global : public v8::UniquePersistent<T> {
+ public:
+  inline Global() : v8::UniquePersistent<T>() {}
+
+  template<typename S> inline Global(v8::Local<S> that) :
+    v8::UniquePersistent<T>(v8::Isolate::GetCurrent(), that) {}
+
+  template<typename S>
+  inline
+  Global(const v8::PersistentBase<S> &that) :  // NOLINT(runtime/explicit)
+      v8::UniquePersistent<S>(v8::Isolate::GetCurrent(), that) {}
+
+  inline void Reset() { v8::PersistentBase<T>::Reset(); }
+
+  template <typename S>
+  inline void Reset(const v8::Local<S> &other) {
+    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
+  }
+
+  template <typename S>
+  inline void Reset(const v8::PersistentBase<S> &other) {
+    v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
+  }
+
+  template<typename P>
+  inline void SetWeak(
+    P *parameter
+    , typename WeakCallbackInfo<P>::Callback callback
+    , WeakCallbackType type) {
+    reinterpret_cast<Persistent<T>*>(this)->SetWeak(
+        parameter, callback, type);
+  }
+};
+#endif
+
+#endif  // NAN_PERSISTENT_12_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_persistent_pre_12_inl.h b/node_modules/node-pty/node_modules/nan/nan_persistent_pre_12_inl.h
new file mode 100644 (file)
index 0000000..4c9c59d
--- /dev/null
@@ -0,0 +1,242 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_PERSISTENT_PRE_12_INL_H_
+#define NAN_PERSISTENT_PRE_12_INL_H_
+
+template<typename T>
+class PersistentBase {
+  v8::Persistent<T> persistent;
+  template<typename U>
+  friend v8::Local<U> New(const PersistentBase<U> &p);
+  template<typename U, typename M>
+  friend v8::Local<U> New(const Persistent<U, M> &p);
+  template<typename U>
+  friend v8::Local<U> New(const Global<U> &p);
+  template<typename S> friend class ReturnValue;
+
+ public:
+  inline PersistentBase() :
+      persistent() {}
+
+  inline void Reset() {
+    persistent.Dispose();
+    persistent.Clear();
+  }
+
+  template<typename S>
+  inline void Reset(const v8::Local<S> &other) {
+    TYPE_CHECK(T, S);
+
+    if (!persistent.IsEmpty()) {
+      persistent.Dispose();
+    }
+
+    if (other.IsEmpty()) {
+      persistent.Clear();
+    } else {
+      persistent = v8::Persistent<T>::New(other);
+    }
+  }
+
+  template<typename S>
+  inline void Reset(const PersistentBase<S> &other) {
+    TYPE_CHECK(T, S);
+
+    if (!persistent.IsEmpty()) {
+      persistent.Dispose();
+    }
+
+    if (other.IsEmpty()) {
+      persistent.Clear();
+    } else {
+      persistent = v8::Persistent<T>::New(other.persistent);
+    }
+  }
+
+  inline bool IsEmpty() const { return persistent.IsEmpty(); }
+
+  inline void Empty() { persistent.Clear(); }
+
+  template<typename S>
+  inline bool operator==(const PersistentBase<S> &that) const {
+    return this->persistent == that.persistent;
+  }
+
+  template<typename S>
+  inline bool operator==(const v8::Local<S> &that) const {
+    return this->persistent == that;
+  }
+
+  template<typename S>
+  inline bool operator!=(const PersistentBase<S> &that) const {
+    return !operator==(that);
+  }
+
+  template<typename S>
+  inline bool operator!=(const v8::Local<S> &that) const {
+    return !operator==(that);
+  }
+
+  template<typename P>
+  inline void SetWeak(
+    P *parameter
+    , typename WeakCallbackInfo<P>::Callback callback
+    , WeakCallbackType type);
+
+  inline void ClearWeak() { persistent.ClearWeak(); }
+
+  inline void MarkIndependent() { persistent.MarkIndependent(); }
+
+  inline bool IsIndependent() const { return persistent.IsIndependent(); }
+
+  inline bool IsNearDeath() const { return persistent.IsNearDeath(); }
+
+  inline bool IsWeak() const { return persistent.IsWeak(); }
+
+ private:
+  inline explicit PersistentBase(v8::Persistent<T> that) :
+      persistent(that) { }
+  inline explicit PersistentBase(T *val) : persistent(val) {}
+  template<typename S, typename M> friend class Persistent;
+  template<typename S> friend class Global;
+  friend class ObjectWrap;
+};
+
+template<typename T>
+class NonCopyablePersistentTraits {
+ public:
+  typedef Persistent<T, NonCopyablePersistentTraits<T> >
+      NonCopyablePersistent;
+  static const bool kResetInDestructor = false;
+  template<typename S, typename M>
+  inline static void Copy(const Persistent<S, M> &source,
+                             NonCopyablePersistent *dest) {
+    Uncompilable<v8::Object>();
+  }
+
+  template<typename O> inline static void Uncompilable() {
+    TYPE_CHECK(O, v8::Primitive);
+  }
+};
+
+template<typename T>
+struct CopyablePersistentTraits {
+  typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
+  static const bool kResetInDestructor = true;
+  template<typename S, typename M>
+  static inline void Copy(const Persistent<S, M> &source,
+                             CopyablePersistent *dest) {}
+};
+
+template<typename T, typename M> class Persistent :
+    public PersistentBase<T> {
+ public:
+  inline Persistent() {}
+
+  template<typename S> inline Persistent(v8::Handle<S> that)
+      : PersistentBase<T>(v8::Persistent<T>::New(that)) {
+    TYPE_CHECK(T, S);
+  }
+
+  inline Persistent(const Persistent &that) : PersistentBase<T>() {
+    Copy(that);
+  }
+
+  template<typename S, typename M2>
+  inline Persistent(const Persistent<S, M2> &that) :
+      PersistentBase<T>() {
+    Copy(that);
+  }
+
+  inline Persistent &operator=(const Persistent &that) {
+    Copy(that);
+    return *this;
+  }
+
+  template <class S, class M2>
+  inline Persistent &operator=(const Persistent<S, M2> &that) {
+    Copy(that);
+    return *this;
+  }
+
+  inline ~Persistent() {
+    if (M::kResetInDestructor) this->Reset();
+  }
+
+ private:
+  inline T *operator*() const { return *PersistentBase<T>::persistent; }
+
+  template<typename S, typename M2>
+  inline void Copy(const Persistent<S, M2> &that) {
+    TYPE_CHECK(T, S);
+
+    this->Reset();
+
+    if (!that.IsEmpty()) {
+      this->persistent = v8::Persistent<T>::New(that.persistent);
+      M::Copy(that, this);
+    }
+  }
+};
+
+template<typename T>
+class Global : public PersistentBase<T> {
+  struct RValue {
+    inline explicit RValue(Global* obj) : object(obj) {}
+    Global* object;
+  };
+
+ public:
+  inline Global() : PersistentBase<T>(0) { }
+
+  template <typename S>
+  inline Global(v8::Local<S> that)  // NOLINT(runtime/explicit)
+      : PersistentBase<T>(v8::Persistent<T>::New(that)) {
+    TYPE_CHECK(T, S);
+  }
+
+  template <typename S>
+  inline Global(const PersistentBase<S> &that)  // NOLINT(runtime/explicit)
+    : PersistentBase<T>(that) {
+    TYPE_CHECK(T, S);
+  }
+  /**
+   * Move constructor.
+   */
+  inline Global(RValue rvalue)  // NOLINT(runtime/explicit)
+    : PersistentBase<T>(rvalue.object->persistent) {
+    rvalue.object->Reset();
+  }
+  inline ~Global() { this->Reset(); }
+  /**
+   * Move via assignment.
+   */
+  template<typename S>
+  inline Global &operator=(Global<S> rhs) {
+    TYPE_CHECK(T, S);
+    this->Reset(rhs.persistent);
+    rhs.Reset();
+    return *this;
+  }
+  /**
+   * Cast operator for moves.
+   */
+  inline operator RValue() { return RValue(this); }
+  /**
+   * Pass allows returning uniques from functions, etc.
+   */
+  Global Pass() { return Global(RValue(this)); }
+
+ private:
+  Global(Global &);
+  void operator=(Global &);
+  template<typename S> friend class ReturnValue;
+};
+
+#endif  // NAN_PERSISTENT_PRE_12_INL_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_private.h b/node_modules/node-pty/node_modules/nan/nan_private.h
new file mode 100644 (file)
index 0000000..15f44cc
--- /dev/null
@@ -0,0 +1,73 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_PRIVATE_H_
+#define NAN_PRIVATE_H_
+
+inline Maybe<bool>
+HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) {
+  HandleScope scope;
+#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::Local<v8::Context> context = isolate->GetCurrentContext();
+  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
+  return object->HasPrivate(context, private_key);
+#else
+  return Just(!object->GetHiddenValue(key).IsEmpty());
+#endif
+}
+
+inline MaybeLocal<v8::Value>
+GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) {
+#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::EscapableHandleScope scope(isolate);
+  v8::Local<v8::Context> context = isolate->GetCurrentContext();
+  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
+  v8::MaybeLocal<v8::Value> v = object->GetPrivate(context, private_key);
+  return scope.Escape(v.ToLocalChecked());
+#else
+  EscapableHandleScope scope;
+  v8::Local<v8::Value> v = object->GetHiddenValue(key);
+  if (v.IsEmpty()) {
+    v = Undefined();
+  }
+  return scope.Escape(v);
+#endif
+}
+
+inline Maybe<bool> SetPrivate(
+    v8::Local<v8::Object> object,
+    v8::Local<v8::String> key,
+    v8::Local<v8::Value> value) {
+#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
+  HandleScope scope;
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::Local<v8::Context> context = isolate->GetCurrentContext();
+  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
+  return object->SetPrivate(context, private_key, value);
+#else
+  return Just(object->SetHiddenValue(key, value));
+#endif
+}
+
+inline Maybe<bool> DeletePrivate(
+    v8::Local<v8::Object> object,
+    v8::Local<v8::String> key) {
+#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION
+  HandleScope scope;
+  v8::Isolate *isolate = v8::Isolate::GetCurrent();
+  v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
+  return object->DeletePrivate(isolate->GetCurrentContext(), private_key);
+#else
+  return Just(object->DeleteHiddenValue(key));
+#endif
+}
+
+#endif  // NAN_PRIVATE_H_
+
diff --git a/node_modules/node-pty/node_modules/nan/nan_string_bytes.h b/node_modules/node-pty/node_modules/nan/nan_string_bytes.h
new file mode 100644 (file)
index 0000000..a2e6437
--- /dev/null
@@ -0,0 +1,305 @@
+// 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.
+
+#ifndef NAN_STRING_BYTES_H_
+#define NAN_STRING_BYTES_H_
+
+// Decodes a v8::Local<v8::String> or Buffer to a raw char*
+
+namespace imp {
+
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+
+//// Base 64 ////
+
+#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4)
+
+
+
+//// HEX ////
+
+static bool contains_non_ascii_slow(const char* buf, size_t len) {
+  for (size_t i = 0; i < len; ++i) {
+    if (buf[i] & 0x80) return true;
+  }
+  return false;
+}
+
+
+static bool contains_non_ascii(const char* src, size_t len) {
+  if (len < 16) {
+    return contains_non_ascii_slow(src, len);
+  }
+
+  const unsigned bytes_per_word = sizeof(void*);
+  const unsigned align_mask = bytes_per_word - 1;
+  const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
+
+  if (unaligned > 0) {
+    const unsigned n = bytes_per_word - unaligned;
+    if (contains_non_ascii_slow(src, n)) return true;
+    src += n;
+    len -= n;
+  }
+
+
+#if defined(__x86_64__) || defined(_WIN64)
+  const uintptr_t mask = 0x8080808080808080ll;
+#else
+  const uintptr_t mask = 0x80808080l;
+#endif
+
+  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
+
+  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
+    if (srcw[i] & mask) return true;
+  }
+
+  const unsigned remainder = len & align_mask;
+  if (remainder > 0) {
+    const size_t offset = len - remainder;
+    if (contains_non_ascii_slow(src + offset, remainder)) return true;
+  }
+
+  return false;
+}
+
+
+static void force_ascii_slow(const char* src, char* dst, size_t len) {
+  for (size_t i = 0; i < len; ++i) {
+    dst[i] = src[i] & 0x7f;
+  }
+}
+
+
+static void force_ascii(const char* src, char* dst, size_t len) {
+  if (len < 16) {
+    force_ascii_slow(src, dst, len);
+    return;
+  }
+
+  const unsigned bytes_per_word = sizeof(void*);
+  const unsigned align_mask = bytes_per_word - 1;
+  const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
+  const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
+
+  if (src_unalign > 0) {
+    if (src_unalign == dst_unalign) {
+      const unsigned unalign = bytes_per_word - src_unalign;
+      force_ascii_slow(src, dst, unalign);
+      src += unalign;
+      dst += unalign;
+      len -= src_unalign;
+    } else {
+      force_ascii_slow(src, dst, len);
+      return;
+    }
+  }
+
+#if defined(__x86_64__) || defined(_WIN64)
+  const uintptr_t mask = ~0x8080808080808080ll;
+#else
+  const uintptr_t mask = ~0x80808080l;
+#endif
+
+  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
+  uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
+
+  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
+    dstw[i] = srcw[i] & mask;
+  }
+
+  const unsigned remainder = len & align_mask;
+  if (remainder > 0) {
+    const size_t offset = len - remainder;
+    force_ascii_slow(src + offset, dst + offset, remainder);
+  }
+}
+
+
+static size_t base64_encode(const char* src,
+                            size_t slen,
+                            char* dst,
+                            size_t dlen) {
+  // We know how much we'll write, just make sure that there's space.
+  assert(dlen >= base64_encoded_size(slen) &&
+      "not enough space provided for base64 encode");
+
+  dlen = base64_encoded_size(slen);
+
+  unsigned a;
+  unsigned b;
+  unsigned c;
+  unsigned i;
+  unsigned k;
+  unsigned n;
+
+  static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                              "abcdefghijklmnopqrstuvwxyz"
+                              "0123456789+/";
+
+  i = 0;
+  k = 0;
+  n = slen / 3 * 3;
+
+  while (i < n) {
+    a = src[i + 0] & 0xff;
+    b = src[i + 1] & 0xff;
+    c = src[i + 2] & 0xff;
+
+    dst[k + 0] = table[a >> 2];
+    dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
+    dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)];
+    dst[k + 3] = table[c & 0x3f];
+
+    i += 3;
+    k += 4;
+  }
+
+  if (n != slen) {
+    switch (slen - n) {
+      case 1:
+        a = src[i + 0] & 0xff;
+        dst[k + 0] = table[a >> 2];
+        dst[k + 1] = table[(a & 3) << 4];
+        dst[k + 2] = '=';
+        dst[k + 3] = '=';
+        break;
+
+      case 2:
+        a = src[i + 0] & 0xff;
+        b = src[i + 1] & 0xff;
+        dst[k + 0] = table[a >> 2];
+        dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
+        dst[k + 2] = table[(b & 0x0f) << 2];
+        dst[k + 3] = '=';
+        break;
+    }
+  }
+
+  return dlen;
+}
+
+
+static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
+  // We know how much we'll write, just make sure that there's space.
+  assert(dlen >= slen * 2 &&
+      "not enough space provided for hex encode");
+
+  dlen = slen * 2;
+  for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
+    static const char hex[] = "0123456789abcdef";
+    uint8_t val = static_cast<uint8_t>(src[i]);
+    dst[k + 0] = hex[val >> 4];
+    dst[k + 1] = hex[val & 15];
+  }
+
+  return dlen;
+}
+
+
+
+static Local<Value> Encode(const char* buf,
+                           size_t buflen,
+                           enum Encoding encoding) {
+  assert(buflen <= node::Buffer::kMaxLength);
+  if (!buflen && encoding != BUFFER)
+    return New("").ToLocalChecked();
+
+  Local<String> val;
+  switch (encoding) {
+    case BUFFER:
+      return CopyBuffer(buf, buflen).ToLocalChecked();
+
+    case ASCII:
+      if (contains_non_ascii(buf, buflen)) {
+        char* out = new char[buflen];
+        force_ascii(buf, out, buflen);
+        val = New<String>(out, buflen).ToLocalChecked();
+        delete[] out;
+      } else {
+        val = New<String>(buf, buflen).ToLocalChecked();
+      }
+      break;
+
+    case UTF8:
+      val = New<String>(buf, buflen).ToLocalChecked();
+      break;
+
+    case BINARY: {
+      // TODO(isaacs) use ExternalTwoByteString?
+      const unsigned char *cbuf = reinterpret_cast<const unsigned char*>(buf);
+      uint16_t * twobytebuf = new uint16_t[buflen];
+      for (size_t i = 0; i < buflen; i++) {
+        // XXX is the following line platform independent?
+        twobytebuf[i] = cbuf[i];
+      }
+      val = New<String>(twobytebuf, buflen).ToLocalChecked();
+      delete[] twobytebuf;
+      break;
+    }
+
+    case BASE64: {
+      size_t dlen = base64_encoded_size(buflen);
+      char* dst = new char[dlen];
+
+      size_t written = base64_encode(buf, buflen, dst, dlen);
+      assert(written == dlen);
+
+      val = New<String>(dst, dlen).ToLocalChecked();
+      delete[] dst;
+      break;
+    }
+
+    case UCS2: {
+      const uint16_t* data = reinterpret_cast<const uint16_t*>(buf);
+      val = New<String>(data, buflen / 2).ToLocalChecked();
+      break;
+    }
+
+    case HEX: {
+      size_t dlen = buflen * 2;
+      char* dst = new char[dlen];
+      size_t written = hex_encode(buf, buflen, dst, dlen);
+      assert(written == dlen);
+
+      val = New<String>(dst, dlen).ToLocalChecked();
+      delete[] dst;
+      break;
+    }
+
+    default:
+      assert(0 && "unknown encoding");
+      break;
+  }
+
+  return val;
+}
+
+#undef base64_encoded_size
+
+}  // end of namespace imp
+
+#endif  // NAN_STRING_BYTES_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_typedarray_contents.h b/node_modules/node-pty/node_modules/nan/nan_typedarray_contents.h
new file mode 100644 (file)
index 0000000..d28ae32
--- /dev/null
@@ -0,0 +1,90 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_TYPEDARRAY_CONTENTS_H_
+#define NAN_TYPEDARRAY_CONTENTS_H_
+
+template<typename T>
+class TypedArrayContents {
+ public:
+  inline explicit TypedArrayContents(v8::Local<v8::Value> from) :
+      length_(0), data_(NULL) {
+    HandleScope scope;
+
+    size_t length = 0;
+    void*  data = NULL;
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+
+    if (from->IsArrayBufferView()) {
+      v8::Local<v8::ArrayBufferView> array =
+        v8::Local<v8::ArrayBufferView>::Cast(from);
+
+      const size_t    byte_length = array->ByteLength();
+      const ptrdiff_t byte_offset = array->ByteOffset();
+      v8::Local<v8::ArrayBuffer> buffer = array->Buffer();
+
+      length = byte_length / sizeof(T);
+      data   = static_cast<char*>(buffer->GetContents().Data()) + byte_offset;
+    }
+
+#else
+
+    if (from->IsObject() && !from->IsNull()) {
+      v8::Local<v8::Object> array = v8::Local<v8::Object>::Cast(from);
+
+      MaybeLocal<v8::Value> buffer = Get(array,
+        New<v8::String>("buffer").ToLocalChecked());
+      MaybeLocal<v8::Value> byte_length = Get(array,
+        New<v8::String>("byteLength").ToLocalChecked());
+      MaybeLocal<v8::Value> byte_offset = Get(array,
+        New<v8::String>("byteOffset").ToLocalChecked());
+
+      if (!buffer.IsEmpty() &&
+          !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() &&
+          !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) {
+        data = array->GetIndexedPropertiesExternalArrayData();
+        if(data) {
+          length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T);
+        }
+      }
+    }
+
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L
+    assert(reinterpret_cast<uintptr_t>(data) % alignof (T) == 0);
+#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__)
+    assert(reinterpret_cast<uintptr_t>(data) % __alignof(T) == 0);
+#else
+    assert(reinterpret_cast<uintptr_t>(data) % sizeof (T) == 0);
+#endif
+
+    length_ = length;
+    data_   = static_cast<T*>(data);
+  }
+
+  inline size_t length() const      { return length_; }
+  inline T* operator*()             { return data_;   }
+  inline const T* operator*() const { return data_;   }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents)
+
+  //Disable heap allocation
+  void *operator new(size_t size);
+  void operator delete(void *, size_t) {
+    abort();
+  }
+
+  size_t  length_;
+  T*      data_;
+};
+
+#endif  // NAN_TYPEDARRAY_CONTENTS_H_
diff --git a/node_modules/node-pty/node_modules/nan/nan_weak.h b/node_modules/node-pty/node_modules/nan/nan_weak.h
new file mode 100644 (file)
index 0000000..7e7ab07
--- /dev/null
@@ -0,0 +1,437 @@
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+#ifndef NAN_WEAK_H_
+#define NAN_WEAK_H_
+
+static const int kInternalFieldsInWeakCallback = 2;
+static const int kNoInternalFieldIndex = -1;
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
+    v8::WeakCallbackInfo<WeakCallbackInfo<T> > const&
+# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
+    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
+#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION
+# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
+    v8::PhantomCallbackData<WeakCallbackInfo<T> > const&
+# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
+    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
+#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
+    v8::PhantomCallbackData<WeakCallbackInfo<T> > const&
+# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
+    v8::InternalFieldsCallbackData<WeakCallbackInfo<T>, void> const&
+# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+# define NAN_WEAK_CALLBACK_DATA_TYPE_ \
+    v8::WeakCallbackData<S, WeakCallbackInfo<T> > const&
+# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_
+#else
+# define NAN_WEAK_CALLBACK_DATA_TYPE_ void *
+# define NAN_WEAK_CALLBACK_SIG_ \
+    v8::Persistent<v8::Value>, NAN_WEAK_CALLBACK_DATA_TYPE_
+#endif
+
+template<typename T>
+class WeakCallbackInfo {
+ public:
+  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
+  WeakCallbackInfo(
+      Persistent<v8::Value> *persistent
+    , Callback callback
+    , void *parameter
+    , void *field1 = 0
+    , void *field2 = 0) :
+        callback_(callback), isolate_(0), parameter_(parameter) {
+    std::memcpy(&persistent_, persistent, sizeof (v8::Persistent<v8::Value>));
+    internal_fields_[0] = field1;
+    internal_fields_[1] = field2;
+  }
+  inline v8::Isolate *GetIsolate() const { return isolate_; }
+  inline T *GetParameter() const { return static_cast<T*>(parameter_); }
+  inline void *GetInternalField(int index) const {
+    assert((index == 0 || index == 1) && "internal field index out of bounds");
+    if (index == 0) {
+      return internal_fields_[0];
+    } else {
+      return internal_fields_[1];
+    }
+  }
+
+ private:
+  NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo)
+  Callback callback_;
+  v8::Isolate *isolate_;
+  void *parameter_;
+  void *internal_fields_[kInternalFieldsInWeakCallback];
+  v8::Persistent<v8::Value> persistent_;
+  template<typename S, typename M> friend class Persistent;
+  template<typename S> friend class PersistentBase;
+#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION
+# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+  template<typename S>
+  static void invoke(NAN_WEAK_CALLBACK_SIG_ data);
+  template<typename S>
+  static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data);
+# else
+  static void invoke(NAN_WEAK_CALLBACK_SIG_ data);
+  static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data);
+# endif
+#else
+# if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                     \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+  template<bool isFirstPass>
+  static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data);
+  template<bool isFirstPass>
+  static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data);
+# else
+  static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data);
+  static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data);
+# endif
+  static WeakCallbackInfo *unwrapparameter(
+      NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data);
+  static WeakCallbackInfo *unwraptwofield(
+      NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data);
+#endif
+};
+
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+
+template<typename T>
+template<bool isFirstPass>
+void
+WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) {
+  WeakCallbackInfo<T> *cbinfo = unwrapparameter(data);
+  if (isFirstPass) {
+    cbinfo->persistent_.Reset();
+    data.SetSecondPassCallback(invokeparameter<false>);
+  } else {
+    cbinfo->callback_(*cbinfo);
+    delete cbinfo;
+  }
+}
+
+template<typename T>
+template<bool isFirstPass>
+void
+WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) {
+  WeakCallbackInfo<T> *cbinfo = unwraptwofield(data);
+  if (isFirstPass) {
+    cbinfo->persistent_.Reset();
+    data.SetSecondPassCallback(invoketwofield<false>);
+  } else {
+    cbinfo->callback_(*cbinfo);
+    delete cbinfo;
+  }
+}
+
+template<typename T>
+WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter(
+    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) {
+  WeakCallbackInfo<T> *cbinfo =
+      static_cast<WeakCallbackInfo<T>*>(data.GetParameter());
+  cbinfo->isolate_ = data.GetIsolate();
+  return cbinfo;
+}
+
+template<typename T>
+WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield(
+    NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) {
+  WeakCallbackInfo<T> *cbinfo =
+      static_cast<WeakCallbackInfo<T>*>(data.GetInternalField(0));
+  cbinfo->isolate_ = data.GetIsolate();
+  return cbinfo;
+}
+
+#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_
+#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_
+#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
+# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+
+template<typename T>
+void
+WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) {
+  WeakCallbackInfo<T> *cbinfo = unwrapparameter(data);
+  cbinfo->persistent_.Reset();
+  cbinfo->callback_(*cbinfo);
+  delete cbinfo;
+}
+
+template<typename T>
+void
+WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) {
+  WeakCallbackInfo<T> *cbinfo = unwraptwofield(data);
+  cbinfo->persistent_.Reset();
+  cbinfo->callback_(*cbinfo);
+  delete cbinfo;
+}
+
+template<typename T>
+WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter(
+    NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) {
+  WeakCallbackInfo<T> *cbinfo =
+       static_cast<WeakCallbackInfo<T>*>(data.GetParameter());
+  cbinfo->isolate_ = data.GetIsolate();
+  return cbinfo;
+}
+
+template<typename T>
+WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield(
+    NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) {
+  WeakCallbackInfo<T> *cbinfo =
+       static_cast<WeakCallbackInfo<T>*>(data.GetInternalField1());
+  cbinfo->isolate_ = data.GetIsolate();
+  return cbinfo;
+}
+
+#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_
+#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_
+#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
+#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+
+template<typename T>
+template<typename S>
+void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) {
+  WeakCallbackInfo<T> *cbinfo = unwrap(data);
+  cbinfo->persistent_.Reset();
+  cbinfo->callback_(*cbinfo);
+  delete cbinfo;
+}
+
+template<typename T>
+template<typename S>
+WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap(
+    NAN_WEAK_CALLBACK_DATA_TYPE_ data) {
+  void *parameter = data.GetParameter();
+  WeakCallbackInfo<T> *cbinfo =
+      static_cast<WeakCallbackInfo<T>*>(parameter);
+  cbinfo->isolate_ = data.GetIsolate();
+  return cbinfo;
+}
+
+#undef NAN_WEAK_CALLBACK_SIG_
+#undef NAN_WEAK_CALLBACK_DATA_TYPE_
+#else
+
+template<typename T>
+void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) {
+  WeakCallbackInfo<T> *cbinfo = unwrap(data);
+  cbinfo->persistent_.Dispose();
+  cbinfo->persistent_.Clear();
+  cbinfo->callback_(*cbinfo);
+  delete cbinfo;
+}
+
+template<typename T>
+WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap(
+    NAN_WEAK_CALLBACK_DATA_TYPE_ data) {
+  WeakCallbackInfo<T> *cbinfo =
+      static_cast<WeakCallbackInfo<T>*>(data);
+  cbinfo->isolate_ = v8::Isolate::GetCurrent();
+  return cbinfo;
+}
+
+#undef NAN_WEAK_CALLBACK_SIG_
+#undef NAN_WEAK_CALLBACK_DATA_TYPE_
+#endif
+
+#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 ||                      \
+  (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
+template<typename T, typename M>
+template<typename P>
+inline void Persistent<T, M>::SetWeak(
+    P *parameter
+  , typename WeakCallbackInfo<P>::Callback callback
+  , WeakCallbackType type) {
+  WeakCallbackInfo<P> *wcbd;
+  if (type == WeakCallbackType::kParameter) {
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , parameter);
+    v8::PersistentBase<T>::SetWeak(
+        wcbd
+      , WeakCallbackInfo<P>::template invokeparameter<true>
+      , type);
+  } else {
+    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
+    assert((*self_v)->IsObject());
+    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
+    int count = self->InternalFieldCount();
+    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
+    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
+      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
+    }
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , 0
+      , internal_fields[0]
+      , internal_fields[1]);
+    self->SetAlignedPointerInInternalField(0, wcbd);
+    v8::PersistentBase<T>::SetWeak(
+        static_cast<WeakCallbackInfo<P>*>(0)
+      , WeakCallbackInfo<P>::template invoketwofield<true>
+      , type);
+  }
+}
+#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION
+template<typename T, typename M>
+template<typename P>
+inline void Persistent<T, M>::SetWeak(
+    P *parameter
+  , typename WeakCallbackInfo<P>::Callback callback
+  , WeakCallbackType type) {
+  WeakCallbackInfo<P> *wcbd;
+  if (type == WeakCallbackType::kParameter) {
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , parameter);
+    v8::PersistentBase<T>::SetPhantom(
+        wcbd
+      , WeakCallbackInfo<P>::invokeparameter);
+  } else {
+    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
+    assert((*self_v)->IsObject());
+    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
+    int count = self->InternalFieldCount();
+    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
+    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
+      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
+    }
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , 0
+      , internal_fields[0]
+      , internal_fields[1]);
+    self->SetAlignedPointerInInternalField(0, wcbd);
+    v8::PersistentBase<T>::SetPhantom(
+        static_cast<WeakCallbackInfo<P>*>(0)
+      , WeakCallbackInfo<P>::invoketwofield
+      , 0
+      , count > 1 ? 1 : kNoInternalFieldIndex);
+  }
+}
+#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
+template<typename T, typename M>
+template<typename P>
+inline void Persistent<T, M>::SetWeak(
+    P *parameter
+  , typename WeakCallbackInfo<P>::Callback callback
+  , WeakCallbackType type) {
+  WeakCallbackInfo<P> *wcbd;
+  if (type == WeakCallbackType::kParameter) {
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , parameter);
+    v8::PersistentBase<T>::SetPhantom(
+        wcbd
+      , WeakCallbackInfo<P>::invokeparameter);
+  } else {
+    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
+    assert((*self_v)->IsObject());
+    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
+    int count = self->InternalFieldCount();
+    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
+    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
+      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
+    }
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , 0
+      , internal_fields[0]
+      , internal_fields[1]);
+    self->SetAlignedPointerInInternalField(0, wcbd);
+    v8::PersistentBase<T>::SetPhantom(
+        WeakCallbackInfo<P>::invoketwofield
+      , 0
+      , count > 1 ? 1 : kNoInternalFieldIndex);
+  }
+}
+#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
+template<typename T, typename M>
+template<typename P>
+inline void Persistent<T, M>::SetWeak(
+    P *parameter
+  , typename WeakCallbackInfo<P>::Callback callback
+  , WeakCallbackType type) {
+  WeakCallbackInfo<P> *wcbd;
+  if (type == WeakCallbackType::kParameter) {
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , parameter);
+    v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke);
+  } else {
+    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
+    assert((*self_v)->IsObject());
+    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
+    int count = self->InternalFieldCount();
+    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
+    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
+      internal_fields[i] = self->GetAlignedPointerFromInternalField(i);
+    }
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , 0
+      , internal_fields[0]
+      , internal_fields[1]);
+    v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke);
+  }
+}
+#else
+template<typename T>
+template<typename P>
+inline void PersistentBase<T>::SetWeak(
+    P *parameter
+  , typename WeakCallbackInfo<P>::Callback callback
+  , WeakCallbackType type) {
+  WeakCallbackInfo<P> *wcbd;
+  if (type == WeakCallbackType::kParameter) {
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , parameter);
+    persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke);
+  } else {
+    v8::Local<v8::Value>* self_v(reinterpret_cast<v8::Local<v8::Value>*>(this));
+    assert((*self_v)->IsObject());
+    v8::Local<v8::Object> self((*self_v).As<v8::Object>());
+    int count = self->InternalFieldCount();
+    void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
+    for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
+      internal_fields[i] = self->GetPointerFromInternalField(i);
+    }
+    wcbd = new WeakCallbackInfo<P>(
+        reinterpret_cast<Persistent<v8::Value>*>(this)
+      , callback
+      , 0
+      , internal_fields[0]
+      , internal_fields[1]);
+    persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke);
+  }
+}
+#endif
+
+#endif  // NAN_WEAK_H_
diff --git a/node_modules/node-pty/node_modules/nan/package.json b/node_modules/node-pty/node_modules/nan/package.json
new file mode 100644 (file)
index 0000000..302da5e
--- /dev/null
@@ -0,0 +1,109 @@
+{
+  "name": "nan",
+  "version": "2.14.0",
+  "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 11 compatibility",
+  "main": "include_dirs.js",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/nodejs/nan.git"
+  },
+  "scripts": {
+    "test": "tap --gc --stderr test/js/*-test.js",
+    "test:worker": "node --experimental-worker test/tap-as-worker.js --gc --stderr test/js/*-test.js",
+    "rebuild-tests": "node-gyp rebuild --msvs_version=2015 --directory test",
+    "docs": "doc/.build.sh"
+  },
+  "contributors": [
+    {
+      "name": "Rod Vagg",
+      "email": "r@va.gg",
+      "url": "https://github.com/rvagg"
+    },
+    {
+      "name": "Benjamin Byholm",
+      "email": "bbyholm@abo.fi",
+      "url": "https://github.com/kkoopa/"
+    },
+    {
+      "name": "Trevor Norris",
+      "email": "trev.norris@gmail.com",
+      "url": "https://github.com/trevnorris"
+    },
+    {
+      "name": "Nathan Rajlich",
+      "email": "nathan@tootallnate.net",
+      "url": "https://github.com/TooTallNate"
+    },
+    {
+      "name": "Brett Lawson",
+      "email": "brett19@gmail.com",
+      "url": "https://github.com/brett19"
+    },
+    {
+      "name": "Ben Noordhuis",
+      "email": "info@bnoordhuis.nl",
+      "url": "https://github.com/bnoordhuis"
+    },
+    {
+      "name": "David Siegel",
+      "email": "david@artcom.de",
+      "url": "https://github.com/agnat"
+    },
+    {
+      "name": "Michael Ira Krufky",
+      "email": "mkrufky@gmail.com",
+      "url": "https://github.com/mkrufky"
+    }
+  ],
+  "devDependencies": {
+    "bindings": "~1.2.1",
+    "commander": "^2.8.1",
+    "glob": "^5.0.14",
+    "request": "=2.81.0",
+    "node-gyp": "~3.6.2",
+    "readable-stream": "^2.1.4",
+    "tap": "~0.7.1",
+    "xtend": "~4.0.0"
+  },
+  "license": "MIT",
+  "gitHead": "1dcc61bd06d84e389bfd5311b2b1492a14c74201",
+  "bugs": {
+    "url": "https://github.com/nodejs/nan/issues"
+  },
+  "homepage": "https://github.com/nodejs/nan#readme",
+  "_id": "nan@2.14.0",
+  "_npmVersion": "5.6.0",
+  "_nodeVersion": "9.6.0",
+  "_npmUser": {
+    "name": "kkoopa",
+    "email": "bbyholm@abo.fi"
+  },
+  "dist": {
+    "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==",
+    "shasum": "7818f722027b2459a86f0295d434d1fc2336c52c",
+    "tarball": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz",
+    "fileCount": 46,
+    "unpackedSize": 417060,
+    "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc3bXpCRA9TVsSAnZWagAApycP/2mhtcraLrh5RRziC2xM\nUKDaEjBIznHn7PqDWecW3HW/CGrUfmuxpDCBlE2fBm2cxF26nB/CV6xoD2W1\nkyu4MkRcKiAvNW0h4a5sTwXey0U6xc8JRBhBTWgfiY2aQoA4fIO5akmbIa/w\nyT6tspFQ0BQWKBrxlSOqfQ/lARU4Dzy2eiKu1aWMffQecgqOPTrlb5/QxFsr\nUmfdePyO2odVrjDiiNJsfkHeMh66ED4n7szrRjwkz7FTkoEF0dMOw/bWJU2X\nEYVziHG7rm9B4Blzv6KtqG4Y9Gty8epOG+itSLQcc088H86TXYXJn6y75+lf\n1Lw5E9lxw5XLfVnE7uzr0NVHhcj/M3RaGzXySi7v2AWMbF6wqxtAdebdNaew\nIpc3+NVj2OjA/79bzzhU76MG0PrYURE8UmVugHZHGp9L1PraD/jWqCT1JMGE\n1qGu2dSlsqoyNe9Y1pTs/kc+I4KLjwDqo14NyQQk8quvkyHrQ66oO5lAPN4U\n5ms7vR+FOZYrtX7jQDTAs9N169N0IxhGwgsUH4zRza2RkkdTzsjyEnPhqlrI\n6tIrfYldrudrGtcNmLJqY7fTUA86L3f7SQvlnpfsDPUFagfwQr4Uz9JE8q1k\nhbe8CqTuhbET2AZNFlBxf0ii3ipwNXXJtB/0hIVQCfud1vbdS1IuOibc2/YY\n6ep0\r\n=AZxH\r\n-----END PGP SIGNATURE-----\r\n"
+  },
+  "maintainers": [
+    {
+      "name": "kkoopa",
+      "email": "bbyholm@abo.fi"
+    },
+    {
+      "name": "rvagg",
+      "email": "rod@vagg.org"
+    }
+  ],
+  "directories": {},
+  "_npmOperationalInternal": {
+    "host": "s3://npm-registry-packages",
+    "tmp": "tmp/nan_2.14.0_1558033896058_0.6879275796293267"
+  },
+  "_hasShrinkwrap": false,
+  "_shasum": "7818f722027b2459a86f0295d434d1fc2336c52c",
+  "_from": "nan@^2.14.0",
+  "_resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz",
+  "readme": "ERROR: No README data found!"
+}
diff --git a/node_modules/node-pty/node_modules/nan/tools/1to2.js b/node_modules/node-pty/node_modules/nan/tools/1to2.js
new file mode 100755 (executable)
index 0000000..337f8bf
--- /dev/null
@@ -0,0 +1,412 @@
+#!/usr/bin/env node
+/*********************************************************************
+ * NAN - Native Abstractions for Node.js
+ *
+ * Copyright (c) 2018 NAN contributors
+ *
+ * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
+ ********************************************************************/
+
+var commander = require('commander'),
+    fs = require('fs'),
+    glob = require('glob'),
+    groups = [],
+    total = 0,
+    warning1 = '/* ERROR: Rewrite using Buffer */\n',
+    warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n',
+    length,
+    i;
+
+fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) {
+  if (err) {
+    throw err;
+  }
+
+  commander
+      .version(JSON.parse(data).version)
+      .usage('[options] <file ...>')
+      .parse(process.argv);
+
+  if (!process.argv.slice(2).length) {
+    commander.outputHelp();
+  }
+});
+
+/* construct strings representing regular expressions
+   each expression contains a unique group allowing for identification of the match
+   the index of this key group, relative to the regular expression in question,
+    is indicated by the first array member */
+
+/* simple substistutions, key group is the entire match, 0 */
+groups.push([0, [
+  '_NAN_',
+  'NODE_SET_METHOD',
+  'NODE_SET_PROTOTYPE_METHOD',
+  'NanAsciiString',
+  'NanEscapeScope',
+  'NanReturnValue',
+  'NanUcs2String'].join('|')]);
+
+/* substitutions of parameterless macros, key group is 1 */
+groups.push([1, ['(', [
+  'NanEscapableScope',
+  'NanReturnNull',
+  'NanReturnUndefined',
+  'NanScope'].join('|'), ')\\(\\)'].join('')]);
+
+/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */
+groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']);
+
+/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ 
+groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]);
+
+/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */
+groups.push([2, ['(', warning2, ')?', '^.*?(', [
+      'GetIndexedPropertiesExternalArrayDataLength',
+      'GetIndexedPropertiesExternalArrayData',
+      'GetIndexedPropertiesExternalArrayDataType',
+      'GetIndexedPropertiesPixelData',
+      'GetIndexedPropertiesPixelDataLength',
+      'HasIndexedPropertiesInExternalArrayData',
+      'HasIndexedPropertiesInPixelData',
+      'SetIndexedPropertiesToExternalArrayData',
+      'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]);
+
+/* No need for NanScope in V8-exposed methods, key group 2 */
+groups.push([2, ['((', [
+      'NAN_METHOD',
+      'NAN_GETTER',
+      'NAN_SETTER',
+      'NAN_PROPERTY_GETTER',
+      'NAN_PROPERTY_SETTER',
+      'NAN_PROPERTY_ENUMERATOR',
+      'NAN_PROPERTY_DELETER',
+      'NAN_PROPERTY_QUERY',
+      'NAN_INDEX_GETTER',
+      'NAN_INDEX_SETTER',
+      'NAN_INDEX_ENUMERATOR',
+      'NAN_INDEX_DELETER',
+      'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]);
+
+/* v8::Value::ToXXXXXXX returns v8::MaybeLocal<T>, key group 3 */
+groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [
+      'Boolean',
+      'Number',
+      'String',
+      'Object',
+      'Integer',
+      'Uint32',
+      'Int32'].join('|'), ')\\('].join('')]);
+
+/* v8::Value::XXXXXXXValue returns v8::Maybe<T>, key group 3 */
+groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [
+      'Boolean',
+      'Number',
+      'Integer',
+      'Uint32',
+      'Int32'].join('|'), ')Value)\\('].join('')]);
+
+/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */
+groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']);
+
+/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */
+groups.push([1, ['(', [
+  'NanDisposePersistent',
+  'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]);
+
+/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */
+groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']);
+
+/* Many methods of v8::Object and others now return v8::MaybeLocal<T>, key group 3 */
+groups.push([3, ['([\\s])([^\\s]+)->(', [
+  'GetEndColumn',
+  'GetFunction',
+  'GetLineNumber',
+  'NewInstance',
+  'GetPropertyNames',
+  'GetOwnPropertyNames',
+  'GetSourceLine',
+  'GetStartColumn',
+  'ObjectProtoToString',
+  'ToArrayIndex',
+  'ToDetailString',
+  'CallAsConstructor',
+  'CallAsFunction',
+  'CloneElementAt',
+  'Delete',
+  'ForceSet',
+  'Get',
+  'GetPropertyAttributes',
+  'GetRealNamedProperty',
+  'GetRealNamedPropertyInPrototypeChain',
+  'Has',
+  'HasOwnProperty',
+  'HasRealIndexedProperty',
+  'HasRealNamedCallbackProperty',
+  'HasRealNamedProperty',
+  'Set',
+  'SetAccessor',
+  'SetIndexedPropertyHandler',
+  'SetNamedPropertyHandler',
+  'SetPrototype'].join('|'), ')\\('].join('')]);
+
+/* You should get an error if any of these fail anyways,
+   or handle the error better, it is indicated either way, key group 2 */
+groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]);
+
+/* v8::Value::Equals now returns a v8::Maybe, key group 3 */
+groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']);
+
+/* NanPersistent makes this unnecessary, key group 1 */
+groups.push([1, '(NanAssignPersistent)(?:<v8\\:\\:[^>]+>)?\\(([^,]+),\\s*']);
+
+/* args has been renamed to info, key group 2 */
+groups.push([2, '(\\W)(args)(\\W)'])
+
+/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */
+groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']);
+
+/* v8::Persistent was replaced with NanPersistent, key group 2 */
+groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']);
+
+/* counts the number of capturing groups in a well-formed regular expression,
+   ignoring non-capturing groups and escaped parentheses */
+function groupcount(s) {
+  var positive = s.match(/\((?!\?)/g),
+      negative = s.match(/\\\(/g);
+  return (positive ? positive.length : 0) - (negative ? negative.length : 0);
+}
+
+/* compute the absolute position of each key group in the joined master RegExp */
+for (i = 1, length = groups.length; i < length; i++) {
+       total += groupcount(groups[i - 1][1]);
+       groups[i][0] += total;
+}
+
+/* create the master RegExp, whis is the union of all the groups' expressions */
+master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm');
+
+/* replacement function for String.replace, receives 21 arguments */
+function replace() {
+       /* simple expressions */
+      switch (arguments[groups[0][0]]) {
+        case '_NAN_':
+          return 'NAN_';
+        case 'NODE_SET_METHOD':
+          return 'NanSetMethod';
+        case 'NODE_SET_PROTOTYPE_METHOD':
+          return 'NanSetPrototypeMethod';
+        case 'NanAsciiString':
+          return 'NanUtf8String';
+        case 'NanEscapeScope':
+          return 'scope.Escape';
+        case 'NanReturnNull':
+          return 'info.GetReturnValue().SetNull';
+        case 'NanReturnValue':
+          return 'info.GetReturnValue().Set';
+        case 'NanUcs2String':
+          return 'v8::String::Value';
+        default:
+      }
+
+      /* macros without arguments */
+      switch (arguments[groups[1][0]]) {
+        case 'NanEscapableScope':
+          return 'NanEscapableScope scope'
+        case 'NanReturnUndefined':
+          return 'return';
+        case 'NanScope':
+          return 'NanScope scope';
+        default:
+      }
+
+      /* TryCatch, emulate negative backref */
+      if (arguments[groups[2][0]] === 'TryCatch') {
+        return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch';
+      }
+
+      /* NanNew("foo") --> NanNew("foo").ToLocalChecked() */
+      if (arguments[groups[3][0]] === 'NanNew') {
+        return [arguments[0], '.ToLocalChecked()'].join('');
+      }
+
+      /* insert warning for removed functions as comment on new line above */
+      switch (arguments[groups[4][0]]) {
+        case 'GetIndexedPropertiesExternalArrayData':
+        case 'GetIndexedPropertiesExternalArrayDataLength':
+        case 'GetIndexedPropertiesExternalArrayDataType':
+        case 'GetIndexedPropertiesPixelData':
+        case 'GetIndexedPropertiesPixelDataLength':
+        case 'HasIndexedPropertiesInExternalArrayData':
+        case 'HasIndexedPropertiesInPixelData':
+        case 'SetIndexedPropertiesToExternalArrayData':
+        case 'SetIndexedPropertiesToPixelData':
+          return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join('');
+        default:
+      }
+
+     /* remove unnecessary NanScope() */
+      switch (arguments[groups[5][0]]) {
+        case 'NAN_GETTER':
+        case 'NAN_METHOD':
+        case 'NAN_SETTER':
+        case 'NAN_INDEX_DELETER':
+        case 'NAN_INDEX_ENUMERATOR':
+        case 'NAN_INDEX_GETTER':
+        case 'NAN_INDEX_QUERY':
+        case 'NAN_INDEX_SETTER':
+        case 'NAN_PROPERTY_DELETER':
+        case 'NAN_PROPERTY_ENUMERATOR':
+        case 'NAN_PROPERTY_GETTER':
+        case 'NAN_PROPERTY_QUERY':
+        case 'NAN_PROPERTY_SETTER':
+          return arguments[groups[5][0] - 1];
+        default:
+      }
+
+      /* Value converstion */
+      switch (arguments[groups[6][0]]) {
+        case 'Boolean':
+        case 'Int32':
+        case 'Integer':
+        case 'Number':
+        case 'Object':
+        case 'String':
+        case 'Uint32':
+          return [arguments[groups[6][0] - 2], 'NanTo<v8::', arguments[groups[6][0]], '>(',  arguments[groups[6][0] - 1]].join('');
+        default:
+      }
+
+      /* other value conversion */
+      switch (arguments[groups[7][0]]) {
+        case 'BooleanValue':
+          return [arguments[groups[7][0] - 2], 'NanTo<bool>(', arguments[groups[7][0] - 1]].join('');
+        case 'Int32Value':
+          return [arguments[groups[7][0] - 2], 'NanTo<int32_t>(', arguments[groups[7][0] - 1]].join('');
+        case 'IntegerValue':
+          return [arguments[groups[7][0] - 2], 'NanTo<int64_t>(', arguments[groups[7][0] - 1]].join('');
+        case 'Uint32Value':
+          return [arguments[groups[7][0] - 2], 'NanTo<uint32_t>(', arguments[groups[7][0] - 1]].join('');
+        default:
+      }
+
+      /* NAN_WEAK_CALLBACK */
+      if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') {
+        return ['template<typename T>\nvoid ',
+          arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo<T> &data)'].join('');
+      }
+
+      /* use methods on NAN classes instead */
+      switch (arguments[groups[9][0]]) {
+        case 'NanDisposePersistent':
+          return [arguments[groups[9][0] + 1], '.Reset('].join('');
+        case 'NanObjectWrapHandle':
+          return [arguments[groups[9][0] + 1], '->handle('].join('');
+        default:
+      }
+
+      /* use method on NanPersistent instead */
+      if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') {
+        return arguments[groups[10][0] + 1] + '.SetWeak(';
+      }
+
+      /* These return Maybes, the upper ones take no arguments */
+      switch (arguments[groups[11][0]]) {
+        case 'GetEndColumn':
+        case 'GetFunction':
+        case 'GetLineNumber':
+        case 'GetOwnPropertyNames':
+        case 'GetPropertyNames':
+        case 'GetSourceLine':
+        case 'GetStartColumn':
+        case 'NewInstance':
+        case 'ObjectProtoToString':
+        case 'ToArrayIndex':
+        case 'ToDetailString':
+          return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join('');
+        case 'CallAsConstructor':
+        case 'CallAsFunction':
+        case 'CloneElementAt':
+        case 'Delete':
+        case 'ForceSet':
+        case 'Get':
+        case 'GetPropertyAttributes':
+        case 'GetRealNamedProperty':
+        case 'GetRealNamedPropertyInPrototypeChain':
+        case 'Has':
+        case 'HasOwnProperty':
+        case 'HasRealIndexedProperty':
+        case 'HasRealNamedCallbackProperty':
+        case 'HasRealNamedProperty':
+        case 'Set':
+        case 'SetAccessor':
+        case 'SetIndexedPropertyHandler':
+        case 'SetNamedPropertyHandler':
+        case 'SetPrototype':
+          return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join('');
+        default:
+      }
+
+      /* Automatic ToLocalChecked(), take it or leave it */
+      switch (arguments[groups[12][0]]) {
+        case 'Date':
+        case 'String':
+        case 'RegExp':
+          return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join('');
+        default:
+      }
+
+      /* NanEquals is now required for uniformity */
+      if (arguments[groups[13][0]] === 'Equals') {
+        return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join('');
+      }
+
+      /* use method on replacement class instead */
+      if (arguments[groups[14][0]] === 'NanAssignPersistent') {
+        return [arguments[groups[14][0] + 1], '.Reset('].join('');
+      }
+
+      /* args --> info */
+      if (arguments[groups[15][0]] === 'args') {
+        return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join('');
+      }
+
+      /* ObjectWrap --> NanObjectWrap */
+      if (arguments[groups[16][0]] === 'ObjectWrap') {
+        return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join('');
+      }
+
+      /* Persistent --> NanPersistent */
+      if (arguments[groups[17][0]] === 'Persistent') {
+        return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join('');
+      }
+
+      /* This should not happen. A switch is probably missing a case if it does. */
+      throw 'Unhandled match: ' + arguments[0];
+}
+
+/* reads a file, runs replacement and writes it back */
+function processFile(file) {
+  fs.readFile(file, {encoding: 'utf8'}, function (err, data) {
+    if (err) {
+      throw err;
+    }
+
+    /* run replacement twice, might need more runs */
+    fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) {
+      if (err) {
+        throw err;
+      }
+    });
+  });
+}
+
+/* process file names from command line and process the identified files */
+for (i = 2, length = process.argv.length; i < length; i++) {
+  glob(process.argv[i], function (err, matches) {
+    if (err) {
+      throw err;
+    }
+    matches.forEach(processFile);
+  });
+}
diff --git a/node_modules/node-pty/node_modules/nan/tools/README.md b/node_modules/node-pty/node_modules/nan/tools/README.md
new file mode 100644 (file)
index 0000000..7f07e4b
--- /dev/null
@@ -0,0 +1,14 @@
+1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions,
+false positives and missed opportunities. The input files are rewritten in place. Make sure that
+you have backups. You will have to manually review the changes afterwards and do some touchups.
+
+```sh
+$ tools/1to2.js
+
+  Usage: 1to2 [options] <file ...>
+
+  Options:
+
+    -h, --help     output usage information
+    -V, --version  output the version number
+```
diff --git a/node_modules/node-pty/node_modules/nan/tools/package.json b/node_modules/node-pty/node_modules/nan/tools/package.json
new file mode 100644 (file)
index 0000000..2dcdd78
--- /dev/null
@@ -0,0 +1,19 @@
+{
+  "name": "1to2",
+  "version": "1.0.0",
+  "description": "NAN 1 -> 2 Migration Script",
+  "main": "1to2.js",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/nodejs/nan.git"
+  },
+  "contributors": [
+    "Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)",
+    "Mathias Küsel (https://github.com/mathiask88/)"
+  ],
+  "dependencies": {
+    "glob": "~5.0.10",
+    "commander": "~2.8.1"
+  },
+  "license": "MIT"
+}
diff --git a/node_modules/node-pty/package.json b/node_modules/node-pty/package.json
new file mode 100644 (file)
index 0000000..82fae37
--- /dev/null
@@ -0,0 +1,89 @@
+{
+  "name": "node-pty",
+  "description": "Fork pseudoterminals in Node.JS",
+  "author": {
+    "name": "Microsoft Corporation"
+  },
+  "version": "0.9.0",
+  "license": "MIT",
+  "main": "./lib/index.js",
+  "types": "./typings/node-pty.d.ts",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/Tyriar/node-pty.git"
+  },
+  "homepage": "https://github.com/Tyriar/node-pty",
+  "bugs": {
+    "url": "https://github.com/Tyriar/node-pty/issues"
+  },
+  "keywords": [
+    "pty",
+    "tty",
+    "terminal",
+    "pseudoterminal",
+    "forkpty",
+    "openpty"
+  ],
+  "scripts": {
+    "tsc": "tsc",
+    "watch": "tsc -w",
+    "lint": "tslint 'src/**/*.ts'",
+    "install": "node scripts/install.js",
+    "postinstall": "node scripts/post-install.js",
+    "test": "cross-env NODE_ENV=test mocha -R spec --exit lib/*.test.js",
+    "prepare": "npm run tsc",
+    "prepublishOnly": "npm run tsc"
+  },
+  "dependencies": {
+    "nan": "^2.14.0"
+  },
+  "devDependencies": {
+    "@types/mocha": "^5.0.0",
+    "@types/node": "8",
+    "cross-env": "^5.1.4",
+    "mocha": "^5.0.5",
+    "ps-list": "^6.0.0",
+    "tslint": "^5.12.1",
+    "tslint-consistent-codestyle": "^1.15.0",
+    "typescript": "3.4"
+  },
+  "gitHead": "beac2b8c8badae230074d88cd0cd08da95daafc5",
+  "_id": "node-pty@0.9.0",
+  "_npmVersion": "6.4.1",
+  "_nodeVersion": "8.16.2",
+  "_npmUser": {
+    "name": "tyriar",
+    "email": "tyriar@tyriar.com"
+  },
+  "dist": {
+    "integrity": "sha512-MBnCQl83FTYOu7B4xWw10AW77AAh7ThCE1VXEv+JeWj8mSpGo+0bwgsV+b23ljBFwEM9OmsOv3kM27iUPPm84g==",
+    "shasum": "8f9bcc0d1c5b970a3184ffd533d862c7eb6590a6",
+    "tarball": "https://registry.npmjs.org/node-pty/-/node-pty-0.9.0.tgz",
+    "fileCount": 243,
+    "unpackedSize": 1079779,
+    "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdr0CpCRA9TVsSAnZWagAAvQoP/0G3Jy4bgYG7P44M7AkK\n7eegnmVgFp+t6PP7UqM4K6y8ex2/CLdl7UMRO0LFiJs7PnWGtEgXAIyC9Tmu\nJ8fkNly2/hAZdXU5C8E2NopUVb7QFjaaNshDkkVbn6pRiVG/Uo1Z4TW4Ijny\nqnDflc53cAzcepb2SnmNV7WqPUSlnY0jq2zPHJFfa4goj6+BU/V/VkYbH/eV\nFjejs5AufMRfG/3lM/R9/yNMNtNRraFRbZE9x6+yW6Wli4QPhw3ITJ1R2gPZ\nq2GjMRvrYmXWDr8pROrfAjSGpkaLpGNrIQbNDMtl5P9MfInBAH34zPurwV+J\ntx65FZ5ifCbeSU7b3f1JVkoLA09pAJpu/6Xk4xhsYfvacZxOcMCwlQ6UzAUA\n9gsVieq4acx1KbtlKIjvrgN3UrsdTvVDb5jlslD+7kD0Ux4jiXaiCblw0fyj\nMgxgN2xADa2wsihSgcSsW8wIp7X+K0VV5k0HgJ7iQpVtEZrN41UJ4hIH/toU\n+XEkQo1wqsjlXHVZocxIhwNYrSmoEWTlXW0OTC2tCWYkkIkY33JNRSEkWlHg\noNMjX4Gjt9769my7Us94K8yORg3xyEC0b859xSL70M71/zRuHFwn6hWa/z5i\nqmbLfyhz+AZkywh45CJ6H3BqSjLed/70CfVSfqy58j1NqcKy7oqtCiFjYWKf\nOwd4\r\n=jQ/c\r\n-----END PGP SIGNATURE-----\r\n"
+  },
+  "maintainers": [
+    {
+      "email": "alros@microsoft.com",
+      "name": "alexr00"
+    },
+    {
+      "email": "npmjs@microsoft.com",
+      "name": "microsoft"
+    },
+    {
+      "email": "tyriar@tyriar.com",
+      "name": "tyriar"
+    }
+  ],
+  "directories": {},
+  "_npmOperationalInternal": {
+    "host": "s3://npm-registry-packages",
+    "tmp": "tmp/node-pty_0.9.0_1571766440764_0.5541740518865894"
+  },
+  "_hasShrinkwrap": false,
+  "_shasum": "8f9bcc0d1c5b970a3184ffd533d862c7eb6590a6",
+  "_from": "node-pty@",
+  "_resolved": "https://registry.npmjs.org/node-pty/-/node-pty-0.9.0.tgz"
+}
diff --git a/node_modules/node-pty/scripts/install.js b/node_modules/node-pty/scripts/install.js
new file mode 100644 (file)
index 0000000..d88b7f1
--- /dev/null
@@ -0,0 +1,18 @@
+'use strict'
+
+const os = require('os');
+const path = require('path');
+const spawn = require('child_process').spawn;
+
+const gypArgs = ['rebuild'];
+if (process.env.NODE_PTY_DEBUG) {
+  gypArgs.push('--debug');
+}
+const gypProcess = spawn(os.platform() === 'win32' ? 'node-gyp.cmd' : 'node-gyp', gypArgs, {
+  cwd: path.join(__dirname, '..'),
+  stdio: 'inherit'
+});
+
+gypProcess.on('exit', function (code) {
+  process.exit(code);
+});
diff --git a/node_modules/node-pty/scripts/post-install.js b/node_modules/node-pty/scripts/post-install.js
new file mode 100644 (file)
index 0000000..2c026ee
--- /dev/null
@@ -0,0 +1,41 @@
+var fs = require('fs');
+var path = require('path');
+
+var RELEASE_DIR = path.join(__dirname, '..', 'build', 'Release');
+var BUILD_FILES = [
+  path.join(RELEASE_DIR, 'conpty.node'),
+  path.join(RELEASE_DIR, 'conpty.pdb'),
+  path.join(RELEASE_DIR, 'conpty_console_list.node'),
+  path.join(RELEASE_DIR, 'conpty_console_list.pdb'),
+  path.join(RELEASE_DIR, 'pty.node'),
+  path.join(RELEASE_DIR, 'pty.pdb'),
+  path.join(RELEASE_DIR, 'winpty-agent.exe'),
+  path.join(RELEASE_DIR, 'winpty-agent.pdb'),
+  path.join(RELEASE_DIR, 'winpty.dll'),
+  path.join(RELEASE_DIR, 'winpty.pdb')
+];
+
+cleanFolderRecursive = function(folder) {
+  var files = [];
+  if( fs.existsSync(folder) ) {
+    files = fs.readdirSync(folder);
+    files.forEach(function(file,index) {
+      var curPath = path.join(folder, file);
+      if(fs.lstatSync(curPath).isDirectory()) { // recurse
+        cleanFolderRecursive(curPath);
+        fs.rmdirSync(curPath);
+      } else if (BUILD_FILES.indexOf(curPath) < 0){ // delete file
+        fs.unlinkSync(curPath);
+      }
+    });
+  }
+};
+
+try {
+  cleanFolderRecursive(RELEASE_DIR);
+} catch(e) {
+  console.log(e);
+  //process.exit(1);
+} finally {
+  process.exit(0);
+}
diff --git a/node_modules/node-pty/scripts/publish.js b/node_modules/node-pty/scripts/publish.js
new file mode 100644 (file)
index 0000000..968531e
--- /dev/null
@@ -0,0 +1,62 @@
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+
+const cp = require('child_process');
+const fs = require('fs');
+const path = require('path');
+const packageJson = require('../package.json');
+
+// Setup auth
+fs.writeFileSync(`${process.env['HOME']}/.npmrc`, `//registry.npmjs.org/:_authToken=${process.env['NPM_AUTH_TOKEN']}`);
+
+// Determine if this is a stable or beta release
+const publishedVersions = getPublishedVersions();
+const isStableRelease = publishedVersions.indexOf(packageJson.version) === -1;
+
+// Get the next version
+let nextVersion = isStableRelease ? packageJson.version : getNextBetaVersion();
+console.log(`Publishing version: ${nextVersion}`);
+
+// Set the version in package.json
+const packageJsonFile = path.resolve(__dirname, '..', 'package.json');
+packageJson.version = nextVersion;
+fs.writeFileSync(packageJsonFile, JSON.stringify(packageJson, null, 2));
+
+// Publish
+const args = ['publish'];
+if (!isStableRelease) {
+  args.push('--tag', 'beta');
+}
+const result = cp.spawn('npm', args, { stdio: 'inherit' });
+result.on('exit', code => process.exit(code));
+
+function getNextBetaVersion() {
+  if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.exec(packageJson.version)) {
+    console.error('The package.json version must be of the form x.y.z');
+    process.exit(1);
+  }
+  const tag = 'beta';
+  const stableVersion = packageJson.version.split('.');
+  const nextStableVersion = `${stableVersion[0]}.${parseInt(stableVersion[1]) + 1}.0`;
+  const publishedVersions = getPublishedVersions(nextStableVersion, tag);
+  if (publishedVersions.length === 0) {
+    return `${nextStableVersion}-${tag}1`;
+  }
+  const latestPublishedVersion = publishedVersions.sort((a, b) => {
+    const aVersion = parseInt(a.substr(a.search(/[0-9]+$/)));
+    const bVersion = parseInt(b.substr(b.search(/[0-9]+$/)));
+    return aVersion > bVersion ? -1 : 1;
+  })[0];
+  const latestTagVersion = parseInt(latestPublishedVersion.substr(latestPublishedVersion.search(/[0-9]+$/)), 10);
+  return `${nextStableVersion}-${tag}${latestTagVersion + 1}`;
+}
+
+function getPublishedVersions(version, tag) {
+  const versionsProcess = cp.spawnSync('npm', ['view', packageJson.name, 'versions', '--json']);
+  const versionsJson = JSON.parse(versionsProcess.stdout);
+  if (tag) {
+    return versionsJson.filter(v => !v.search(new RegExp(`${version}-${tag}[0-9]+`)));
+  }
+  return versionsJson;
+}
diff --git a/node_modules/node-pty/src/conpty_console_list_agent.ts b/node_modules/node-pty/src/conpty_console_list_agent.ts
new file mode 100644 (file)
index 0000000..2aec542
--- /dev/null
@@ -0,0 +1,19 @@
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ *
+ * This module fetches the console process list for a particular PID. It must be
+ * called from a different process (child_process.fork) as there can only be a
+ * single console attached to a process.
+ */
+
+let getConsoleProcessList: any;
+try {
+  getConsoleProcessList = require('../build/Release/conpty_console_list.node').getConsoleProcessList;
+} catch (err) {
+  getConsoleProcessList = require('../build/Debug/conpty_console_list.node').getConsoleProcessList;
+}
+
+const shellPid = parseInt(process.argv[2], 10);
+const consoleProcessList = getConsoleProcessList(shellPid);
+process.send({ consoleProcessList });
+process.exit(0);
diff --git a/node_modules/node-pty/src/eventEmitter2.test.ts b/node_modules/node-pty/src/eventEmitter2.test.ts
new file mode 100644 (file)
index 0000000..a65bfc2
--- /dev/null
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+
+import * as assert from 'assert';
+import { EventEmitter2 } from './eventEmitter2';
+
+describe('EventEmitter2', () => {
+  it('should fire listeners multiple times', () => {
+    const order: string[] = [];
+    const emitter = new EventEmitter2<number>();
+    emitter.event(data => order.push(data + 'a'));
+    emitter.event(data => order.push(data + 'b'));
+    emitter.fire(1);
+    emitter.fire(2);
+    assert.deepEqual(order, [ '1a', '1b', '2a', '2b' ]);
+  });
+
+  it('should not fire listeners once disposed', () => {
+    const order: string[] = [];
+    const emitter = new EventEmitter2<number>();
+    emitter.event(data => order.push(data + 'a'));
+    const disposeB = emitter.event(data => order.push(data + 'b'));
+    emitter.event(data => order.push(data + 'c'));
+    emitter.fire(1);
+    disposeB.dispose();
+    emitter.fire(2);
+    assert.deepEqual(order, [ '1a', '1b', '1c', '2a', '2c' ]);
+  });
+});
diff --git a/node_modules/node-pty/src/eventEmitter2.ts b/node_modules/node-pty/src/eventEmitter2.ts
new file mode 100644 (file)
index 0000000..6779d0c
--- /dev/null
@@ -0,0 +1,48 @@
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+
+import { IDisposable } from './types';
+
+interface IListener<T> {
+  (e: T): void;
+}
+
+export interface IEvent<T> {
+  (listener: (e: T) => any): IDisposable;
+}
+
+export class EventEmitter2<T> {
+  private _listeners: IListener<T>[] = [];
+  private _event?: IEvent<T>;
+
+  public get event(): IEvent<T> {
+    if (!this._event) {
+      this._event = (listener: (e: T) => any) => {
+        this._listeners.push(listener);
+        const disposable = {
+          dispose: () => {
+            for (let i = 0; i < this._listeners.length; i++) {
+              if (this._listeners[i] === listener) {
+                this._listeners.splice(i, 1);
+                return;
+              }
+            }
+          }
+        };
+        return disposable;
+      };
+    }
+    return this._event;
+  }
+
+  public fire(data: T): void {
+    const queue: IListener<T>[] = [];
+    for (let i = 0; i < this._listeners.length; i++) {
+      queue.push(this._listeners[i]);
+    }
+    for (let i = 0; i < queue.length; i++) {
+      queue[i].call(undefined, data);
+    }
+  }
+}
diff --git a/node_modules/node-pty/src/index.ts b/node_modules/node-pty/src/index.ts
new file mode 100644 (file)
index 0000000..53d0322
--- /dev/null
@@ -0,0 +1,51 @@
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import { ITerminal, IPtyOpenOptions, IPtyForkOptions, IWindowsPtyForkOptions } from './interfaces';
+import { ArgvOrCommandLine } from './types';
+
+let terminalCtor: any;
+if (process.platform === 'win32') {
+  terminalCtor = require('./windowsTerminal').WindowsTerminal;
+} else {
+  terminalCtor = require('./unixTerminal').UnixTerminal;
+}
+
+/**
+ * Forks a process as a pseudoterminal.
+ * @param file The file to launch.
+ * @param args The file's arguments as argv (string[]) or in a pre-escaped
+ * CommandLine format (string). Note that the CommandLine option is only
+ * available on Windows and is expected to be escaped properly.
+ * @param options The options of the terminal.
+ * @throws When the file passed to spawn with does not exists.
+ * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
+ * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
+ * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx
+ */
+export function spawn(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions | IWindowsPtyForkOptions): ITerminal {
+  return new terminalCtor(file, args, opt);
+}
+
+/** @deprecated */
+export function fork(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions | IWindowsPtyForkOptions): ITerminal {
+  return new terminalCtor(file, args, opt);
+}
+
+/** @deprecated */
+export function createTerminal(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions | IWindowsPtyForkOptions): ITerminal {
+  return new terminalCtor(file, args, opt);
+}
+
+export function open(options: IPtyOpenOptions): ITerminal {
+  return terminalCtor.open(options);
+}
+
+/**
+ * Expose the native API when not Windows, note that this is not public API and
+ * could be removed at any time.
+ */
+export const native = (process.platform !== 'win32' ? require('../build/Release/pty.node') : null);
diff --git a/node_modules/node-pty/src/interfaces.ts b/node_modules/node-pty/src/interfaces.ts
new file mode 100644 (file)
index 0000000..f100e0e
--- /dev/null
@@ -0,0 +1,136 @@
+/**
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import * as net from 'net';
+
+export interface IProcessEnv {
+  [key: string]: string;
+}
+
+export interface ITerminal {
+  /**
+   * Gets the name of the process.
+   */
+  process: string;
+
+  /**
+   * Gets the process ID.
+   */
+  pid: number;
+
+  /**
+   * The socket for the master file descriptor. This is not supported on
+   * Windows.
+   */
+  master: net.Socket;
+
+  /**
+   * The socket for the slave file descriptor. This is not supported on Windows.
+   */
+  slave: net.Socket;
+
+  /**
+   * Writes data to the socket.
+   * @param data The data to write.
+   */
+  write(data: string): void;
+
+  /**
+   * Resize the pty.
+   * @param cols The number of columns.
+   * @param rows The number of rows.
+   */
+  resize(cols: number, rows: number): void;
+
+  /**
+   * Close, kill and destroy the socket.
+   */
+  destroy(): void;
+
+  /**
+   * Kill the pty.
+   * @param signal The signal to send, by default this is SIGHUP. This is not
+   * supported on Windows.
+   */
+  kill(signal?: string): void;
+
+  /**
+   * Set the pty socket encoding.
+   */
+  setEncoding(encoding: string | null): void;
+
+  /**
+   * Resume the pty socket.
+   */
+  resume(): void;
+
+  /**
+   * Pause the pty socket.
+   */
+  pause(): void;
+
+  /**
+   * Alias for ITerminal.on(eventName, listener).
+   */
+  addListener(eventName: string, listener: (...args: any[]) => any): void;
+
+  /**
+   * Adds the listener function to the end of the listeners array for the event
+   * named eventName.
+   * @param eventName The event name.
+   * @param listener The callback function
+   */
+  on(eventName: string, listener: (...args: any[]) => any): void;
+
+  /**
+   * Returns a copy of the array of listeners for the event named eventName.
+   */
+  listeners(eventName: string): Function[];
+
+  /**
+   * Removes the specified listener from the listener array for the event named
+   * eventName.
+   */
+  removeListener(eventName: string, listener: (...args: any[]) => any): void;
+
+  /**
+   * Removes all listeners, or those of the specified eventName.
+   */
+  removeAllListeners(eventName: string): void;
+
+  /**
+   * Adds a one time listener function for the event named eventName. The next
+   * time eventName is triggered, this listener is removed and then invoked.
+   */
+  once(eventName: string, listener: (...args: any[]) => any): void;
+}
+
+interface IBasePtyForkOptions {
+  name?: string;
+  cols?: number;
+  rows?: number;
+  cwd?: string;
+  env?: { [key: string]: string };
+  encoding?: string;
+  handleFlowControl?: boolean;
+  flowControlPause?: string;
+  flowControlResume?: string;
+}
+
+export interface IPtyForkOptions extends IBasePtyForkOptions {
+  uid?: number;
+  gid?: number;
+}
+
+export interface IWindowsPtyForkOptions extends IBasePtyForkOptions {
+  useConpty?: boolean;
+  conptyInheritCursor?: boolean;
+}
+
+export interface IPtyOpenOptions {
+  cols?: number;
+  rows?: number;
+  encoding?: string;
+}
diff --git a/node_modules/node-pty/src/native.d.ts b/node_modules/node-pty/src/native.d.ts
new file mode 100644 (file)
index 0000000..3212e3b
--- /dev/null
@@ -0,0 +1,54 @@
+/**
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+interface IConptyNative {
+  startProcess(file: string, cols: number, rows: number, debug: boolean, pipeName: string, conptyInheritCursor: boolean): IConptyProcess;
+  connect(ptyId: number, commandLine: string, cwd: string, env: string[], onExitCallback: (exitCode: number) => void): { pid: number };
+  resize(ptyId: number, cols: number, rows: number): void;
+  kill(ptyId: number): void;
+}
+
+interface IWinptyNative {
+  startProcess(file: string, commandLine: string, env: string[], cwd: string, cols: number, rows: number, debug: boolean): IWinptyProcess;
+  resize(processHandle: number, cols: number, rows: number): void;
+  kill(pid: number, innerPidHandle: number): void;
+  getProcessList(pid: number): number[];
+  getExitCode(innerPidHandle: number): number;
+}
+
+interface IUnixNative {
+  fork(file: string, args: string[], parsedEnv: string[], cwd: string, cols: number, rows: number, uid: number, gid: number, useUtf8: boolean, onExitCallback: (code: number, signal: number) => void): IUnixProcess;
+  open(cols: number, rows: number): IUnixOpenProcess;
+  process(fd: number, pty: string): string;
+  resize(fd: number, cols: number, rows: number): void;
+}
+
+interface IConptyProcess {
+  pty: number;
+  fd: number;
+  conin: string;
+  conout: string;
+}
+
+interface IWinptyProcess {
+  pty: number;
+  fd: number;
+  conin: string;
+  conout: string;
+  pid: number;
+  innerPid: number;
+  innerPidHandle: number;
+}
+
+interface IUnixProcess {
+  fd: number;
+  pid: number;
+  pty: string;
+}
+
+interface IUnixOpenProcess {
+  master: number;
+  slave: number;
+  pty: string;
+}
diff --git a/node_modules/node-pty/src/terminal.test.ts b/node_modules/node-pty/src/terminal.test.ts
new file mode 100644 (file)
index 0000000..dba011f
--- /dev/null
@@ -0,0 +1,66 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import * as assert from 'assert';
+import { WindowsTerminal } from './windowsTerminal';
+import { UnixTerminal } from './unixTerminal';
+import { pollUntil } from './testUtils.test';
+
+const terminalConstructor = (process.platform === 'win32') ? WindowsTerminal : UnixTerminal;
+const SHELL = (process.platform === 'win32') ? 'cmd.exe' : '/bin/bash';
+
+let terminalCtor: WindowsTerminal | UnixTerminal;
+if (process.platform === 'win32') {
+  terminalCtor = require('./windowsTerminal');
+} else {
+  terminalCtor = require('./unixTerminal');
+}
+
+
+describe('Terminal', () => {
+  describe('constructor', () => {
+    it('should do basic type checks', () => {
+      assert.throws(
+        () => new (<any>terminalCtor)('a', 'b', { 'name': {} }),
+        'name must be a string (not a object)'
+      );
+    });
+  });
+
+  describe('automatic flow control', () => {
+    it('should respect ctor flow control options', () => {
+      const pty = new terminalConstructor(SHELL, [], {handleFlowControl: true, flowControlPause: 'abc', flowControlResume: '123'});
+      assert.equal(pty.handleFlowControl, true);
+      assert.equal((pty as any)._flowControlPause, 'abc');
+      assert.equal((pty as any)._flowControlResume, '123');
+    });
+    // TODO: I don't think this test ever worked due to pollUntil being used incorrectly
+    // it('should do flow control automatically', async function(): Promise<void> {
+    //   // Flow control doesn't work on Windows
+    //   if (process.platform === 'win32') {
+    //     return;
+    //   }
+
+    //   this.timeout(10000);
+    //   const pty = new terminalConstructor(SHELL, [], {handleFlowControl: true, flowControlPause: 'PAUSE', flowControlResume: 'RESUME'});
+    //   let read: string = '';
+    //   pty.on('data', data => read += data);
+    //   pty.on('pause', () => read += 'paused');
+    //   pty.on('resume', () => read += 'resumed');
+    //   pty.write('1');
+    //   pty.write('PAUSE');
+    //   pty.write('2');
+    //   pty.write('RESUME');
+    //   pty.write('3');
+    //   await pollUntil(() => {
+    //     return stripEscapeSequences(read).endsWith('1pausedresumed23');
+    //   }, 100, 10);
+    // });
+  });
+});
+
+function stripEscapeSequences(data: string): string {
+  return data.replace(/\u001b\[0K/, '');
+}
diff --git a/node_modules/node-pty/src/terminal.ts b/node_modules/node-pty/src/terminal.ts
new file mode 100644 (file)
index 0000000..fb7f609
--- /dev/null
@@ -0,0 +1,195 @@
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import { Socket } from 'net';
+import { EventEmitter } from 'events';
+import { ITerminal, IPtyForkOptions } from './interfaces';
+import { EventEmitter2, IEvent } from './eventEmitter2';
+import { IExitEvent } from './types';
+
+export const DEFAULT_COLS: number = 80;
+export const DEFAULT_ROWS: number = 24;
+
+/**
+ * Default messages to indicate PAUSE/RESUME for automatic flow control.
+ * To avoid conflicts with rebound XON/XOFF control codes (such as on-my-zsh),
+ * the sequences can be customized in `IPtyForkOptions`.
+ */
+const FLOW_CONTROL_PAUSE =  '\x13';   // defaults to XOFF
+const FLOW_CONTROL_RESUME = '\x11';   // defaults to XON
+
+export abstract class Terminal implements ITerminal {
+  protected _socket: Socket;
+  protected _pid: number;
+  protected _fd: number;
+  protected _pty: any;
+
+  protected _file: string;
+  protected _name: string;
+  protected _cols: number;
+  protected _rows: number;
+
+  protected _readable: boolean;
+  protected _writable: boolean;
+
+  protected _internalee: EventEmitter;
+  private _flowControlPause: string;
+  private _flowControlResume: string;
+  public handleFlowControl: boolean;
+
+  private _onData = new EventEmitter2<string>();
+  public get onData(): IEvent<string> { return this._onData.event; }
+  private _onExit = new EventEmitter2<IExitEvent>();
+  public get onExit(): IEvent<IExitEvent> { return this._onExit.event; }
+
+  public get pid(): number { return this._pid; }
+  public get cols(): number { return this._cols; }
+  public get rows(): number { return this._rows; }
+
+  constructor(opt?: IPtyForkOptions) {
+    // for 'close'
+    this._internalee = new EventEmitter();
+
+    if (!opt) {
+      return;
+    }
+
+    // Do basic type checks here in case node-pty is being used within JavaScript. If the wrong
+    // types go through to the C++ side it can lead to hard to diagnose exceptions.
+    this._checkType('name', opt.name ? opt.name : null, 'string');
+    this._checkType('cols', opt.cols ? opt.cols : null, 'number');
+    this._checkType('rows', opt.rows ? opt.rows : null, 'number');
+    this._checkType('cwd', opt.cwd ? opt.cwd : null, 'string');
+    this._checkType('env', opt.env ? opt.env : null, 'object');
+    this._checkType('uid', opt.uid ? opt.uid : null, 'number');
+    this._checkType('gid', opt.gid ? opt.gid : null, 'number');
+    this._checkType('encoding', opt.encoding ? opt.encoding : null, 'string');
+
+    // setup flow control handling
+    this.handleFlowControl = !!(opt.handleFlowControl);
+    this._flowControlPause = opt.flowControlPause || FLOW_CONTROL_PAUSE;
+    this._flowControlResume = opt.flowControlResume || FLOW_CONTROL_RESUME;
+  }
+
+  protected abstract _write(data: string): void;
+
+  public write(data: string): void {
+    if (this.handleFlowControl) {
+      // PAUSE/RESUME messages are not forwarded to the pty
+      if (data === this._flowControlPause) {
+        this.pause();
+        return;
+      }
+      if (data === this._flowControlResume) {
+        this.resume();
+        return;
+      }
+    }
+    // everything else goes to the real pty
+    this._write(data);
+  }
+
+  protected _forwardEvents(): void {
+    this.on('data', e => this._onData.fire(e));
+    this.on('exit', (exitCode, signal) => this._onExit.fire({ exitCode, signal }));
+  }
+
+  private _checkType(name: string, value: any, type: string): void {
+    if (value && typeof value !== type) {
+      throw new Error(`${name} must be a ${type} (not a ${typeof value})`);
+    }
+  }
+
+  /** See net.Socket.end */
+  public end(data: string): void {
+    this._socket.end(data);
+  }
+
+  /** See stream.Readable.pipe */
+  public pipe(dest: any, options: any): any {
+    return this._socket.pipe(dest, options);
+  }
+
+  /** See net.Socket.pause */
+  public pause(): Socket {
+    return this._socket.pause();
+  }
+
+  /** See net.Socket.resume */
+  public resume(): Socket {
+    return this._socket.resume();
+  }
+
+  /** See net.Socket.setEncoding */
+  public setEncoding(encoding: string | null): void {
+    if ((<any>this._socket)._decoder) {
+      delete (<any>this._socket)._decoder;
+    }
+    if (encoding) {
+      this._socket.setEncoding(encoding);
+    }
+  }
+
+  public addListener(eventName: string, listener: (...args: any[]) => any): void { this.on(eventName, listener); }
+  public on(eventName: string, listener: (...args: any[]) => any): void {
+    if (eventName === 'close') {
+      this._internalee.on('close', listener);
+      return;
+    }
+    this._socket.on(eventName, listener);
+  }
+
+  public emit(eventName: string, ...args: any[]): any {
+    if (eventName === 'close') {
+      return this._internalee.emit.apply(this._internalee, arguments);
+    }
+    return this._socket.emit.apply(this._socket, arguments);
+  }
+
+  public listeners(eventName: string): Function[] {
+    return this._socket.listeners(eventName);
+  }
+
+  public removeListener(eventName: string, listener: (...args: any[]) => any): void {
+    this._socket.removeListener(eventName, listener);
+  }
+
+  public removeAllListeners(eventName: string): void {
+    this._socket.removeAllListeners(eventName);
+  }
+
+  public once(eventName: string, listener: (...args: any[]) => any): void {
+    this._socket.once(eventName, listener);
+  }
+
+  public abstract resize(cols: number, rows: number): void;
+  public abstract destroy(): void;
+  public abstract kill(signal?: string): void;
+
+  public abstract get process(): string;
+  public abstract get master(): Socket;
+  public abstract get slave(): Socket;
+
+  protected _close(): void {
+    this._socket.writable = false;
+    this._socket.readable = false;
+    this.write = () => {};
+    this.end = () => {};
+    this._writable = false;
+    this._readable = false;
+  }
+
+  protected _parseEnv(env: {[key: string]: string}): string[] {
+    const keys = Object.keys(env || {});
+    const pairs = [];
+
+    for (let i = 0; i < keys.length; i++) {
+      pairs.push(keys[i] + '=' + env[keys[i]]);
+    }
+
+    return pairs;
+  }
+}
diff --git a/node_modules/node-pty/src/testUtils.test.ts b/node_modules/node-pty/src/testUtils.test.ts
new file mode 100644 (file)
index 0000000..0bdabff
--- /dev/null
@@ -0,0 +1,23 @@
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+
+export function pollUntil(cb: () => boolean, timeout: number, interval: number): Promise<void> {
+  return new Promise<void>((resolve, reject) => {
+    const intervalId = setInterval(() => {
+      if (cb()) {
+        clearInterval(intervalId);
+        clearTimeout(timeoutId);
+        resolve();
+      }
+    }, interval);
+    const timeoutId = setTimeout(() => {
+      clearInterval(intervalId);
+      if (cb()) {
+        resolve();
+      } else {
+        reject();
+      }
+    }, timeout);
+  });
+}
diff --git a/node_modules/node-pty/src/types.ts b/node_modules/node-pty/src/types.ts
new file mode 100644 (file)
index 0000000..94c2ac7
--- /dev/null
@@ -0,0 +1,15 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+export type ArgvOrCommandLine = string[] | string;
+
+export interface IExitEvent {
+  exitCode: number;
+  signal: number | undefined;
+}
+
+export interface IDisposable {
+  dispose(): void;
+}
diff --git a/node_modules/node-pty/src/unix/pty.cc b/node_modules/node-pty/src/unix/pty.cc
new file mode 100644 (file)
index 0000000..d2f4c11
--- /dev/null
@@ -0,0 +1,708 @@
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
+ * Copyright (c) 2017, Daniel Imms (MIT License)
+ *
+ * pty.cc:
+ *   This file is responsible for starting processes
+ *   with pseudo-terminal file descriptors.
+ *
+ * See:
+ *   man pty
+ *   man tty_ioctl
+ *   man termios
+ *   man forkpty
+ */
+
+/**
+ * Includes
+ */
+
+#include <nan.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+
+/* forkpty */
+/* http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html */
+#if defined(__GLIBC__) || defined(__CYGWIN__)
+#include <pty.h>
+#elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__)
+#include <util.h>
+#elif defined(__FreeBSD__)
+#include <libutil.h>
+#elif defined(__sun)
+#include <stropts.h> /* for I_PUSH */
+#else
+#include <pty.h>
+#endif
+
+#include <termios.h> /* tcgetattr, tty_ioctl */
+
+/* Some platforms name VWERASE and VDISCARD differently */
+#if !defined(VWERASE) && defined(VWERSE)
+#define VWERASE        VWERSE
+#endif
+#if !defined(VDISCARD) && defined(VDISCRD)
+#define VDISCARD       VDISCRD
+#endif
+
+/* environ for execvpe */
+/* node/src/node_child_process.cc */
+#if defined(__APPLE__) && !TARGET_OS_IPHONE
+#include <crt_externs.h>
+#define environ (*_NSGetEnviron())
+#else
+extern char **environ;
+#endif
+
+/* for pty_getproc */
+#if defined(__linux__)
+#include <stdio.h>
+#include <stdint.h>
+#elif defined(__APPLE__)
+#include <sys/sysctl.h>
+#include <libproc.h>
+#endif
+
+/**
+ * Structs
+ */
+
+struct pty_baton {
+  Nan::Persistent<v8::Function> cb;
+  int exit_code;
+  int signal_code;
+  pid_t pid;
+  uv_async_t async;
+  uv_thread_t tid;
+};
+
+/**
+ * Methods
+ */
+
+NAN_METHOD(PtyFork);
+NAN_METHOD(PtyOpen);
+NAN_METHOD(PtyResize);
+NAN_METHOD(PtyGetProc);
+
+/**
+ * Functions
+ */
+
+static int
+pty_execvpe(const char *, char **, char **);
+
+static int
+pty_nonblock(int);
+
+static char *
+pty_getproc(int, char *);
+
+static int
+pty_openpty(int *, int *, char *,
+            const struct termios *,
+            const struct winsize *);
+
+static pid_t
+pty_forkpty(int *, char *,
+            const struct termios *,
+            const struct winsize *);
+
+static void
+pty_waitpid(void *);
+
+static void
+pty_after_waitpid(uv_async_t *);
+
+static void
+pty_after_close(uv_handle_t *);
+
+NAN_METHOD(PtyFork) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 10 ||
+      !info[0]->IsString() ||
+      !info[1]->IsArray() ||
+      !info[2]->IsArray() ||
+      !info[3]->IsString() ||
+      !info[4]->IsNumber() ||
+      !info[5]->IsNumber() ||
+      !info[6]->IsNumber() ||
+      !info[7]->IsNumber() ||
+      !info[8]->IsBoolean() ||
+      !info[9]->IsFunction()) {
+    return Nan::ThrowError(
+        "Usage: pty.fork(file, args, env, cwd, cols, rows, uid, gid, utf8, onexit)");
+  }
+
+  // Make sure the process still listens to SIGINT
+  signal(SIGINT, SIG_DFL);
+
+  // file
+  Nan::Utf8String file(info[0]);
+
+  // args
+  int i = 0;
+  v8::Local<v8::Array> argv_ = v8::Local<v8::Array>::Cast(info[1]);
+  int argc = argv_->Length();
+  int argl = argc + 1 + 1;
+  char **argv = new char*[argl];
+  argv[0] = strdup(*file);
+  argv[argl-1] = NULL;
+  for (; i < argc; i++) {
+    Nan::Utf8String arg(Nan::Get(argv_, i).ToLocalChecked());
+    argv[i+1] = strdup(*arg);
+  }
+
+  // env
+  i = 0;
+  v8::Local<v8::Array> env_ = v8::Local<v8::Array>::Cast(info[2]);
+  int envc = env_->Length();
+  char **env = new char*[envc+1];
+  env[envc] = NULL;
+  for (; i < envc; i++) {
+    Nan::Utf8String pair(Nan::Get(env_, i).ToLocalChecked());
+    env[i] = strdup(*pair);
+  }
+
+  // cwd
+  Nan::Utf8String cwd_(info[3]);
+  char *cwd = strdup(*cwd_);
+
+  // size
+  struct winsize winp;
+  winp.ws_col = info[4]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  winp.ws_row = info[5]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  winp.ws_xpixel = 0;
+  winp.ws_ypixel = 0;
+
+  // termios
+  struct termios t = termios();
+  struct termios *term = &t;
+  term->c_iflag = ICRNL | IXON | IXANY | IMAXBEL | BRKINT;
+  if (Nan::To<bool>(info[8]).FromJust()) {
+#if defined(IUTF8)
+    term->c_iflag |= IUTF8;
+#endif
+  }
+  term->c_oflag = OPOST | ONLCR;
+  term->c_cflag = CREAD | CS8 | HUPCL;
+  term->c_lflag = ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL;
+
+  term->c_cc[VEOF] = 4;
+  term->c_cc[VEOL] = -1;
+  term->c_cc[VEOL2] = -1;
+  term->c_cc[VERASE] = 0x7f;
+  term->c_cc[VWERASE] = 23;
+  term->c_cc[VKILL] = 21;
+  term->c_cc[VREPRINT] = 18;
+  term->c_cc[VINTR] = 3;
+  term->c_cc[VQUIT] = 0x1c;
+  term->c_cc[VSUSP] = 26;
+  term->c_cc[VSTART] = 17;
+  term->c_cc[VSTOP] = 19;
+  term->c_cc[VLNEXT] = 22;
+  term->c_cc[VDISCARD] = 15;
+  term->c_cc[VMIN] = 1;
+  term->c_cc[VTIME] = 0;
+
+  #if (__APPLE__)
+  term->c_cc[VDSUSP] = 25;
+  term->c_cc[VSTATUS] = 20;
+  #endif
+
+  cfsetispeed(term, B38400);
+  cfsetospeed(term, B38400);
+
+  // uid / gid
+  int uid = info[6]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  int gid = info[7]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+
+  // fork the pty
+  int master = -1;
+  pid_t pid = pty_forkpty(&master, nullptr, term, &winp);
+
+  if (pid) {
+    for (i = 0; i < argl; i++) free(argv[i]);
+    delete[] argv;
+    for (i = 0; i < envc; i++) free(env[i]);
+    delete[] env;
+    free(cwd);
+  }
+
+  switch (pid) {
+    case -1:
+      return Nan::ThrowError("forkpty(3) failed.");
+    case 0:
+      if (strlen(cwd)) {
+        if (chdir(cwd) == -1) {
+          perror("chdir(2) failed.");
+          _exit(1);
+        }
+      }
+
+      if (uid != -1 && gid != -1) {
+        if (setgid(gid) == -1) {
+          perror("setgid(2) failed.");
+          _exit(1);
+        }
+        if (setuid(uid) == -1) {
+          perror("setuid(2) failed.");
+          _exit(1);
+        }
+      }
+
+      pty_execvpe(argv[0], argv, env);
+
+      perror("execvp(3) failed.");
+      _exit(1);
+    default:
+      if (pty_nonblock(master) == -1) {
+        return Nan::ThrowError("Could not set master fd to nonblocking.");
+      }
+
+      v8::Local<v8::Object> obj = Nan::New<v8::Object>();
+      Nan::Set(obj,
+        Nan::New<v8::String>("fd").ToLocalChecked(),
+        Nan::New<v8::Number>(master));
+      Nan::Set(obj,
+        Nan::New<v8::String>("pid").ToLocalChecked(),
+        Nan::New<v8::Number>(pid));
+      Nan::Set(obj,
+        Nan::New<v8::String>("pty").ToLocalChecked(),
+        Nan::New<v8::String>(ptsname(master)).ToLocalChecked());
+
+      pty_baton *baton = new pty_baton();
+      baton->exit_code = 0;
+      baton->signal_code = 0;
+      baton->cb.Reset(v8::Local<v8::Function>::Cast(info[9]));
+      baton->pid = pid;
+      baton->async.data = baton;
+
+      uv_async_init(uv_default_loop(), &baton->async, pty_after_waitpid);
+
+      uv_thread_create(&baton->tid, pty_waitpid, static_cast<void*>(baton));
+
+      return info.GetReturnValue().Set(obj);
+  }
+
+  return info.GetReturnValue().SetUndefined();
+}
+
+NAN_METHOD(PtyOpen) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 2 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsNumber()) {
+    return Nan::ThrowError("Usage: pty.open(cols, rows)");
+  }
+
+  // size
+  struct winsize winp;
+  winp.ws_col = info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  winp.ws_row = info[1]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  winp.ws_xpixel = 0;
+  winp.ws_ypixel = 0;
+
+  // pty
+  int master, slave;
+  int ret = pty_openpty(&master, &slave, nullptr, NULL, &winp);
+
+  if (ret == -1) {
+    return Nan::ThrowError("openpty(3) failed.");
+  }
+
+  if (pty_nonblock(master) == -1) {
+    return Nan::ThrowError("Could not set master fd to nonblocking.");
+  }
+
+  if (pty_nonblock(slave) == -1) {
+    return Nan::ThrowError("Could not set slave fd to nonblocking.");
+  }
+
+  v8::Local<v8::Object> obj = Nan::New<v8::Object>();
+  Nan::Set(obj,
+    Nan::New<v8::String>("master").ToLocalChecked(),
+    Nan::New<v8::Number>(master));
+  Nan::Set(obj,
+    Nan::New<v8::String>("slave").ToLocalChecked(),
+    Nan::New<v8::Number>(slave));
+  Nan::Set(obj,
+    Nan::New<v8::String>("pty").ToLocalChecked(),
+    Nan::New<v8::String>(ptsname(master)).ToLocalChecked());
+
+  return info.GetReturnValue().Set(obj);
+}
+
+NAN_METHOD(PtyResize) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 3 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsNumber() ||
+      !info[2]->IsNumber()) {
+    return Nan::ThrowError("Usage: pty.resize(fd, cols, rows)");
+  }
+
+  int fd = info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+
+  struct winsize winp;
+  winp.ws_col = info[1]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  winp.ws_row = info[2]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+  winp.ws_xpixel = 0;
+  winp.ws_ypixel = 0;
+
+  if (ioctl(fd, TIOCSWINSZ, &winp) == -1) {
+    switch (errno) {
+      case EBADF: return Nan::ThrowError("ioctl(2) failed, EBADF");
+      case EFAULT: return Nan::ThrowError("ioctl(2) failed, EFAULT");
+      case EINVAL: return Nan::ThrowError("ioctl(2) failed, EINVAL");
+      case ENOTTY: return Nan::ThrowError("ioctl(2) failed, ENOTTY");
+    }
+    return Nan::ThrowError("ioctl(2) failed");
+  }
+
+  return info.GetReturnValue().SetUndefined();
+}
+
+/**
+ * Foreground Process Name
+ */
+NAN_METHOD(PtyGetProc) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 2 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsString()) {
+    return Nan::ThrowError("Usage: pty.process(fd, tty)");
+  }
+
+  int fd = info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust();
+
+  Nan::Utf8String tty_(info[1]);
+  char *tty = strdup(*tty_);
+  char *name = pty_getproc(fd, tty);
+  free(tty);
+
+  if (name == NULL) {
+    return info.GetReturnValue().SetUndefined();
+  }
+
+  v8::Local<v8::String> name_ = Nan::New<v8::String>(name).ToLocalChecked();
+  free(name);
+  return info.GetReturnValue().Set(name_);
+}
+
+/**
+ * execvpe
+ */
+
+// execvpe(3) is not portable.
+// http://www.gnu.org/software/gnulib/manual/html_node/execvpe.html
+static int
+pty_execvpe(const char *file, char **argv, char **envp) {
+  char **old = environ;
+  environ = envp;
+  int ret = execvp(file, argv);
+  environ = old;
+  return ret;
+}
+
+/**
+ * Nonblocking FD
+ */
+
+static int
+pty_nonblock(int fd) {
+  int flags = fcntl(fd, F_GETFL, 0);
+  if (flags == -1) return -1;
+  return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+}
+
+/**
+ * pty_waitpid
+ * Wait for SIGCHLD to read exit status.
+ */
+
+static void
+pty_waitpid(void *data) {
+  int ret;
+  int stat_loc;
+
+  pty_baton *baton = static_cast<pty_baton*>(data);
+
+  errno = 0;
+
+  if ((ret = waitpid(baton->pid, &stat_loc, 0)) != baton->pid) {
+    if (ret == -1 && errno == EINTR) {
+      return pty_waitpid(baton);
+    }
+    if (ret == -1 && errno == ECHILD) {
+      // XXX node v0.8.x seems to have this problem.
+      // waitpid is already handled elsewhere.
+      ;
+    } else {
+      assert(false);
+    }
+  }
+
+  if (WIFEXITED(stat_loc)) {
+    baton->exit_code = WEXITSTATUS(stat_loc); // errno?
+  }
+
+  if (WIFSIGNALED(stat_loc)) {
+    baton->signal_code = WTERMSIG(stat_loc);
+  }
+
+  uv_async_send(&baton->async);
+}
+
+/**
+ * pty_after_waitpid
+ * Callback after exit status has been read.
+ */
+
+static void
+pty_after_waitpid(uv_async_t *async) {
+  Nan::HandleScope scope;
+  pty_baton *baton = static_cast<pty_baton*>(async->data);
+
+  v8::Local<v8::Value> argv[] = {
+    Nan::New<v8::Integer>(baton->exit_code),
+    Nan::New<v8::Integer>(baton->signal_code),
+  };
+
+  v8::Local<v8::Function> cb = Nan::New<v8::Function>(baton->cb);
+  baton->cb.Reset();
+  memset(&baton->cb, -1, sizeof(baton->cb));
+  Nan::AsyncResource resource("pty_after_waitpid");
+  resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), cb, 2, argv);
+
+  uv_close((uv_handle_t *)async, pty_after_close);
+}
+
+/**
+ * pty_after_close
+ * uv_close() callback - free handle data
+ */
+
+static void
+pty_after_close(uv_handle_t *handle) {
+  uv_async_t *async = (uv_async_t *)handle;
+  pty_baton *baton = static_cast<pty_baton*>(async->data);
+  delete baton;
+}
+
+/**
+ * pty_getproc
+ * Taken from tmux.
+ */
+
+// Taken from: tmux (http://tmux.sourceforge.net/)
+// Copyright (c) 2009 Nicholas Marriott <nicm@users.sourceforge.net>
+// Copyright (c) 2009 Joshua Elsasser <josh@elsasser.org>
+// Copyright (c) 2009 Todd Carson <toc@daybefore.net>
+//
+// Permission to use, copy, modify, and distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
+// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
+// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+#if defined(__linux__)
+
+static char *
+pty_getproc(int fd, char *tty) {
+  FILE *f;
+  char *path, *buf;
+  size_t len;
+  int ch;
+  pid_t pgrp;
+  int r;
+
+  if ((pgrp = tcgetpgrp(fd)) == -1) {
+    return NULL;
+  }
+
+  r = asprintf(&path, "/proc/%lld/cmdline", (long long)pgrp);
+  if (r == -1 || path == NULL) return NULL;
+
+  if ((f = fopen(path, "r")) == NULL) {
+    free(path);
+    return NULL;
+  }
+
+  free(path);
+
+  len = 0;
+  buf = NULL;
+  while ((ch = fgetc(f)) != EOF) {
+    if (ch == '\0') break;
+    buf = (char *)realloc(buf, len + 2);
+    if (buf == NULL) return NULL;
+    buf[len++] = ch;
+  }
+
+  if (buf != NULL) {
+    buf[len] = '\0';
+  }
+
+  fclose(f);
+  return buf;
+}
+
+#elif defined(__APPLE__)
+
+static char *
+pty_getproc(int fd, char *tty) {
+  int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
+  size_t size;
+  struct kinfo_proc kp;
+
+  if ((mib[3] = tcgetpgrp(fd)) == -1) {
+    return NULL;
+  }
+
+  size = sizeof kp;
+  if (sysctl(mib, 4, &kp, &size, NULL, 0) == -1) {
+    return NULL;
+  }
+
+  if (*kp.kp_proc.p_comm == '\0') {
+    return NULL;
+  }
+
+  return strdup(kp.kp_proc.p_comm);
+}
+
+#else
+
+static char *
+pty_getproc(int fd, char *tty) {
+  return NULL;
+}
+
+#endif
+
+/**
+ * openpty(3) / forkpty(3)
+ */
+
+static int
+pty_openpty(int *amaster,
+            int *aslave,
+            char *name,
+            const struct termios *termp,
+            const struct winsize *winp) {
+#if defined(__sun)
+  char *slave_name;
+  int slave;
+  int master = open("/dev/ptmx", O_RDWR | O_NOCTTY);
+  if (master == -1) return -1;
+  if (amaster) *amaster = master;
+
+  if (grantpt(master) == -1) goto err;
+  if (unlockpt(master) == -1) goto err;
+
+  slave_name = ptsname(master);
+  if (slave_name == NULL) goto err;
+  if (name) strcpy(name, slave_name);
+
+  slave = open(slave_name, O_RDWR | O_NOCTTY);
+  if (slave == -1) goto err;
+  if (aslave) *aslave = slave;
+
+  ioctl(slave, I_PUSH, "ptem");
+  ioctl(slave, I_PUSH, "ldterm");
+  ioctl(slave, I_PUSH, "ttcompat");
+
+  if (termp) tcsetattr(slave, TCSAFLUSH, termp);
+  if (winp) ioctl(slave, TIOCSWINSZ, winp);
+
+  return 0;
+
+err:
+  close(master);
+  return -1;
+#else
+  return openpty(amaster, aslave, name, (termios *)termp, (winsize *)winp);
+#endif
+}
+
+static pid_t
+pty_forkpty(int *amaster,
+            char *name,
+            const struct termios *termp,
+            const struct winsize *winp) {
+#if defined(__sun)
+  int master, slave;
+
+  int ret = pty_openpty(&master, &slave, name, termp, winp);
+  if (ret == -1) return -1;
+  if (amaster) *amaster = master;
+
+  pid_t pid = fork();
+
+  switch (pid) {
+    case -1:
+      close(master);
+      close(slave);
+      return -1;
+    case 0:
+      close(master);
+
+      setsid();
+
+#if defined(TIOCSCTTY)
+      // glibc does this
+      if (ioctl(slave, TIOCSCTTY, NULL) == -1) {
+        _exit(1);
+      }
+#endif
+
+      dup2(slave, 0);
+      dup2(slave, 1);
+      dup2(slave, 2);
+
+      if (slave > 2) close(slave);
+
+      return 0;
+    default:
+      close(slave);
+      return pid;
+  }
+
+  return -1;
+#else
+  return forkpty(amaster, name, (termios *)termp, (winsize *)winp);
+#endif
+}
+
+/**
+ * Init
+ */
+
+NAN_MODULE_INIT(init) {
+  Nan::HandleScope scope;
+  Nan::Export(target, "fork", PtyFork);
+  Nan::Export(target, "open", PtyOpen);
+  Nan::Export(target, "resize", PtyResize);
+  Nan::Export(target, "process", PtyGetProc);
+}
+
+NODE_MODULE(pty, init)
diff --git a/node_modules/node-pty/src/unixTerminal.test.ts b/node_modules/node-pty/src/unixTerminal.test.ts
new file mode 100644 (file)
index 0000000..b9d330f
--- /dev/null
@@ -0,0 +1,108 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import { UnixTerminal } from './unixTerminal';
+import * as assert from 'assert';
+import * as path from 'path';
+import { pollUntil } from './testUtils.test';
+
+const FIXTURES_PATH = path.normalize(path.join(__dirname, '..', 'fixtures', 'utf8-character.txt'));
+
+if (process.platform !== 'win32') {
+  describe('UnixTerminal', () => {
+    describe('Constructor', () => {
+      it('should set a valid pts name', () => {
+        const term = new UnixTerminal('/bin/bash', [], {});
+        let regExp;
+        if (process.platform === 'linux') {
+          // https://linux.die.net/man/4/pts
+          regExp = /^\/dev\/pts\/\d+$/;
+        }
+        if (process.platform === 'darwin') {
+          // https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man4/pty.4.html
+          regExp = /^\/dev\/tty[p-sP-S][a-z0-9]+$/;
+        }
+        if (regExp) {
+          assert.ok(regExp.test((<any>term)._pty), '"' + (<any>term)._pty + '" should match ' + regExp.toString());
+        }
+      });
+    });
+
+    describe('PtyForkEncodingOption', () => {
+      it('should default to utf8', (done) => {
+        const term = new UnixTerminal('/bin/bash', [ '-c', `cat "${FIXTURES_PATH}"` ]);
+        term.on('data', (data) => {
+          assert.equal(typeof data, 'string');
+          assert.equal(data, '\u00E6');
+          done();
+        });
+      });
+      it('should return a Buffer when encoding is null', (done) => {
+        const term = new UnixTerminal('/bin/bash', [ '-c', `cat "${FIXTURES_PATH}"` ], {
+          encoding: null
+        });
+        term.on('data', (data) => {
+          assert.equal(typeof data, 'object');
+          assert.ok(data instanceof Buffer);
+          assert.equal(0xC3, data[0]);
+          assert.equal(0xA6, data[1]);
+          done();
+        });
+      });
+      it('should support other encodings', (done) => {
+        const text = 'test æ!';
+        const term = new UnixTerminal(null, ['-c', 'echo "' + text + '"'], {
+          encoding: 'base64'
+        });
+        let buffer = '';
+        term.on('data', (data) => {
+          assert.equal(typeof data, 'string');
+          buffer += data;
+        });
+        term.on('exit', () => {
+          assert.equal(Buffer.alloc(8, buffer, 'base64').toString().replace('\r', '').replace('\n', ''), text);
+          done();
+        });
+      });
+    });
+
+    describe('open', () => {
+      let term: UnixTerminal;
+
+      afterEach(() => {
+        if (term) {
+          term.slave.destroy();
+          term.master.destroy();
+        }
+      });
+
+      it('should open a pty with access to a master and slave socket', (done) => {
+        let doneCalled = false;
+        term = UnixTerminal.open({});
+
+        let slavebuf = '';
+        term.slave.on('data', (data) => {
+          slavebuf += data;
+        });
+
+        let masterbuf = '';
+        term.master.on('data', (data) => {
+          masterbuf += data;
+        });
+
+        pollUntil(() => {
+          if (masterbuf === 'slave\r\nmaster\r\n' && slavebuf === 'master\n') {
+            done();
+            return true;
+          }
+          return false;
+        }, 200, 10);
+
+        term.slave.write('slave\n');
+        term.master.write('master\n');
+      });
+    });
+  });
+}
diff --git a/node_modules/node-pty/src/unixTerminal.ts b/node_modules/node-pty/src/unixTerminal.ts
new file mode 100644 (file)
index 0000000..58e4567
--- /dev/null
@@ -0,0 +1,299 @@
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+import * as net from 'net';
+import { Terminal, DEFAULT_COLS, DEFAULT_ROWS } from './terminal';
+import { IProcessEnv, IPtyForkOptions, IPtyOpenOptions } from './interfaces';
+import { ArgvOrCommandLine } from './types';
+import { assign } from './utils';
+
+let pty: IUnixNative;
+try {
+  pty = require('../build/Release/pty.node');
+} catch (outerError) {
+  try {
+    pty = require('../build/Debug/pty.node');
+  } catch (innerError) {
+    console.error('innerError', innerError);
+    // Re-throw the exception from the Release require if the Debug require fails as well
+    throw outerError;
+  }
+}
+
+const DEFAULT_FILE = 'sh';
+const DEFAULT_NAME = 'xterm';
+const DESTROY_SOCKET_TIMEOUT_MS = 200;
+
+export class UnixTerminal extends Terminal {
+  protected _fd: number;
+  protected _pty: string;
+
+  protected _file: string;
+  protected _name: string;
+
+  protected _readable: boolean;
+  protected _writable: boolean;
+
+  private _boundClose: boolean;
+  private _emittedClose: boolean;
+  private _master: net.Socket;
+  private _slave: net.Socket;
+
+  public get master(): net.Socket { return this._master; }
+  public get slave(): net.Socket { return this._slave; }
+
+  constructor(file?: string, args?: ArgvOrCommandLine, opt?: IPtyForkOptions) {
+    super(opt);
+
+    if (typeof args === 'string') {
+      throw new Error('args as a string is not supported on unix.');
+    }
+
+    // Initialize arguments
+    args = args || [];
+    file = file || DEFAULT_FILE;
+    opt = opt || {};
+    opt.env = opt.env || process.env;
+
+    this._cols = opt.cols || DEFAULT_COLS;
+    this._rows = opt.rows || DEFAULT_ROWS;
+    const uid = opt.uid || -1;
+    const gid = opt.gid || -1;
+    const env = assign({}, opt.env);
+
+    if (opt.env === process.env) {
+      this._sanitizeEnv(env);
+    }
+
+    const cwd = opt.cwd || process.cwd();
+    const name = opt.name || env.TERM || DEFAULT_NAME;
+    env.TERM = name;
+    const parsedEnv = this._parseEnv(env);
+
+    const encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
+
+    const onexit = (code: number, signal: number) => {
+      // XXX Sometimes a data event is emitted after exit. Wait til socket is
+      // destroyed.
+      if (!this._emittedClose) {
+        if (this._boundClose) {
+          return;
+        }
+        this._boundClose = true;
+        // From macOS High Sierra 10.13.2 sometimes the socket never gets
+        // closed. A timeout is applied here to avoid the terminal never being
+        // destroyed when this occurs.
+        let timeout = setTimeout(() => {
+          timeout = null;
+          // Destroying the socket now will cause the close event to fire
+          this._socket.destroy();
+        }, DESTROY_SOCKET_TIMEOUT_MS);
+        this.once('close', () => {
+          if (timeout !== null) {
+            clearTimeout(timeout);
+          }
+          this.emit('exit', code, signal);
+        });
+        return;
+      }
+      this.emit('exit', code, signal);
+    };
+
+    // fork
+    const term = pty.fork(file, args, parsedEnv, cwd, this._cols, this._rows, uid, gid, (encoding === 'utf8'), onexit);
+
+    this._socket = new PipeSocket(term.fd);
+    if (encoding !== null) {
+      this._socket.setEncoding(encoding);
+    }
+
+    // setup
+    this._socket.on('error', (err: any) => {
+      // NOTE: fs.ReadStream gets EAGAIN twice at first:
+      if (err.code) {
+        if (~err.code.indexOf('EAGAIN')) {
+          return;
+        }
+      }
+
+      // close
+      this._close();
+      // EIO on exit from fs.ReadStream:
+      if (!this._emittedClose) {
+        this._emittedClose = true;
+        this.emit('close');
+      }
+
+      // EIO, happens when someone closes our child process: the only process in
+      // the terminal.
+      // node < 0.6.14: errno 5
+      // node >= 0.6.14: read EIO
+      if (err.code) {
+        if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) {
+          return;
+        }
+      }
+
+      // throw anything else
+      if (this.listeners('error').length < 2) {
+        throw err;
+      }
+    });
+
+    this._pid = term.pid;
+    this._fd = term.fd;
+    this._pty = term.pty;
+
+    this._file = file;
+    this._name = name;
+
+    this._readable = true;
+    this._writable = true;
+
+    this._socket.on('close', () => {
+      if (this._emittedClose) {
+        return;
+      }
+      this._emittedClose = true;
+      this._close();
+      this.emit('close');
+    });
+
+    this._forwardEvents();
+  }
+
+  protected _write(data: string): void {
+    this._socket.write(data);
+  }
+
+  /**
+   * openpty
+   */
+
+  public static open(opt: IPtyOpenOptions): UnixTerminal {
+    const self: UnixTerminal = Object.create(UnixTerminal.prototype);
+    opt = opt || {};
+
+    if (arguments.length > 1) {
+      opt = {
+        cols: arguments[1],
+        rows: arguments[2]
+      };
+    }
+
+    const cols = opt.cols || DEFAULT_COLS;
+    const rows = opt.rows || DEFAULT_ROWS;
+    const encoding = (opt.encoding === undefined ? 'utf8' : opt.encoding);
+
+    // open
+    const term: IUnixOpenProcess = pty.open(cols, rows);
+
+    self._master = new PipeSocket(<number>term.master);
+    if (encoding !== null) {
+        self._master.setEncoding(encoding);
+    }
+    self._master.resume();
+
+    self._slave = new PipeSocket(term.slave);
+    if (encoding !== null) {
+        self._slave.setEncoding(encoding);
+    }
+    self._slave.resume();
+
+    self._socket = self._master;
+    self._pid = null;
+    self._fd = term.master;
+    self._pty = term.pty;
+
+    self._file = process.argv[0] || 'node';
+    self._name = process.env.TERM || '';
+
+    self._readable = true;
+    self._writable = true;
+
+    self._socket.on('error', err => {
+      self._close();
+      if (self.listeners('error').length < 2) {
+        throw err;
+      }
+    });
+
+    self._socket.on('close', () => {
+      self._close();
+    });
+
+    return self;
+  }
+
+  public destroy(): void {
+    this._close();
+
+    // Need to close the read stream so node stops reading a dead file
+    // descriptor. Then we can safely SIGHUP the shell.
+    this._socket.once('close', () => {
+      this.kill('SIGHUP');
+    });
+
+    this._socket.destroy();
+  }
+
+  public kill(signal?: string): void {
+    try {
+      process.kill(this.pid, signal || 'SIGHUP');
+    } catch (e) { /* swallow */ }
+  }
+
+  /**
+   * Gets the name of the process.
+   */
+  public get process(): string {
+    return pty.process(this._fd, this._pty) || this._file;
+  }
+
+  /**
+   * TTY
+   */
+
+  public resize(cols: number, rows: number): void {
+    if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
+      throw new Error('resizing must be done using positive cols and rows');
+    }
+    pty.resize(this._fd, cols, rows);
+    this._cols = cols;
+    this._rows = rows;
+  }
+
+  private _sanitizeEnv(env: IProcessEnv): void {
+      // Make sure we didn't start our server from inside tmux.
+      delete env['TMUX'];
+      delete env['TMUX_PANE'];
+
+      // Make sure we didn't start our server from inside screen.
+      // http://web.mit.edu/gnu/doc/html/screen_20.html
+      delete env['STY'];
+      delete env['WINDOW'];
+
+      // Delete some variables that might confuse our terminal.
+      delete env['WINDOWID'];
+      delete env['TERMCAP'];
+      delete env['COLUMNS'];
+      delete env['LINES'];
+  }
+}
+
+/**
+ * Wraps net.Socket to force the handle type "PIPE" by temporarily overwriting
+ * tty_wrap.guessHandleType.
+ * See: https://github.com/chjj/pty.js/issues/103
+ */
+class PipeSocket extends net.Socket {
+  constructor(fd: number) {
+    const { Pipe, constants } = (<any>process).binding('pipe_wrap'); // tslint:disable-line
+    // @types/node has fd as string? https://github.com/DefinitelyTyped/DefinitelyTyped/pull/18275
+    const handle = new Pipe(constants.SOCKET);
+    handle.open(fd);
+    super(<any>{ handle });
+  }
+}
diff --git a/node_modules/node-pty/src/utils.ts b/node_modules/node-pty/src/utils.ts
new file mode 100644 (file)
index 0000000..6306c8b
--- /dev/null
@@ -0,0 +1,9 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+export function assign(target: any, ...sources: any[]): any {
+  sources.forEach(source => Object.keys(source).forEach(key => target[key] = source[key]));
+  return target;
+}
diff --git a/node_modules/node-pty/src/win/conpty.cc b/node_modules/node-pty/src/win/conpty.cc
new file mode 100644 (file)
index 0000000..4500f6e
--- /dev/null
@@ -0,0 +1,455 @@
+/**
+ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ *
+ * pty.cc:
+ *   This file is responsible for starting processes
+ *   with pseudo-terminal file descriptors.
+ */
+
+// node versions lower than 10 define this as 0x502 which disables many of the definitions needed to compile
+#include <node_version.h>
+#if NODE_MODULE_VERSION <= 57
+  #define _WIN32_WINNT 0x600
+#endif
+
+#include <iostream>
+#include <nan.h>
+#include <Shlwapi.h> // PathCombine, PathIsRelative
+#include <sstream>
+#include <string>
+#include <vector>
+#include <Windows.h>
+#include <strsafe.h>
+#include "path_util.h"
+
+extern "C" void init(v8::Local<v8::Object>);
+
+// Taken from the RS5 Windows SDK, but redefined here in case we're targeting <= 17134
+#ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
+#define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE \
+  ProcThreadAttributeValue(22, FALSE, TRUE, FALSE)
+
+typedef VOID* HPCON;
+typedef HRESULT (__stdcall *PFNCREATEPSEUDOCONSOLE)(COORD c, HANDLE hIn, HANDLE hOut, DWORD dwFlags, HPCON* phpcon);
+typedef HRESULT (__stdcall *PFNRESIZEPSEUDOCONSOLE)(HPCON hpc, COORD newSize);
+typedef void (__stdcall *PFNCLOSEPSEUDOCONSOLE)(HPCON hpc);
+
+#endif
+
+struct pty_baton {
+  int id;
+  HANDLE hIn;
+  HANDLE hOut;
+  HPCON hpc;
+
+  HANDLE hShell;
+  HANDLE hWait;
+  Nan::Callback cb;
+  uv_async_t async;
+  uv_thread_t tid;
+
+  pty_baton(int _id, HANDLE _hIn, HANDLE _hOut, HPCON _hpc) : id(_id), hIn(_hIn), hOut(_hOut), hpc(_hpc) {};
+};
+
+static std::vector<pty_baton*> ptyHandles;
+static volatile LONG ptyCounter;
+
+static pty_baton* get_pty_baton(int id) {
+  for (size_t i = 0; i < ptyHandles.size(); ++i) {
+    pty_baton* ptyHandle = ptyHandles[i];
+    if (ptyHandle->id == id) {
+      return ptyHandle;
+    }
+  }
+  return nullptr;
+}
+
+template <typename T>
+std::vector<T> vectorFromString(const std::basic_string<T> &str) {
+    return std::vector<T>(str.begin(), str.end());
+}
+
+void throwNanError(const Nan::FunctionCallbackInfo<v8::Value>* info, const char* text, const bool getLastError) {
+  std::stringstream errorText;
+  errorText << text;
+  if (getLastError) {
+    errorText << ", error code: " << GetLastError();
+  }
+  Nan::ThrowError(errorText.str().c_str());
+  (*info).GetReturnValue().SetUndefined();
+}
+
+// Returns a new server named pipe.  It has not yet been connected.
+bool createDataServerPipe(bool write,
+                          std::wstring kind,
+                          HANDLE* hServer,
+                          std::wstring &name,
+                          const std::wstring &pipeName)
+{
+  *hServer = INVALID_HANDLE_VALUE;
+
+  name = L"\\\\.\\pipe\\" + pipeName + L"-" + kind;
+
+  const DWORD winOpenMode =  PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE/*  | FILE_FLAG_OVERLAPPED */;
+
+  SECURITY_ATTRIBUTES sa = {};
+  sa.nLength = sizeof(sa);
+
+  *hServer = CreateNamedPipeW(
+      name.c_str(),
+      /*dwOpenMode=*/winOpenMode,
+      /*dwPipeMode=*/PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+      /*nMaxInstances=*/1,
+      /*nOutBufferSize=*/0,
+      /*nInBufferSize=*/0,
+      /*nDefaultTimeOut=*/30000,
+      &sa);
+
+  return *hServer != INVALID_HANDLE_VALUE;
+}
+
+HRESULT CreateNamedPipesAndPseudoConsole(COORD size,
+                                         DWORD dwFlags,
+                                         HANDLE *phInput,
+                                         HANDLE *phOutput,
+                                         HPCON* phPC,
+                                         std::wstring& inName,
+                                         std::wstring& outName,
+                                         const std::wstring& pipeName)
+{
+  HANDLE hLibrary = LoadLibraryExW(L"kernel32.dll", 0, 0);
+  bool fLoadedDll = hLibrary != nullptr;
+  if (fLoadedDll)
+  {
+    PFNCREATEPSEUDOCONSOLE const pfnCreate = (PFNCREATEPSEUDOCONSOLE)GetProcAddress((HMODULE)hLibrary, "CreatePseudoConsole");
+    if (pfnCreate)
+    {
+      if (phPC == NULL || phInput == NULL || phOutput == NULL)
+      {
+        return E_INVALIDARG;
+      }
+
+      bool success = createDataServerPipe(true, L"in", phInput, inName, pipeName);
+      if (!success)
+      {
+        return HRESULT_FROM_WIN32(GetLastError());
+      }
+      success = createDataServerPipe(false, L"out", phOutput, outName, pipeName);
+      if (!success)
+      {
+        return HRESULT_FROM_WIN32(GetLastError());
+      }
+      return pfnCreate(size, *phInput, *phOutput, dwFlags, phPC);
+    }
+    else
+    {
+      // Failed to find CreatePseudoConsole in kernel32. This is likely because
+      //    the user is not running a build of Windows that supports that API.
+      //    We should fall back to winpty in this case.
+      return HRESULT_FROM_WIN32(GetLastError());
+    }
+  }
+
+  // Failed to find  kernel32. This is realy unlikely - honestly no idea how
+  //    this is even possible to hit. But if it does happen, fall back to winpty.
+  return HRESULT_FROM_WIN32(GetLastError());
+}
+
+static NAN_METHOD(PtyStartProcess) {
+  Nan::HandleScope scope;
+
+  v8::Local<v8::Object> marshal;
+  std::wstring inName, outName;
+  BOOL fSuccess = FALSE;
+  std::unique_ptr<wchar_t[]> mutableCommandline;
+  PROCESS_INFORMATION _piClient{};
+
+  if (info.Length() != 6 ||
+      !info[0]->IsString() ||
+      !info[1]->IsNumber() ||
+      !info[2]->IsNumber() ||
+      !info[3]->IsBoolean() ||
+      !info[4]->IsString() ||
+      !info[5]->IsBoolean()) {
+    Nan::ThrowError("Usage: pty.startProcess(file, cols, rows, debug, pipeName, inheritCursor)");
+    return;
+  }
+
+  const std::wstring filename(path_util::to_wstring(Nan::Utf8String(info[0])));
+  const SHORT cols = info[1]->Uint32Value(Nan::GetCurrentContext()).FromJust();
+  const SHORT rows = info[2]->Uint32Value(Nan::GetCurrentContext()).FromJust();
+  const bool debug = Nan::To<bool>(info[3]).FromJust();
+  const std::wstring pipeName(path_util::to_wstring(Nan::Utf8String(info[4])));
+  const bool inheritCursor = Nan::To<bool>(info[5]).FromJust();
+
+  // use environment 'Path' variable to determine location of
+  // the relative path that we have recieved (e.g cmd.exe)
+  std::wstring shellpath;
+  if (::PathIsRelativeW(filename.c_str())) {
+    shellpath = path_util::get_shell_path(filename.c_str());
+  } else {
+    shellpath = filename;
+  }
+
+  std::string shellpath_(shellpath.begin(), shellpath.end());
+
+  if (shellpath.empty() || !path_util::file_exists(shellpath)) {
+    std::stringstream why;
+    why << "File not found: " << shellpath_;
+    Nan::ThrowError(why.str().c_str());
+    return;
+  }
+
+  HANDLE hIn, hOut;
+  HPCON hpc;
+  HRESULT hr = CreateNamedPipesAndPseudoConsole({cols, rows}, inheritCursor ? 1/*PSEUDOCONSOLE_INHERIT_CURSOR*/ : 0, &hIn, &hOut, &hpc, inName, outName, pipeName);
+
+  // Restore default handling of ctrl+c
+  SetConsoleCtrlHandler(NULL, FALSE);
+
+  // Set return values
+  marshal = Nan::New<v8::Object>();
+
+  if (SUCCEEDED(hr)) {
+    // We were able to instantiate a conpty
+    const int ptyId = InterlockedIncrement(&ptyCounter);
+    Nan::Set(marshal, Nan::New<v8::String>("pty").ToLocalChecked(), Nan::New<v8::Number>(ptyId));
+    ptyHandles.insert(ptyHandles.end(), new pty_baton(ptyId, hIn, hOut, hpc));
+  } else {
+    Nan::ThrowError("Cannot launch conpty");
+    return;
+  }
+
+  Nan::Set(marshal, Nan::New<v8::String>("fd").ToLocalChecked(), Nan::New<v8::Number>(-1));
+  {
+    std::string coninPipeNameStr(inName.begin(), inName.end());
+    Nan::Set(marshal, Nan::New<v8::String>("conin").ToLocalChecked(), Nan::New<v8::String>(coninPipeNameStr).ToLocalChecked());
+
+    std::string conoutPipeNameStr(outName.begin(), outName.end());
+    Nan::Set(marshal, Nan::New<v8::String>("conout").ToLocalChecked(), Nan::New<v8::String>(conoutPipeNameStr).ToLocalChecked());
+  }
+  info.GetReturnValue().Set(marshal);
+}
+
+VOID CALLBACK OnProcessExitWinEvent(
+    _In_ PVOID context,
+    _In_ BOOLEAN TimerOrWaitFired) {
+  pty_baton *baton = static_cast<pty_baton*>(context);
+
+  // Fire OnProcessExit
+  uv_async_send(&baton->async);
+}
+
+static void OnProcessExit(uv_async_t *async) {
+  Nan::HandleScope scope;
+  pty_baton *baton = static_cast<pty_baton*>(async->data);
+
+  UnregisterWait(baton->hWait);
+
+  // Get exit code
+  DWORD exitCode = 0;
+  GetExitCodeProcess(baton->hShell, &exitCode);
+
+  // Call function
+  v8::Local<v8::Value> args[1] = {
+    Nan::New<v8::Number>(exitCode)
+  };
+
+  Nan::AsyncResource asyncResource("node-pty.callback");
+  baton->cb.Call(1, args, &asyncResource);
+  // Clean up
+  baton->cb.Reset();
+}
+
+static NAN_METHOD(PtyConnect) {
+  Nan::HandleScope scope;
+
+  // If we're working with conpty's we need to call ConnectNamedPipe here AFTER
+  //    the Socket has attempted to connect to the other end, then actually
+  //    spawn the process here.
+
+  std::stringstream errorText;
+  BOOL fSuccess = FALSE;
+
+  if (info.Length() != 5 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsString() ||
+      !info[2]->IsString() ||
+      !info[3]->IsArray() ||
+      !info[4]->IsFunction()) {
+    Nan::ThrowError("Usage: pty.connect(id, cmdline, cwd, env, exitCallback)");
+    return;
+  }
+
+  const int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  const std::wstring cmdline(path_util::to_wstring(Nan::Utf8String(info[1])));
+  const std::wstring cwd(path_util::to_wstring(Nan::Utf8String(info[2])));
+  const v8::Local<v8::Array> envValues = info[3].As<v8::Array>();
+  const v8::Local<v8::Function> exitCallback = v8::Local<v8::Function>::Cast(info[4]);
+
+  // Prepare command line
+  std::unique_ptr<wchar_t[]> mutableCommandline = std::make_unique<wchar_t[]>(cmdline.length() + 1);
+  HRESULT hr = StringCchCopyW(mutableCommandline.get(), cmdline.length() + 1, cmdline.c_str());
+
+  // Prepare cwd
+  std::unique_ptr<wchar_t[]> mutableCwd = std::make_unique<wchar_t[]>(cwd.length() + 1);
+  hr = StringCchCopyW(mutableCwd.get(), cwd.length() + 1, cwd.c_str());
+
+  // Prepare environment
+  std::wstring env;
+  if (!envValues.IsEmpty()) {
+    std::wstringstream envBlock;
+    for(uint32_t i = 0; i < envValues->Length(); i++) {
+      std::wstring envValue(path_util::to_wstring(Nan::Utf8String(Nan::Get(envValues, i).ToLocalChecked())));
+      envBlock << envValue << L'\0';
+    }
+    envBlock << L'\0';
+    env = envBlock.str();
+  }
+  auto envV = vectorFromString(env);
+  LPWSTR envArg = envV.empty() ? nullptr : envV.data();
+
+  // Fetch pty handle from ID and start process
+  pty_baton* handle = get_pty_baton(id);
+
+  BOOL success = ConnectNamedPipe(handle->hIn, nullptr);
+  success = ConnectNamedPipe(handle->hOut, nullptr);
+
+  // Attach the pseudoconsole to the client application we're creating
+  STARTUPINFOEXW siEx{0};
+  siEx.StartupInfo.cb = sizeof(STARTUPINFOEXW);
+  siEx.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
+  siEx.StartupInfo.hStdError = nullptr;
+  siEx.StartupInfo.hStdInput = nullptr;
+  siEx.StartupInfo.hStdOutput = nullptr;
+
+  SIZE_T size = 0;
+  InitializeProcThreadAttributeList(NULL, 1, 0, &size);
+  BYTE *attrList = new BYTE[size];
+  siEx.lpAttributeList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrList);
+
+  fSuccess = InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, &size);
+  if (!fSuccess) {
+    return throwNanError(&info, "InitializeProcThreadAttributeList failed", true);
+  }
+  fSuccess = UpdateProcThreadAttribute(siEx.lpAttributeList,
+                                       0,
+                                       PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
+                                       handle->hpc,
+                                       sizeof(HPCON),
+                                       NULL,
+                                       NULL);
+  if (!fSuccess) {
+    return throwNanError(&info, "UpdateProcThreadAttribute failed", true);
+  }
+
+  PROCESS_INFORMATION piClient{};
+  fSuccess = !!CreateProcessW(
+      nullptr,
+      mutableCommandline.get(),
+      nullptr,                      // lpProcessAttributes
+      nullptr,                      // lpThreadAttributes
+      false,                        // bInheritHandles VERY IMPORTANT that this is false
+      EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT, // dwCreationFlags
+      envArg,                       // lpEnvironment
+      mutableCwd.get(),             // lpCurrentDirectory
+      &siEx.StartupInfo,            // lpStartupInfo
+      &piClient                     // lpProcessInformation
+  );
+  if (!fSuccess) {
+    return throwNanError(&info, "Cannot create process", true);
+  }
+
+  // Update handle
+  handle->hShell = piClient.hProcess;
+  handle->cb.Reset(exitCallback);
+  handle->async.data = handle;
+
+  // Setup OnProcessExit callback
+  uv_async_init(uv_default_loop(), &handle->async, OnProcessExit);
+
+  // Setup Windows wait for process exit event
+  RegisterWaitForSingleObject(&handle->hWait, piClient.hProcess, OnProcessExitWinEvent, (PVOID)handle, INFINITE, WT_EXECUTEONLYONCE);
+
+  // Return
+  v8::Local<v8::Object> marshal = Nan::New<v8::Object>();
+  Nan::Set(marshal, Nan::New<v8::String>("pid").ToLocalChecked(), Nan::New<v8::Number>(piClient.dwProcessId));
+  info.GetReturnValue().Set(marshal);
+}
+
+static NAN_METHOD(PtyResize) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 3 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsNumber() ||
+      !info[2]->IsNumber()) {
+    Nan::ThrowError("Usage: pty.resize(id, cols, rows)");
+    return;
+  }
+
+  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  SHORT cols = info[1]->Uint32Value(Nan::GetCurrentContext()).FromJust();
+  SHORT rows = info[2]->Uint32Value(Nan::GetCurrentContext()).FromJust();
+
+  const pty_baton* handle = get_pty_baton(id);
+
+  HANDLE hLibrary = LoadLibraryExW(L"kernel32.dll", 0, 0);
+  bool fLoadedDll = hLibrary != nullptr;
+  if (fLoadedDll)
+  {
+    PFNRESIZEPSEUDOCONSOLE const pfnResizePseudoConsole = (PFNRESIZEPSEUDOCONSOLE)GetProcAddress((HMODULE)hLibrary, "ResizePseudoConsole");
+    if (pfnResizePseudoConsole)
+    {
+      COORD size = {cols, rows};
+      pfnResizePseudoConsole(handle->hpc, size);
+    }
+  }
+
+  return info.GetReturnValue().SetUndefined();
+}
+
+static NAN_METHOD(PtyKill) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 1 ||
+      !info[0]->IsNumber()) {
+    Nan::ThrowError("Usage: pty.kill(id)");
+    return;
+  }
+
+  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
+
+  const pty_baton* handle = get_pty_baton(id);
+
+  HANDLE hLibrary = LoadLibraryExW(L"kernel32.dll", 0, 0);
+  bool fLoadedDll = hLibrary != nullptr;
+  if (fLoadedDll)
+  {
+    PFNCLOSEPSEUDOCONSOLE const pfnClosePseudoConsole = (PFNCLOSEPSEUDOCONSOLE)GetProcAddress((HMODULE)hLibrary, "ClosePseudoConsole");
+    if (pfnClosePseudoConsole)
+    {
+      pfnClosePseudoConsole(handle->hpc);
+    }
+  }
+
+  CloseHandle(handle->hShell);
+
+  return info.GetReturnValue().SetUndefined();
+}
+
+/**
+* Init
+*/
+
+extern "C" void init(v8::Local<v8::Object> target) {
+  Nan::HandleScope scope;
+  Nan::SetMethod(target, "startProcess", PtyStartProcess);
+  Nan::SetMethod(target, "connect", PtyConnect);
+  Nan::SetMethod(target, "resize", PtyResize);
+  Nan::SetMethod(target, "kill", PtyKill);
+};
+
+NODE_MODULE(pty, init);
diff --git a/node_modules/node-pty/src/win/conpty_console_list.cc b/node_modules/node-pty/src/win/conpty_console_list.cc
new file mode 100644 (file)
index 0000000..be135ba
--- /dev/null
@@ -0,0 +1,43 @@
+/**
+ * Copyright (c) 2019, Microsoft Corporation (MIT License).
+ */
+
+#include <nan.h>
+#include <windows.h>
+
+static NAN_METHOD(ApiConsoleProcessList) {
+  if (info.Length() != 1 ||
+      !info[0]->IsNumber()) {
+    Nan::ThrowError("Usage: getConsoleProcessList(shellPid)");
+    return;
+  }
+
+  const SHORT pid = info[0]->Uint32Value(Nan::GetCurrentContext()).FromJust();
+
+  if (!FreeConsole()) {
+    Nan::ThrowError("FreeConsole failed");
+  }
+  if (!AttachConsole(pid)) {
+    Nan::ThrowError("AttachConsole failed");
+  }
+  auto processList = std::vector<DWORD>(64);
+  auto processCount = GetConsoleProcessList(&processList[0], processList.size());
+  if (processList.size() < processCount) {
+      processList.resize(processCount);
+      processCount = GetConsoleProcessList(&processList[0], processList.size());
+  }
+  FreeConsole();
+
+  v8::Local<v8::Array> result = Nan::New<v8::Array>();
+  for (DWORD i = 0; i < processCount; i++) {
+    Nan::Set(result, i, Nan::New<v8::Number>(processList[i]));
+  }
+  info.GetReturnValue().Set(result);
+}
+
+extern "C" void init(v8::Local<v8::Object> target) {
+  Nan::HandleScope scope;
+  Nan::SetMethod(target, "getConsoleProcessList", ApiConsoleProcessList);
+};
+
+NODE_MODULE(pty, init);
diff --git a/node_modules/node-pty/src/win/path_util.cc b/node_modules/node-pty/src/win/path_util.cc
new file mode 100644 (file)
index 0000000..4e69f30
--- /dev/null
@@ -0,0 +1,73 @@
+/**
+ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+#include <nan.h>
+#include <Shlwapi.h> // PathCombine
+
+#include "path_util.h"
+
+namespace path_util {
+
+const wchar_t* to_wstring(const Nan::Utf8String& str) {
+  const char *bytes = *str;
+  unsigned int sizeOfStr = MultiByteToWideChar(CP_UTF8, 0, bytes, -1, NULL, 0);
+  wchar_t *output = new wchar_t[sizeOfStr];
+  MultiByteToWideChar(CP_UTF8, 0, bytes, -1, output, sizeOfStr);
+  return output;
+}
+
+bool file_exists(std::wstring filename) {
+  DWORD attr = ::GetFileAttributesW(filename.c_str());
+  if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
+    return false;
+  }
+  return true;
+}
+
+// cmd.exe -> C:\Windows\system32\cmd.exe
+std::wstring get_shell_path(std::wstring filename) {
+  std::wstring shellpath;
+
+  if (file_exists(filename)) {
+    return shellpath;
+  }
+
+  wchar_t buffer_[MAX_ENV];
+  int read = ::GetEnvironmentVariableW(L"Path", buffer_, MAX_ENV);
+  if (!read) {
+    return shellpath;
+  }
+
+  std::wstring delimiter = L";";
+  size_t pos = 0;
+  std::vector<std::wstring> paths;
+  std::wstring buffer(buffer_);
+  while ((pos = buffer.find(delimiter)) != std::wstring::npos) {
+    paths.push_back(buffer.substr(0, pos));
+    buffer.erase(0, pos + delimiter.length());
+  }
+
+  const wchar_t *filename_ = filename.c_str();
+
+  for (int i = 0; i < paths.size(); ++i) {
+    std::wstring path = paths[i];
+    wchar_t searchPath[MAX_PATH];
+    ::PathCombineW(searchPath, const_cast<wchar_t*>(path.c_str()), filename_);
+
+    if (searchPath == NULL) {
+      continue;
+    }
+
+    if (file_exists(searchPath)) {
+      shellpath = searchPath;
+      break;
+    }
+  }
+
+  return shellpath;
+}
+
+}  // namespace path_util
diff --git a/node_modules/node-pty/src/win/path_util.h b/node_modules/node-pty/src/win/path_util.h
new file mode 100644 (file)
index 0000000..8dd58d2
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+#ifndef NODE_PTY_PATH_UTIL_H_
+#define NODE_PTY_PATH_UTIL_H_
+
+#include <nan.h>
+
+#define MAX_ENV 65536
+
+namespace path_util {
+
+const wchar_t* to_wstring(const Nan::Utf8String& str);
+bool file_exists(std::wstring filename);
+std::wstring get_shell_path(std::wstring filename);
+
+}  // namespace path_util
+
+#endif  // NODE_PTY_PATH_UTIL_H_
diff --git a/node_modules/node-pty/src/win/winpty.cc b/node_modules/node-pty/src/win/winpty.cc
new file mode 100644 (file)
index 0000000..b054dee
--- /dev/null
@@ -0,0 +1,312 @@
+/**
+ * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ *
+ * pty.cc:
+ *   This file is responsible for starting processes
+ *   with pseudo-terminal file descriptors.
+ */
+
+#include <iostream>
+#include <nan.h>
+#include <Shlwapi.h> // PathCombine, PathIsRelative
+#include <sstream>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include <vector>
+#include <winpty.h>
+
+#include "path_util.h"
+
+/**
+* Misc
+*/
+extern "C" void init(v8::Local<v8::Object>);
+
+#define WINPTY_DBG_VARIABLE TEXT("WINPTYDBG")
+
+/**
+* winpty
+*/
+static std::vector<winpty_t *> ptyHandles;
+static volatile LONG ptyCounter;
+
+/**
+* Helpers
+*/
+
+static winpty_t *get_pipe_handle(int handle) {
+  for (size_t i = 0; i < ptyHandles.size(); ++i) {
+    winpty_t *ptyHandle = ptyHandles[i];
+    int current = (int)winpty_agent_process(ptyHandle);
+    if (current == handle) {
+      return ptyHandle;
+    }
+  }
+  return nullptr;
+}
+
+static bool remove_pipe_handle(int handle) {
+  for (size_t i = 0; i < ptyHandles.size(); ++i) {
+    winpty_t *ptyHandle = ptyHandles[i];
+    if ((int)winpty_agent_process(ptyHandle) == handle) {
+      winpty_free(ptyHandle);
+      ptyHandles.erase(ptyHandles.begin() + i);
+      ptyHandle = nullptr;
+      return true;
+    }
+  }
+  return false;
+}
+
+void throw_winpty_error(const char *generalMsg, winpty_error_ptr_t error_ptr) {
+  std::stringstream why;
+  std::wstring msg(winpty_error_msg(error_ptr));
+  std::string msg_(msg.begin(), msg.end());
+  why << generalMsg << ": " << msg_;
+  Nan::ThrowError(why.str().c_str());
+  winpty_error_free(error_ptr);
+}
+
+static NAN_METHOD(PtyGetExitCode) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 1 ||
+      !info[0]->IsNumber()) {
+    Nan::ThrowError("Usage: pty.getExitCode(pidHandle)");
+    return;
+  }
+
+  DWORD exitCode = 0;
+  GetExitCodeProcess((HANDLE)info[0]->IntegerValue(Nan::GetCurrentContext()).FromJust(), &exitCode);
+
+  info.GetReturnValue().Set(Nan::New<v8::Number>(exitCode));
+}
+
+static NAN_METHOD(PtyGetProcessList) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 1 ||
+      !info[0]->IsNumber()) {
+    Nan::ThrowError("Usage: pty.getProcessList(pid)");
+    return;
+  }
+
+  int pid = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
+
+  winpty_t *pc = get_pipe_handle(pid);
+  if (pc == nullptr) {
+    info.GetReturnValue().Set(Nan::New<v8::Array>(0));
+    return;
+  }
+  int processList[64];
+  const int processCount = 64;
+  int actualCount = winpty_get_console_process_list(pc, processList, processCount, nullptr);
+
+  v8::Local<v8::Array> result = Nan::New<v8::Array>(actualCount);
+  for (uint32_t i = 0; i < actualCount; i++) {
+    Nan::Set(result, i, Nan::New<v8::Number>(processList[i]));
+  }
+  info.GetReturnValue().Set(result);
+}
+
+static NAN_METHOD(PtyStartProcess) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 7 ||
+      !info[0]->IsString() ||
+      !info[1]->IsString() ||
+      !info[2]->IsArray() ||
+      !info[3]->IsString() ||
+      !info[4]->IsNumber() ||
+      !info[5]->IsNumber() ||
+      !info[6]->IsBoolean()) {
+    Nan::ThrowError("Usage: pty.startProcess(file, cmdline, env, cwd, cols, rows, debug)");
+    return;
+  }
+
+  std::stringstream why;
+
+  const wchar_t *filename = path_util::to_wstring(Nan::Utf8String(info[0]));
+  const wchar_t *cmdline = path_util::to_wstring(Nan::Utf8String(info[1]));
+  const wchar_t *cwd = path_util::to_wstring(Nan::Utf8String(info[3]));
+
+  // create environment block
+  std::wstring env;
+  const v8::Local<v8::Array> envValues = v8::Local<v8::Array>::Cast(info[2]);
+  if (!envValues.IsEmpty()) {
+
+    std::wstringstream envBlock;
+
+    for(uint32_t i = 0; i < envValues->Length(); i++) {
+      std::wstring envValue(path_util::to_wstring(Nan::Utf8String(Nan::Get(envValues, i).ToLocalChecked())));
+      envBlock << envValue << L'\0';
+    }
+
+    env = envBlock.str();
+  }
+
+  // use environment 'Path' variable to determine location of
+  // the relative path that we have recieved (e.g cmd.exe)
+  std::wstring shellpath;
+  if (::PathIsRelativeW(filename)) {
+    shellpath = path_util::get_shell_path(filename);
+  } else {
+    shellpath = filename;
+  }
+
+  std::string shellpath_(shellpath.begin(), shellpath.end());
+
+  if (shellpath.empty() || !path_util::file_exists(shellpath)) {
+    why << "File not found: " << shellpath_;
+    Nan::ThrowError(why.str().c_str());
+    goto cleanup;
+  }
+
+  int cols = info[4]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  int rows = info[5]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  bool debug = Nan::To<bool>(info[6]).FromJust();
+
+  // Enable/disable debugging
+  SetEnvironmentVariable(WINPTY_DBG_VARIABLE, debug ? "1" : NULL); // NULL = deletes variable
+
+  // Create winpty config
+  winpty_error_ptr_t error_ptr = nullptr;
+  winpty_config_t* winpty_config = winpty_config_new(0, &error_ptr);
+  if (winpty_config == nullptr) {
+    throw_winpty_error("Error creating WinPTY config", error_ptr);
+    goto cleanup;
+  }
+  winpty_error_free(error_ptr);
+
+  // Set pty size on config
+  winpty_config_set_initial_size(winpty_config, cols, rows);
+
+  // Start the pty agent
+  winpty_t *pc = winpty_open(winpty_config, &error_ptr);
+  winpty_config_free(winpty_config);
+  if (pc == nullptr) {
+    throw_winpty_error("Error launching WinPTY agent", error_ptr);
+    goto cleanup;
+  }
+  winpty_error_free(error_ptr);
+
+  // Save pty struct for later use
+  ptyHandles.insert(ptyHandles.end(), pc);
+
+  // Create winpty spawn config
+  winpty_spawn_config_t* config = winpty_spawn_config_new(WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN, shellpath.c_str(), cmdline, cwd, env.c_str(), &error_ptr);
+  if (config == nullptr) {
+    throw_winpty_error("Error creating WinPTY spawn config", error_ptr);
+    goto cleanup;
+  }
+  winpty_error_free(error_ptr);
+
+  // Spawn the new process
+  HANDLE handle = nullptr;
+  BOOL spawnSuccess = winpty_spawn(pc, config, &handle, nullptr, nullptr, &error_ptr);
+  winpty_spawn_config_free(config);
+  if (!spawnSuccess) {
+    throw_winpty_error("Unable to start terminal process", error_ptr);
+    goto cleanup;
+  }
+  winpty_error_free(error_ptr);
+
+  // Set return values
+  v8::Local<v8::Object> marshal = Nan::New<v8::Object>();
+  Nan::Set(marshal, Nan::New<v8::String>("innerPid").ToLocalChecked(), Nan::New<v8::Number>((int)GetProcessId(handle)));
+  Nan::Set(marshal, Nan::New<v8::String>("innerPidHandle").ToLocalChecked(), Nan::New<v8::Number>((int)handle));
+  Nan::Set(marshal, Nan::New<v8::String>("pid").ToLocalChecked(), Nan::New<v8::Number>((int)winpty_agent_process(pc)));
+  Nan::Set(marshal, Nan::New<v8::String>("pty").ToLocalChecked(), Nan::New<v8::Number>(InterlockedIncrement(&ptyCounter)));
+  Nan::Set(marshal, Nan::New<v8::String>("fd").ToLocalChecked(), Nan::New<v8::Number>(-1));
+  {
+    LPCWSTR coninPipeName = winpty_conin_name(pc);
+    std::wstring coninPipeNameWStr(coninPipeName);
+    std::string coninPipeNameStr(coninPipeNameWStr.begin(), coninPipeNameWStr.end());
+    Nan::Set(marshal, Nan::New<v8::String>("conin").ToLocalChecked(), Nan::New<v8::String>(coninPipeNameStr).ToLocalChecked());
+    LPCWSTR conoutPipeName = winpty_conout_name(pc);
+    std::wstring conoutPipeNameWStr(conoutPipeName);
+    std::string conoutPipeNameStr(conoutPipeNameWStr.begin(), conoutPipeNameWStr.end());
+    Nan::Set(marshal, Nan::New<v8::String>("conout").ToLocalChecked(), Nan::New<v8::String>(conoutPipeNameStr).ToLocalChecked());
+  }
+  info.GetReturnValue().Set(marshal);
+
+  goto cleanup;
+
+cleanup:
+  delete filename;
+  delete cmdline;
+  delete cwd;
+}
+
+static NAN_METHOD(PtyResize) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 3 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsNumber() ||
+      !info[2]->IsNumber()) {
+    Nan::ThrowError("Usage: pty.resize(pid, cols, rows)");
+    return;
+  }
+
+  int handle = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  int cols = info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  int rows = info[2]->Int32Value(Nan::GetCurrentContext()).FromJust();
+
+  winpty_t *pc = get_pipe_handle(handle);
+
+  if (pc == nullptr) {
+    Nan::ThrowError("The pty doesn't appear to exist");
+    return;
+  }
+  BOOL success = winpty_set_size(pc, cols, rows, nullptr);
+  if (!success) {
+    Nan::ThrowError("The pty could not be resized");
+    return;
+  }
+
+  return info.GetReturnValue().SetUndefined();
+}
+
+static NAN_METHOD(PtyKill) {
+  Nan::HandleScope scope;
+
+  if (info.Length() != 2 ||
+      !info[0]->IsNumber() ||
+      !info[1]->IsNumber()) {
+    Nan::ThrowError("Usage: pty.kill(pid, innerPidHandle)");
+    return;
+  }
+
+  int handle = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
+  HANDLE innerPidHandle = (HANDLE)info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();
+
+  winpty_t *pc = get_pipe_handle(handle);
+  if (pc == nullptr) {
+    Nan::ThrowError("Pty seems to have been killed already");
+    return;
+  }
+
+  assert(remove_pipe_handle(handle));
+  CloseHandle(innerPidHandle);
+
+  return info.GetReturnValue().SetUndefined();
+}
+
+/**
+* Init
+*/
+
+extern "C" void init(v8::Local<v8::Object> target) {
+  Nan::HandleScope scope;
+  Nan::SetMethod(target, "startProcess", PtyStartProcess);
+  Nan::SetMethod(target, "resize", PtyResize);
+  Nan::SetMethod(target, "kill", PtyKill);
+  Nan::SetMethod(target, "getExitCode", PtyGetExitCode);
+  Nan::SetMethod(target, "getProcessList", PtyGetProcessList);
+};
+
+NODE_MODULE(pty, init);
diff --git a/node_modules/node-pty/src/windowsPtyAgent.test.ts b/node_modules/node-pty/src/windowsPtyAgent.test.ts
new file mode 100644 (file)
index 0000000..dc2104b
--- /dev/null
@@ -0,0 +1,94 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import * as assert from 'assert';
+import { argsToCommandLine } from './windowsPtyAgent';
+
+function check(file: string, args: string | string[], expected: string): void {
+  assert.equal(argsToCommandLine(file, args), expected);
+}
+
+if (process.platform === 'win32') {
+  describe('argsToCommandLine', () => {
+    describe('Plain strings', () => {
+      it('doesn\'t quote plain string', () => {
+        check('asdf', [], 'asdf');
+      });
+      it('doesn\'t escape backslashes', () => {
+        check('\\asdf\\qwer\\', [], '\\asdf\\qwer\\');
+      });
+      it('doesn\'t escape multiple backslashes', () => {
+        check('asdf\\\\qwer', [], 'asdf\\\\qwer');
+      });
+      it('adds backslashes before quotes', () => {
+        check('"asdf"qwer"', [], '\\"asdf\\"qwer\\"');
+      });
+      it('escapes backslashes before quotes', () => {
+        check('asdf\\"qwer', [], 'asdf\\\\\\"qwer');
+      });
+    });
+
+    describe('Quoted strings', () => {
+      it('quotes string with spaces', () => {
+        check('asdf qwer', [], '"asdf qwer"');
+      });
+      it('quotes empty string', () => {
+        check('', [], '""');
+      });
+      it('quotes string with tabs', () => {
+        check('asdf\tqwer', [], '"asdf\tqwer"');
+      });
+      it('escapes only the last backslash', () => {
+        check('\\asdf \\qwer\\', [], '"\\asdf \\qwer\\\\"');
+      });
+      it('doesn\'t escape multiple backslashes', () => {
+        check('asdf \\\\qwer', [], '"asdf \\\\qwer"');
+      });
+      it('escapes backslashes before quotes', () => {
+        check('asdf \\"qwer', [], '"asdf \\\\\\"qwer"');
+      });
+      it('escapes multiple backslashes at the end', () => {
+        check('asdf qwer\\\\', [], '"asdf qwer\\\\\\\\"');
+      });
+    });
+
+    describe('Multiple arguments', () => {
+      it('joins arguments with spaces', () => {
+        check('asdf', ['qwer zxcv', '', '"'], 'asdf "qwer zxcv" "" \\"');
+      });
+      it('array argument all in quotes', () => {
+        check('asdf', ['"surounded by quotes"'], 'asdf \\"surounded by quotes\\"');
+      });
+      it('array argument quotes in the middle', () => {
+        check('asdf', ['quotes "in the" middle'], 'asdf "quotes \\"in the\\" middle"');
+      });
+      it('array argument quotes near start', () => {
+        check('asdf', ['"quotes" near start'], 'asdf "\\"quotes\\" near start"');
+      });
+      it('array argument quotes near end', () => {
+        check('asdf', ['quotes "near end"'], 'asdf "quotes \\"near end\\""');
+      });
+    });
+
+    describe('Args as CommandLine', () => {
+      it('should handle empty string', () => {
+        check('file', '', 'file');
+      });
+      it('should not change args', () => {
+        check('file', 'foo bar baz', 'file foo bar baz');
+        check('file', 'foo \\ba"r \baz', 'file foo \\ba"r \baz');
+      });
+    });
+
+    describe('Real-world cases', () => {
+      it('quotes within quotes', () => {
+        check('cmd.exe', ['/c', 'powershell -noexit -command \'Set-location \"C:\\user\"\''], 'cmd.exe /c "powershell -noexit -command \'Set-location \\\"C:\\user\\"\'"');
+      });
+      it('space within quotes', () => {
+        check('cmd.exe', ['/k', '"C:\\Users\\alros\\Desktop\\test script.bat"'], 'cmd.exe /k \\"C:\\Users\\alros\\Desktop\\test script.bat\\"');
+      });
+    });
+  });
+}
diff --git a/node_modules/node-pty/src/windowsPtyAgent.ts b/node_modules/node-pty/src/windowsPtyAgent.ts
new file mode 100644 (file)
index 0000000..cf8b65d
--- /dev/null
@@ -0,0 +1,313 @@
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import * as os from 'os';
+import * as path from 'path';
+import { Socket } from 'net';
+import { ArgvOrCommandLine } from './types';
+import { fork } from 'child_process';
+
+let conptyNative: IConptyNative;
+let winptyNative: IWinptyNative;
+
+/**
+ * The amount of time to wait for additional data after the conpty shell process has exited before
+ * shutting down the socket. The timer will be reset if a new data event comes in after the timer
+ * has started.
+ */
+const FLUSH_DATA_INTERVAL = 20;
+
+/**
+ * This agent sits between the WindowsTerminal class and provides a common interface for both conpty
+ * and winpty.
+ */
+export class WindowsPtyAgent {
+  private _inSocket: Socket;
+  private _outSocket: Socket;
+  private _pid: number;
+  private _innerPid: number;
+  private _innerPidHandle: number;
+  private _closeTimeout: NodeJS.Timer;
+  private _exitCode: number | undefined;
+
+  private _fd: any;
+  private _pty: number;
+  private _ptyNative: IConptyNative | IWinptyNative;
+
+  public get inSocket(): Socket { return this._inSocket; }
+  public get outSocket(): Socket { return this._outSocket; }
+  public get fd(): any { return this._fd; }
+  public get innerPid(): number { return this._innerPid; }
+  public get pty(): number { return this._pty; }
+
+  constructor(
+    file: string,
+    args: ArgvOrCommandLine,
+    env: string[],
+    cwd: string,
+    cols: number,
+    rows: number,
+    debug: boolean,
+    private _useConpty: boolean | undefined,
+    conptyInheritCursor: boolean = false
+  ) {
+    if (this._useConpty === undefined || this._useConpty === true) {
+      this._useConpty = this._getWindowsBuildNumber() >= 18309;
+    }
+    if (this._useConpty) {
+      if (!conptyNative) {
+        try {
+          conptyNative = require('../build/Release/conpty.node');
+        } catch (outerError) {
+          try {
+            conptyNative = require('../build/Debug/conpty.node');
+          } catch (innerError) {
+            console.error('innerError', innerError);
+            // Re-throw the exception from the Release require if the Debug require fails as well
+            throw outerError;
+          }
+        }
+      }
+    } else {
+      if (!winptyNative) {
+        try {
+          winptyNative = require('../build/Release/pty.node');
+        } catch (outerError) {
+          try {
+            winptyNative = require('../build/Debug/pty.node');
+          } catch (innerError) {
+            console.error('innerError', innerError);
+            // Re-throw the exception from the Release require if the Debug require fails as well
+            throw outerError;
+          }
+        }
+      }
+    }
+    this._ptyNative = this._useConpty ? conptyNative : winptyNative;
+
+    // Sanitize input variable.
+    cwd = path.resolve(cwd);
+
+    // Compose command line
+    const commandLine = argsToCommandLine(file, args);
+
+    // Open pty session.
+    let term: IConptyProcess | IWinptyProcess;
+    if (this._useConpty) {
+      term = (this._ptyNative as IConptyNative).startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor);
+    } else {
+      term = (this._ptyNative as IWinptyNative).startProcess(file, commandLine, env, cwd, cols, rows, debug);
+      this._pid = (term as IWinptyProcess).pid;
+      this._innerPid = (term as IWinptyProcess).innerPid;
+      this._innerPidHandle = (term as IWinptyProcess).innerPidHandle;
+    }
+
+    // Not available on windows.
+    this._fd = term.fd;
+
+    // Generated incremental number that has no real purpose besides  using it
+    // as a terminal id.
+    this._pty = term.pty;
+
+    // Create terminal pipe IPC channel and forward to a local unix socket.
+    this._outSocket = new Socket();
+    this._outSocket.setEncoding('utf8');
+    this._outSocket.connect(term.conout, () => {
+      // TODO: Emit event on agent instead of socket?
+
+      // Emit ready event.
+      this._outSocket.emit('ready_datapipe');
+    });
+
+    this._inSocket = new Socket();
+    this._inSocket.setEncoding('utf8');
+    this._inSocket.connect(term.conin);
+    // TODO: Wait for ready event?
+
+    if (this._useConpty) {
+      const connect = (this._ptyNative as IConptyNative).connect(this._pty, commandLine, cwd, env, c => this._$onProcessExit(c)
+);
+      this._innerPid = connect.pid;
+    }
+  }
+
+  public resize(cols: number, rows: number): void {
+    if (this._useConpty) {
+      if (this._exitCode !== undefined) {
+        throw new Error('Cannot resize a pty that has already exited');
+      }
+      this._ptyNative.resize(this._pty, cols, rows);
+      return;
+    }
+    this._ptyNative.resize(this._pid, cols, rows);
+  }
+
+  public kill(): void {
+    this._inSocket.readable = false;
+    this._inSocket.writable = false;
+    this._outSocket.readable = false;
+    this._outSocket.writable = false;
+    // Tell the agent to kill the pty, this releases handles to the process
+    if (this._useConpty) {
+      this._getConsoleProcessList().then(consoleProcessList => {
+        consoleProcessList.forEach((pid: number) => {
+          try {
+            process.kill(pid);
+          } catch (e) {
+            // Ignore if process cannot be found (kill ESRCH error)
+          }
+        });
+        (this._ptyNative as IConptyNative).kill(this._pty);
+      });
+    } else {
+      (this._ptyNative as IWinptyNative).kill(this._pid, this._innerPidHandle);
+      // Since pty.kill closes the handle it will kill most processes by itself
+      // and process IDs can be reused as soon as all handles to them are
+      // dropped, we want to immediately kill the entire console process list.
+      // If we do not force kill all processes here, node servers in particular
+      // seem to become detached and remain running (see
+      // Microsoft/vscode#26807).
+      const processList: number[] = (this._ptyNative as IWinptyNative).getProcessList(this._pid);
+      processList.forEach(pid => {
+        try {
+          process.kill(pid);
+        } catch (e) {
+          // Ignore if process cannot be found (kill ESRCH error)
+        }
+      });
+    }
+  }
+
+  private _getConsoleProcessList(): Promise<number[]> {
+    return new Promise<number[]>(resolve => {
+      const agent = fork(path.join(__dirname, 'conpty_console_list_agent'), [ this._innerPid.toString() ]);
+      agent.on('message', message => {
+        clearTimeout(timeout);
+        resolve(message.consoleProcessList);
+      });
+      const timeout = setTimeout(() => {
+        // Something went wrong, just send back the shell PID
+        agent.kill();
+        resolve([ this._innerPid ]);
+      }, 5000);
+    });
+  }
+
+  public get exitCode(): number {
+    if (this._useConpty) {
+      return this._exitCode;
+    }
+    return (this._ptyNative as IWinptyNative).getExitCode(this._innerPidHandle);
+  }
+
+  private _getWindowsBuildNumber(): number {
+    const osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
+    let buildNumber: number = 0;
+    if (osVersion && osVersion.length === 4) {
+      buildNumber = parseInt(osVersion[3]);
+    }
+    return buildNumber;
+  }
+
+  private _generatePipeName(): string {
+    return `conpty-${Math.random() * 10000000}`;
+  }
+
+  /**
+   * Triggered from the native side when a contpy process exits.
+   */
+  private _$onProcessExit(exitCode: number): void {
+    this._exitCode = exitCode;
+    this._flushDataAndCleanUp();
+    this._outSocket.on('data', () => this._flushDataAndCleanUp());
+  }
+
+  private _flushDataAndCleanUp(): void {
+    if (this._closeTimeout) {
+      clearTimeout(this._closeTimeout);
+    }
+    this._closeTimeout = setTimeout(() => this._cleanUpProcess(), FLUSH_DATA_INTERVAL);
+  }
+
+  private _cleanUpProcess(): void {
+    this._inSocket.readable = false;
+    this._inSocket.writable = false;
+    this._outSocket.readable = false;
+    this._outSocket.writable = false;
+    this._outSocket.destroy();
+  }
+}
+
+// Convert argc/argv into a Win32 command-line following the escaping convention
+// documented on MSDN (e.g. see CommandLineToArgvW documentation). Copied from
+// winpty project.
+export function argsToCommandLine(file: string, args: ArgvOrCommandLine): string {
+  if (isCommandLine(args)) {
+    if (args.length === 0) {
+      return file;
+    }
+    return `${argsToCommandLine(file, [])} ${args}`;
+  }
+  const argv = [file];
+  Array.prototype.push.apply(argv, args);
+  let result = '';
+  for (let argIndex = 0; argIndex < argv.length; argIndex++) {
+    if (argIndex > 0) {
+      result += ' ';
+    }
+    const arg = argv[argIndex];
+    // if it is empty or it contains whitespace and is not already quoted
+    const hasLopsidedEnclosingQuote = xOr((arg[0] !== '"'), (arg[arg.length - 1] !== '"'));
+    const hasNoEnclosingQuotes = ((arg[0] !== '"') && (arg[arg.length - 1] !== '"'));
+    const quote =
+      arg === '' ||
+      (arg.indexOf(' ') !== -1 ||
+      arg.indexOf('\t') !== -1) &&
+      ((arg.length > 1) &&
+      (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
+    if (quote) {
+      result += '\"';
+    }
+    let bsCount = 0;
+    for (let i = 0; i < arg.length; i++) {
+      const p = arg[i];
+      if (p === '\\') {
+        bsCount++;
+      } else if (p === '"') {
+        result += repeatText('\\', bsCount * 2 + 1);
+        result += '"';
+        bsCount = 0;
+      } else {
+        result += repeatText('\\', bsCount);
+        bsCount = 0;
+        result += p;
+      }
+    }
+    if (quote) {
+      result += repeatText('\\', bsCount * 2);
+      result += '\"';
+    } else {
+      result += repeatText('\\', bsCount);
+    }
+  }
+  return result;
+}
+
+function isCommandLine(args: ArgvOrCommandLine): args is string {
+  return typeof args === 'string';
+}
+
+function repeatText(text: string, count: number): string {
+  let result = '';
+  for (let i = 0; i < count; i++) {
+    result += text;
+  }
+  return result;
+}
+
+function xOr(arg1: boolean, arg2: boolean): boolean {
+  return ((arg1 && !arg2) || (!arg1 && arg2));
+}
diff --git a/node_modules/node-pty/src/windowsTerminal.test.ts b/node_modules/node-pty/src/windowsTerminal.test.ts
new file mode 100644 (file)
index 0000000..9044162
--- /dev/null
@@ -0,0 +1,205 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import * as fs from 'fs';
+import * as assert from 'assert';
+import { WindowsTerminal } from './windowsTerminal';
+import * as path from 'path';
+import * as psList from 'ps-list';
+
+interface IProcessState {
+  // Whether the PID must exist or must not exist
+  [pid: number]: boolean;
+}
+
+interface IWindowsProcessTreeResult {
+  name: string;
+  pid: number;
+}
+
+function pollForProcessState(desiredState: IProcessState, intervalMs: number = 100, timeoutMs: number = 2000): Promise<void> {
+  return new Promise<void>(resolve => {
+    let tries = 0;
+    const interval = setInterval(() => {
+      psList({ all: true }).then(ps => {
+        let success = true;
+        const pids = Object.keys(desiredState).map(k => parseInt(k, 10));
+        pids.forEach(pid => {
+          if (desiredState[pid]) {
+            if (!ps.some(p => p.pid === pid)) {
+              success = false;
+            }
+          } else {
+            if (ps.some(p => p.pid === pid)) {
+              success = false;
+            }
+          }
+        });
+        if (success) {
+          clearInterval(interval);
+          resolve();
+          return;
+        }
+        tries++;
+        if (tries * intervalMs >= timeoutMs) {
+          clearInterval(interval);
+          const processListing = pids.map(k => `${k}: ${desiredState[k]}`).join('\n');
+          assert.fail(`Bad process state, expected:\n${processListing}`);
+          resolve();
+        }
+      });
+    }, intervalMs);
+  });
+}
+
+function pollForProcessTreeSize(pid: number, size: number, intervalMs: number = 100, timeoutMs: number = 2000): Promise<IWindowsProcessTreeResult[]> {
+  return new Promise<IWindowsProcessTreeResult[]>(resolve => {
+    let tries = 0;
+    const interval = setInterval(() => {
+      psList({ all: true }).then(ps => {
+        const openList: IWindowsProcessTreeResult[] = [];
+        openList.push(ps.filter(p => p.pid === pid).map(p => {
+          return { name: p.name, pid: p.pid };
+        })[0]);
+        const list: IWindowsProcessTreeResult[] = [];
+        while (openList.length) {
+          const current = openList.shift();
+          ps.filter(p => p.ppid === current.pid).map(p => {
+            return { name: p.name, pid: p.pid };
+          }).forEach(p => openList.push(p));
+          list.push(current);
+        }
+        const success = list.length === size;
+        if (success) {
+          clearInterval(interval);
+          resolve(list);
+          return;
+        }
+        tries++;
+        if (tries * intervalMs >= timeoutMs) {
+          clearInterval(interval);
+          assert.fail(`Bad process state, expected: ${size}, actual: ${list.length}`);
+          resolve();
+        }
+      });
+    }, intervalMs);
+  });
+}
+
+if (process.platform === 'win32') {
+  describe('WindowsTerminal', () => {
+    describe('kill', () => {
+      it('should not crash parent process', (done) => {
+        const term = new WindowsTerminal('cmd.exe', [], {});
+        term.kill();
+        // Add done call to deferred function queue to ensure the kill call has completed
+        (<any>term)._defer(done);
+      });
+      it('should kill the process tree', function (done: Mocha.Done): void {
+        this.timeout(5000);
+        const term = new WindowsTerminal('cmd.exe', [], {});
+        // Start sub-processes
+        term.write('powershell.exe\r');
+        term.write('notepad.exe\r');
+        term.write('node.exe\r');
+        pollForProcessTreeSize(term.pid, 4, 500, 5000).then(list => {
+          assert.equal(list[0].name, 'cmd.exe');
+          assert.equal(list[1].name, 'powershell.exe');
+          assert.equal(list[2].name, 'notepad.exe');
+          assert.equal(list[3].name, 'node.exe');
+          term.kill();
+          const desiredState: IProcessState = {};
+          desiredState[list[0].pid] = false;
+          desiredState[list[1].pid] = false;
+          desiredState[list[2].pid] = true;
+          desiredState[list[3].pid] = false;
+          pollForProcessState(desiredState).then(() => {
+            // Kill notepad before done
+            process.kill(list[2].pid);
+            done();
+          });
+        });
+      });
+    });
+
+    describe('resize', () => {
+      it('should throw a non-native exception when resizing an invalid value', () => {
+        const term = new WindowsTerminal('cmd.exe', [], {});
+        assert.throws(() => term.resize(-1, -1));
+        assert.throws(() => term.resize(0, 0));
+        assert.doesNotThrow(() => term.resize(1, 1));
+      });
+      it('should throw an non-native exception when resizing a killed terminal', (done) => {
+        const term = new WindowsTerminal('cmd.exe', [], {});
+        (<any>term)._defer(() => {
+          term.on('exit', () => {
+            assert.throws(() => term.resize(1, 1));
+            done();
+          });
+          term.destroy();
+        });
+      });
+    });
+
+    describe('Args as CommandLine', () => {
+      it('should not fail running a file containing a space in the path', (done) => {
+        const spaceFolder = path.resolve(__dirname, '..', 'fixtures', 'space folder');
+        if (!fs.existsSync(spaceFolder)) {
+          fs.mkdirSync(spaceFolder);
+        }
+
+        const cmdCopiedPath = path.resolve(spaceFolder, 'cmd.exe');
+        const data = fs.readFileSync(`${process.env.windir}\\System32\\cmd.exe`);
+        fs.writeFileSync(cmdCopiedPath, data);
+
+        if (!fs.existsSync(cmdCopiedPath)) {
+          // Skip test if git bash isn't installed
+          return;
+        }
+        const term = new WindowsTerminal(cmdCopiedPath, '/c echo "hello world"', {});
+        let result = '';
+        term.on('data', (data) => {
+          result += data;
+        });
+        term.on('exit', () => {
+          assert.ok(result.indexOf('hello world') >= 1);
+          done();
+        });
+      });
+    });
+
+    describe('env', () => {
+      it('should set environment variables of the shell', (done) => {
+        const term = new WindowsTerminal('cmd.exe', '/C echo %FOO%', { env: { FOO: 'BAR' }});
+        let result = '';
+        term.on('data', (data) => {
+          result += data;
+        });
+        term.on('exit', () => {
+          assert.ok(result.indexOf('BAR') >= 0);
+          done();
+        });
+      });
+    });
+
+    describe('On close', () => {
+      it('should return process zero exit codes', (done) => {
+        const term = new WindowsTerminal('cmd.exe', '/C exit');
+        term.on('exit', (code) => {
+          assert.equal(code, 0);
+          done();
+        });
+      });
+
+      it('should return process non-zero exit codes', (done) => {
+        const term = new WindowsTerminal('cmd.exe', '/C exit 2');
+        term.on('exit', (code) => {
+          assert.equal(code, 2);
+          done();
+        });
+      });
+    });
+  });
+}
diff --git a/node_modules/node-pty/src/windowsTerminal.ts b/node_modules/node-pty/src/windowsTerminal.ts
new file mode 100644 (file)
index 0000000..b076288
--- /dev/null
@@ -0,0 +1,187 @@
+/**
+ * Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
+ * Copyright (c) 2016, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+import { Socket } from 'net';
+import { Terminal, DEFAULT_COLS, DEFAULT_ROWS } from './terminal';
+import { WindowsPtyAgent } from './windowsPtyAgent';
+import { IPtyOpenOptions, IWindowsPtyForkOptions } from './interfaces';
+import { ArgvOrCommandLine } from './types';
+import { assign } from './utils';
+
+const DEFAULT_FILE = 'cmd.exe';
+const DEFAULT_NAME = 'Windows Shell';
+
+export class WindowsTerminal extends Terminal {
+  private _isReady: boolean;
+  private _deferreds: any[];
+  private _agent: WindowsPtyAgent;
+
+  constructor(file?: string, args?: ArgvOrCommandLine, opt?: IWindowsPtyForkOptions) {
+    super(opt);
+
+    // Initialize arguments
+    args = args || [];
+    file = file || DEFAULT_FILE;
+    opt = opt || {};
+    opt.env = opt.env || process.env;
+
+    if (opt.encoding) {
+      console.warn('Setting encoding on Windows is not supported');
+    }
+
+    const env = assign({}, opt.env);
+    this._cols = opt.cols || DEFAULT_COLS;
+    this._rows = opt.rows || DEFAULT_ROWS;
+    const cwd = opt.cwd || process.cwd();
+    const name = opt.name || env.TERM || DEFAULT_NAME;
+    const parsedEnv = this._parseEnv(env);
+
+    // If the terminal is ready
+    this._isReady = false;
+
+    // Functions that need to run after `ready` event is emitted.
+    this._deferreds = [];
+
+    // Create new termal.
+    this._agent = new WindowsPtyAgent(file, args, parsedEnv, cwd, this._cols, this._rows, false, opt.useConpty, opt.conptyInheritCursor);
+    this._socket = this._agent.outSocket;
+
+    // Not available until `ready` event emitted.
+    this._pid = this._agent.innerPid;
+    this._fd = this._agent.fd;
+    this._pty = this._agent.pty;
+
+    // The forked windows terminal is not available until `ready` event is
+    // emitted.
+    this._socket.on('ready_datapipe', () => {
+
+      // These events needs to be forwarded.
+      ['connect', 'data', 'end', 'timeout', 'drain'].forEach(event => {
+        this._socket.on(event, () => {
+
+          // Wait until the first data event is fired then we can run deferreds.
+          if (!this._isReady && event === 'data') {
+
+            // Terminal is now ready and we can avoid having to defer method
+            // calls.
+            this._isReady = true;
+
+            // Execute all deferred methods
+            this._deferreds.forEach(fn => {
+              // NB! In order to ensure that `this` has all its references
+              // updated any variable that need to be available in `this` before
+              // the deferred is run has to be declared above this forEach
+              // statement.
+              fn.run();
+            });
+
+            // Reset
+            this._deferreds = [];
+
+          }
+        });
+      });
+
+      // Shutdown if `error` event is emitted.
+      this._socket.on('error', err => {
+        // Close terminal session.
+        this._close();
+
+        // EIO, happens when someone closes our child process: the only process
+        // in the terminal.
+        // node < 0.6.14: errno 5
+        // node >= 0.6.14: read EIO
+        if ((<any>err).code) {
+          if (~(<any>err).code.indexOf('errno 5') || ~(<any>err).code.indexOf('EIO')) return;
+        }
+
+        // Throw anything else.
+        if (this.listeners('error').length < 2) {
+          throw err;
+        }
+      });
+
+      // Cleanup after the socket is closed.
+      this._socket.on('close', () => {
+        this.emit('exit', this._agent.exitCode);
+        this._close();
+      });
+
+    });
+
+    this._file = file;
+    this._name = name;
+
+    this._readable = true;
+    this._writable = true;
+
+    this._forwardEvents();
+  }
+
+  protected _write(data: string): void {
+    this._defer(this._doWrite, data);
+  }
+
+  private _doWrite(data: string): void {
+    this._agent.inSocket.write(data);
+  }
+
+  /**
+   * openpty
+   */
+
+  public static open(options?: IPtyOpenOptions): void {
+    throw new Error('open() not supported on windows, use Fork() instead.');
+  }
+
+  /**
+   * TTY
+   */
+
+  public resize(cols: number, rows: number): void {
+    if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
+      throw new Error('resizing must be done using positive cols and rows');
+    }
+    this._defer(() => {
+      this._agent.resize(cols, rows);
+      this._cols = cols;
+      this._rows = rows;
+    });
+  }
+
+  public destroy(): void {
+    this._defer(() => {
+      this.kill();
+    });
+  }
+
+  public kill(signal?: string): void {
+    this._defer(() => {
+      if (signal) {
+        throw new Error('Signals not supported on windows.');
+      }
+      this._close();
+      this._agent.kill();
+    });
+  }
+
+  private _defer<A extends any>(deferredFn: (arg?: A) => void, arg?: A): void {
+    // If the terminal is ready, execute.
+    if (this._isReady) {
+      deferredFn.call(this, arg);
+      return;
+    }
+
+    // Queue until terminal is ready.
+    this._deferreds.push({
+      run: () => deferredFn.call(this, arg)
+    });
+  }
+
+  public get process(): string { return this._name; }
+  public get master(): Socket { throw new Error('master is not supported on Windows'); }
+  public get slave(): Socket { throw new Error('slave is not supported on Windows'); }
+}
diff --git a/node_modules/node-pty/typings/node-pty.d.ts b/node_modules/node-pty/typings/node-pty.d.ts
new file mode 100644 (file)
index 0000000..5b1e0e4
--- /dev/null
@@ -0,0 +1,202 @@
+/**
+ * Copyright (c) 2017, Daniel Imms (MIT License).
+ * Copyright (c) 2018, Microsoft Corporation (MIT License).
+ */
+
+declare module 'node-pty' {
+  /**
+   * Forks a process as a pseudoterminal.
+   * @param file The file to launch.
+   * @param args The file's arguments as argv (string[]) or in a pre-escaped CommandLine format
+   * (string). Note that the CommandLine option is only available on Windows and is expected to be
+   * escaped properly.
+   * @param options The options of the terminal.
+   * @see CommandLineToArgvW https://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
+   * @see Parsing C++ Comamnd-Line Arguments https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
+   * @see GetCommandLine https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156.aspx
+   */
+  export function spawn(file: string, args: string[] | string, options: IPtyForkOptions | IWindowsPtyForkOptions): IPty;
+
+  export interface IBasePtyForkOptions {
+
+    /**
+     * Name of the terminal to be set in environment ($TERM variable).
+     */
+    name?: string;
+
+    /**
+     * Number of intial cols of the pty.
+     */
+    cols?: number;
+
+    /**
+     * Number of initial rows of the pty.
+     */
+    rows?: number;
+
+    /**
+     * Working directory to be set for the slave program.
+     */
+    cwd?: string;
+
+    /**
+     * Environment to be set for the slave program.
+     */
+    env?: { [key: string]: string };
+
+    /**
+     * String encoding of the underlying pty.
+     * If set, incoming data will be decoded to strings and outgoing strings to bytes applying this encoding.
+     * If unset, incoming data will be delivered as raw bytes (Buffer type).
+     * By default 'utf8' is assumed, to unset it explicitly set it to `null`.
+     */
+    encoding?: string | null;
+
+    /**
+     * (EXPERIMENTAL)
+     * Whether to enable flow control handling (false by default). If enabled a message of `flowControlPause`
+     * will pause the socket and thus blocking the slave program execution due to buffer back pressure.
+     * A message of `flowControlResume` will resume the socket into flow mode.
+     * For performance reasons only a single message as a whole will match (no message part matching).
+     * If flow control is enabled the `flowControlPause` and `flowControlResume` messages are not forwarded to
+     * the underlying pseudoterminal.
+     */
+    handleFlowControl?: boolean;
+
+    /**
+     * (EXPERIMENTAL)
+     * The string that should pause the pty when `handleFlowControl` is true. Default is XOFF ('\x13').
+     */
+    flowControlPause?: string;
+
+    /**
+     * (EXPERIMENTAL)
+     * The string that should resume the pty when `handleFlowControl` is true. Default is XON ('\x11').
+     */
+    flowControlResume?: string;
+  }
+
+  export interface IPtyForkOptions extends IBasePtyForkOptions {
+    /**
+     * Security warning: use this option with great caution, as opened file descriptors
+     * with higher privileges might leak to the slave program.
+     */
+    uid?: number;
+    gid?: number;
+  }
+
+  export interface IWindowsPtyForkOptions extends IBasePtyForkOptions {
+    /**
+     * Whether to use the ConPTY system on Windows. When this is not set, ConPTY will be used when
+     * the Windows build number is >= 18309 (instead of winpty). Note that ConPTY is available from
+     * build 17134 but is too unstable to enable by default.
+     *
+     * This setting does nothing on non-Windows.
+     */
+    useConpty?: boolean;
+
+    /**
+     * Whether to use PSEUDOCONSOLE_INHERIT_CURSOR in conpty.
+     * @see https://docs.microsoft.com/en-us/windows/console/createpseudoconsole
+     */
+    conptyInheritCursor?: boolean;
+  }
+
+  /**
+   * An interface representing a pseudoterminal, on Windows this is emulated via the winpty library.
+   */
+  export interface IPty {
+    /**
+     * The process ID of the outer process.
+     */
+    readonly pid: number;
+
+    /**
+     * The column size in characters.
+     */
+    readonly cols: number;
+
+    /**
+     * The row size in characters.
+     */
+    readonly rows: number;
+
+    /**
+     * The title of the active process.
+     */
+    readonly process: string;
+
+    /**
+     * (EXPERIMENTAL)
+     * Whether to handle flow control. Useful to disable/re-enable flow control during runtime.
+     * Use this for binary data that is likely to contain the `flowControlPause` string by accident.
+     */
+    handleFlowControl: boolean;
+
+    /**
+     * Adds an event listener for when a data event fires. This happens when data is returned from
+     * the pty.
+     * @returns an `IDisposable` to stop listening.
+     */
+    readonly onData: IEvent<string>;
+
+    /**
+     * Adds an event listener for when an exit event fires. This happens when the pty exits.
+     * @returns an `IDisposable` to stop listening.
+     */
+    readonly onExit: IEvent<{ exitCode: number, signal?: number }>;
+
+    /**
+     * Adds a listener to the data event, fired when data is returned from the pty.
+     * @param event The name of the event.
+     * @param listener The callback function.
+     * @deprecated Use IPty.onData
+     */
+    on(event: 'data', listener: (data: string) => void): void;
+
+    /**
+     * Adds a listener to the exit event, fired when the pty exits.
+     * @param event The name of the event.
+     * @param listener The callback function, exitCode is the exit code of the process and signal is
+     * the signal that triggered the exit. signal is not supported on Windows.
+     * @deprecated Use IPty.onExit
+     */
+    on(event: 'exit', listener: (exitCode: number, signal?: number) => void): void;
+
+    /**
+     * Resizes the dimensions of the pty.
+     * @param columns THe number of columns to use.
+     * @param rows The number of rows to use.
+     */
+    resize(columns: number, rows: number): void;
+
+    /**
+     * Writes data to the pty.
+     * @param data The data to write.
+     */
+    write(data: string): void;
+
+    /**
+     * Kills the pty.
+     * @param signal The signal to use, defaults to SIGHUP. This parameter is not supported on
+     * Windows.
+     * @throws Will throw when signal is used on Windows.
+     */
+    kill(signal?: string): void;
+  }
+
+  /**
+   * An object that can be disposed via a dispose function.
+   */
+  export interface IDisposable {
+    dispose(): void;
+  }
+
+  /**
+   * An event that can be listened to.
+   * @returns an `IDisposable` to stop listening.
+   */
+  export interface IEvent<T> {
+    (listener: (e: T) => any): IDisposable;
+  }
+}
diff --git a/node_modules/xterm/LICENSE b/node_modules/xterm/LICENSE
new file mode 100644 (file)
index 0000000..4472336
--- /dev/null
@@ -0,0 +1,21 @@
+Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
+Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/node_modules/xterm/README.md b/node_modules/xterm/README.md
new file mode 100644 (file)
index 0000000..5cf2848
--- /dev/null
@@ -0,0 +1,190 @@
+# [![xterm.js logo](logo-full.png)](https://xtermjs.org)
+
+[![Build Status](https://dev.azure.com/xtermjs/xterm.js/_apis/build/status/xtermjs.xterm.js)](https://dev.azure.com/xtermjs/xterm.js/_build/latest?definitionId=3)
+
+Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia.
+
+## Features
+
+- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim` and `tmux`, this includes support for curses-based apps and mouse event support.
+- **Performant**: Xterm.js is *really* fast, it even includes a GPU-accelerated renderer.
+- **Rich unicode support**: Supports CJK, emojis and IMEs.
+- **Self-contained**: Requires zero dependencies to work.
+- **Accessible**: Screen reader support can be turned on using the `screenReaderMode` option.
+- **And much more**: Links, theming, addons, well documented API, etc.
+
+## What xterm.js is not
+
+- Xterm.js is not a terminal application that you can download and use on your computer.
+- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output).
+
+## Getting Started
+
+First you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/) so you need that installed and then add xterm.js as a dependency by running:
+
+```
+npm install xterm
+```
+
+To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your html page. Then create a `<div id="terminal"></div>` onto which xterm can attach itself. Finally instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
+
+```html
+<!doctype html>
+  <html>
+    <head>
+      <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
+      <script src="node_modules/xterm/lib/xterm.js"></script>
+    </head>
+    <body>
+      <div id="terminal"></div>
+      <script>
+        var term = new Terminal();
+        term.open(document.getElementById('terminal'));
+        term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
+      </script>
+    </body>
+  </html>
+```
+
+### Importing
+
+The recommended way to load xterm.js is via the ES6 module syntax:
+
+```javascript
+import { Terminal } from 'xterm';
+```
+
+### Addons
+
+⚠️ *This section describes the new addon format introduced in v3.14.0, see [here](https://github.com/xtermjs/xterm.js/blob/3.14.2/README.md#addons) for the instructions on the old format*
+
+Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon you first need to install it in your project:
+
+```bash
+npm i -S xterm-addon-web-links
+```
+
+Then import the addon, instantiate it and call `Terminal.loadAddon`:
+
+```ts
+import { Terminal } from 'xterm';
+import { WebLinksAddon } from 'xterm-addon-web-links';
+
+const terminal = new Terminal();
+// Load WebLinksAddon on terminal, this is all that's needed to get web links
+// working in the terminal.
+terminal.loadAddon(new WebLinksAddon());
+```
+
+The xterm.js team maintains the following addons but they can be built by anyone:
+
+- [`xterm-addon-attach`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-attach): Attaches to a server running a process via a websocket
+- [`xterm-addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-fit): Fits the terminal to the containing element
+- [`xterm-addon-search`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-search): Adds search functionality
+- [`xterm-addon-web-links`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-web-links): Adds web link detection and interaction
+
+## Browser Support
+
+Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox* and *Safari*.
+
+We also partially support *Intenet Explorer 11*, meaning xterm.js should work for the most part, but we reserve the right to not provide workarounds specifically for it unless it's absolutely necessary to get the basic input/output flow working.
+
+Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers, these are the versions we strive to keep working.
+
+## API
+
+The full API for xterm.js is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API.
+
+Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions so be sure to read release notes if you plan on using experimental APIs.
+
+## Real-world uses
+Xterm.js is used in several world-class applications to provide great terminal experiences.
+
+- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js.
+- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile and powerful open source code editor that provides an integrated terminal based on xterm.js.
+- [**ttyd**](https://github.com/tsl0922/ttyd): A command-line tool for sharing terminal over the web, with fully-featured terminal emulation based on xterm.js.
+- [**Katacoda**](https://www.katacoda.com/): Katacoda is an Interactive Learning Platform for software developers, covering the latest Cloud Native technologies.
+- [**Eclipse Che**](http://www.eclipse.org/che): Developer workspace server, cloud IDE, and Eclipse next-generation IDE.
+- [**Codenvy**](http://www.codenvy.com): Cloud workspaces for development teams.
+- [**CoderPad**](https://coderpad.io): Online interviewing platform for programmers. Run code in many programming languages, with results displayed by xterm.js.
+- [**WebSSH2**](https://github.com/billchurch/WebSSH2): A web based SSH2 client using xterm.js, socket.io, and ssh2.
+- [**Spyder Terminal**](https://github.com/spyder-ide/spyder-terminal): A full fledged system terminal embedded on Spyder IDE.
+- [**Cloud Commander**](https://cloudcmd.io "Cloud Commander"): Orthodox web file manager with console and editor.
+- [**Codevolve**](https://www.codevolve.com "Codevolve"): Online platform for interactive coding and web development courses. Live container-backed terminal uses xterm.js.
+- [**RStudio**](https://www.rstudio.com/products/RStudio "RStudio"): RStudio is an integrated development environment (IDE) for R.
+- [**Terminal for Atom**](https://github.com/jsmecham/atom-terminal-tab): A simple terminal for the Atom text editor.
+- [**Eclipse Orion**](https://orionhub.org): A modern, open source software development environment that runs in the cloud. Code, deploy and run in the cloud.
+- [**Gravitational Teleport**](https://github.com/gravitational/teleport): Gravitational Teleport is a modern SSH server for remotely accessing clusters of Linux servers via SSH or HTTPS.
+- [**Hexlet**](https://en.hexlet.io): Practical programming courses (JavaScript, PHP, Unix, databases, functional programming). A steady path from the first line of code to the first job.
+- [**Selenoid UI**](https://github.com/aerokube/selenoid-ui): Simple UI for the scallable golang implementation of Selenium Hub named Selenoid. We use XTerm for streaming logs over websockets from docker containers.
+- [**Portainer**](https://portainer.io): Simple management UI for Docker.
+- [**SSHy**](https://github.com/stuicey/SSHy): HTML5 Based SSHv2 Web Client with E2E encryption utilising xterm.js, SJCL & websockets.
+- [**JupyterLab**](https://github.com/jupyterlab/jupyterlab): An extensible computational environment for Jupyter, supporting interactive data science and scientific computing across all programming languages.
+- [**Theia**](https://github.com/theia-ide/theia): Theia is a cloud & desktop IDE framework implemented in TypeScript.
+- [**Opshell**](https://github.com/ricktbaker/opshell) Ops Helper tool to make life easier working with AWS instances across multiple organizations.
+- [**Proxmox VE**](https://www.proxmox.com/en/proxmox-ve): Proxmox VE is a complete open-source platform for enterprise virtualization. It uses xterm.js for container terminals and the host shell.
+- [**Script Runner**](https://github.com/ioquatix/script-runner): Run scripts (or a shell) in Atom.
+- [**Whack Whack Terminal**](https://github.com/Microsoft/WhackWhackTerminal): Terminal emulator for Visual Studio 2017.
+- [**VTerm**](https://github.com/vterm/vterm): Extensible terminal emulator based on Electron and React.
+- [**electerm**](http://electerm.html5beta.com): electerm is a terminal/ssh/sftp client(mac, win, linux) based on electron/node-pty/xterm.
+- [**Kubebox**](https://github.com/astefanutti/kubebox): Terminal console for Kubernetes clusters.
+- [**Azure Cloud Shell**](https://shell.azure.com): Azure Cloud Shell is a Microsoft-managed admin machine built on Azure, for Azure.
+- [**atom-xterm**](https://atom.io/packages/atom-xterm): Atom plugin for providing terminals inside your Atom workspace.
+- [**rtty**](https://github.com/zhaojh329/rtty): Access your terminals from anywhere via the web.
+- [**Pisth**](https://github.com/ColdGrub1384/Pisth): An SFTP and SSH client for iOS.
+- [**abstruse**](https://github.com/bleenco/abstruse): Abstruse CI is a continuous integration platform based on Node.JS and Docker.
+- [**Azure Data Studio**](https://github.com/Microsoft/azuredatastudio): A data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.
+- [**FreeMAN**](https://github.com/matthew-matvei/freeman): A free, cross-platform file manager for power users.
+- [**Fluent Terminal**](https://github.com/felixse/FluentTerminal): A terminal emulator based on UWP and web technologies.
+- [**Hyper**](https://hyper.is): A terminal built on web technologies.
+- [**Diag**](https://diag.ai): A better way to troubleshoot problems faster. Capture, share and reapply troubleshooting knowledge so you can focus on solving problems that matter.
+- [**GoTTY**](https://github.com/yudai/gotty): A simple command line tool that shares your terminal as a web application based on xterm.js.
+- [**genact**](https://github.com/svenstaro/genact): A nonsense activity generator.
+- [**cPanel & WHM**](https://cpanel.com): The hosting platform of choice.
+- [**Nutanix**](https://github.com/nutanix): Nutanix Enterprise Cloud uses xterm in the webssh functionality within Nutanix Calm, and is also looking to move our old noserial (termjs) functionality to xterm.js.
+- [**SSH Web Client**](https://github.com/roke22/PHP-SSH2-Web-Client): SSH Web Client with PHP.
+- [**Shellvault**](https://www.shellvault.io): The cloud-based SSH terminal you can access from anywhere.
+- [**Juno**](http://junolab.org/): A flexible Julia IDE, based on Atom.
+- [**webssh**](https://github.com/huashengdun/webssh): Web based ssh client.
+- [**info-beamer hosted**](https://info-beamer.com): Uses xterm.js to manage digital signage devices from the web dashboard.
+- [**Jumpserver**](https://github.com/jumpserver/luna): Jumpserver Luna project, Jumpserver is a bastion server project, Luna use xterm.js for web terminal emulation.
+- [**LxdMosaic**](https://github.com/turtle0x1/LxdMosaic): Uses xterm.js to give terminal access to containers through LXD
+- [**CodeInterview.io**](https://codeinterview.io): A coding interview platform in 25+ languages and many web frameworks. Uses xterm.js to provide shell access.
+- [**Bastillion**](https://www.bastillion.io): Bastillion is an open-source web-based SSH console that centrally manages administrative access to systems.
+- [**PHP App Server**](https://github.com/cubiclesoft/php-app-server/): Create lightweight, installable almost-native applications for desktop OSes.  ExecTerminal (nicely wraps the xterm.js Terminal), TerminalManager, and RunProcessSDK are self-contained, reusable ES5+ compliant Javascript components.
+- [**NgTerminal**](https://github.com/qwefgh90/ng-terminal): NgTerminal is a web terminal that leverages xterm.js on Angular 7+. You can easily add it into your application by adding `<ng-terminal></ng-terminal>` into your component.
+- [**tty-share**](https://tty-share.com): Extremely simple terminal sharing over the Internet.
+- [**Ten Hands**](https://github.com/saisandeepvaddi/ten-hands): One place to run your command-line tasks.
+- [**WebAssembly.sh**](https://webassembly.sh): A WebAssembly WASI browser terminal
+
+[And much more...](https://github.com/xtermjs/xterm.js/network/dependents)
+
+Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it in our list. Note: Please add any new contributions to the end of the list only.
+
+## Releases
+
+Xterm.js follows a monthly release cycle roughly.
+
+All current and past releases are available on this repo's [Releases page](https://github.com/sourcelair/xterm.js/releases), you can view the [high-level roadmap on the wiki](https://github.com/xtermjs/xterm.js/wiki/Roadmap) and see what we're working on now by looking through [Milestones](https://github.com/sourcelair/xterm.js/milestones).
+
+### Beta builds
+
+Our CI releases beta builds to npm for every change that goes into master, install the latest beta build with:
+
+```
+npm install -S xterm@beta
+```
+
+These should generally be stable but some bugs may slip in, we recommend using the beta build primarily to test out new features and for verifying bug fixes.
+
+## Contributing
+
+You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and setup xterm.js for development.
+
+## License Agreement
+
+If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work.
+
+Copyright (c) 2017-2019, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)<br>
+Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)<br>
+Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
diff --git a/node_modules/xterm/css/xterm.css b/node_modules/xterm/css/xterm.css
new file mode 100644 (file)
index 0000000..b3d8d4f
--- /dev/null
@@ -0,0 +1,171 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * https://github.com/chjj/term.js
+ * @license MIT
+ *
+ * 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.
+ *
+ * Originally forked from (with the author's permission):
+ *   Fabrice Bellard's javascript vt100 for jslinux:
+ *   http://bellard.org/jslinux/
+ *   Copyright (c) 2011 Fabrice Bellard
+ *   The original design remains. The terminal itself
+ *   has been extended to include xterm CSI codes, among
+ *   other features.
+ */
+
+/**
+ *  Default styles for xterm.js
+ */
+
+.xterm {
+    font-feature-settings: "liga" 0;
+    position: relative;
+    user-select: none;
+    -ms-user-select: none;
+    -webkit-user-select: none;
+}
+
+.xterm.focus,
+.xterm:focus {
+    outline: none;
+}
+
+.xterm .xterm-helpers {
+    position: absolute;
+    top: 0;
+    /**
+     * The z-index of the helpers must be higher than the canvases in order for
+     * IMEs to appear on top.
+     */
+    z-index: 5;
+}
+
+.xterm .xterm-helper-textarea {
+    /*
+     * HACK: to fix IE's blinking cursor
+     * Move textarea out of the screen to the far left, so that the cursor is not visible.
+     */
+    position: absolute;
+    opacity: 0;
+    left: -9999em;
+    top: 0;
+    width: 0;
+    height: 0;
+    z-index: -5;
+    /** Prevent wrapping so the IME appears against the textarea at the correct position */
+    white-space: nowrap;
+    overflow: hidden;
+    resize: none;
+}
+
+.xterm .composition-view {
+    /* TODO: Composition position got messed up somewhere */
+    background: #000;
+    color: #FFF;
+    display: none;
+    position: absolute;
+    white-space: nowrap;
+    z-index: 1;
+}
+
+.xterm .composition-view.active {
+    display: block;
+}
+
+.xterm .xterm-viewport {
+    /* On OS X this is required in order for the scroll bar to appear fully opaque */
+    background-color: #000;
+    overflow-y: scroll;
+    cursor: default;
+    position: absolute;
+    right: 0;
+    left: 0;
+    top: 0;
+    bottom: 0;
+}
+
+.xterm .xterm-screen {
+    position: relative;
+}
+
+.xterm .xterm-screen canvas {
+    position: absolute;
+    left: 0;
+    top: 0;
+}
+
+.xterm .xterm-scroll-area {
+    visibility: hidden;
+}
+
+.xterm-char-measure-element {
+    display: inline-block;
+    visibility: hidden;
+    position: absolute;
+    top: 0;
+    left: -9999em;
+    line-height: normal;
+}
+
+.xterm {
+    cursor: text;
+}
+
+.xterm.enable-mouse-events {
+    /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
+    cursor: default;
+}
+
+.xterm.xterm-cursor-pointer {
+    cursor: pointer;
+}
+
+.xterm.column-select.focus {
+    /* Column selection mode */
+    cursor: crosshair;
+}
+
+.xterm .xterm-accessibility,
+.xterm .xterm-message {
+    position: absolute;
+    left: 0;
+    top: 0;
+    bottom: 0;
+    right: 0;
+    z-index: 10;
+    color: transparent;
+}
+
+.xterm .live-region {
+    position: absolute;
+    left: -9999px;
+    width: 1px;
+    height: 1px;
+    overflow: hidden;
+}
+
+.xterm-dim {
+    opacity: 0.5;
+}
+
+.xterm-underline {
+    text-decoration: underline;
+}
diff --git a/node_modules/xterm/lib/xterm.js b/node_modules/xterm/lib/xterm.js
new file mode 100644 (file)
index 0000000..7ee6ebc
--- /dev/null
@@ -0,0 +1,2 @@
+!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(window,function(){return function(e){var t={};function i(r){if(t[r])return t[r].exports;var n=t[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=e,i.c=t,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(r,n,function(t){return e[t]}.bind(null,n));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=32)}([function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(13);t.IBufferService=r.createDecorator("BufferService"),t.ICoreMouseService=r.createDecorator("CoreMouseService"),t.ICoreService=r.createDecorator("CoreService"),t.IDirtyRowService=r.createDecorator("DirtyRowService"),t.IInstantiationService=r.createDecorator("InstantiationService"),t.ILogService=r.createDecorator("LogService"),t.IOptionsService=r.createDecorator("OptionsService")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._listeners=[]}return Object.defineProperty(e.prototype,"event",{get:function(){var e=this;return this._event||(this._event=function(t){return e._listeners.push(t),{dispose:function(){for(var i=0;i<e._listeners.length;i++)if(e._listeners[i]===t)return void e._listeners.splice(i,1)}}}),this._event},enumerable:!0,configurable:!0}),e.prototype.fire=function(e){for(var t=[],i=0;i<this._listeners.length;i++)t.push(this._listeners[i]);for(i=0;i<t.length;i++)t[i].call(void 0,e)},e}();t.EventEmitter=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._disposables=[],this._isDisposed=!1}return e.prototype.dispose=function(){this._isDisposed=!0,this._disposables.forEach(function(e){return e.dispose()}),this._disposables.length=0},e.prototype.register=function(e){this._disposables.push(e)},e.prototype.unregister=function(e){var t=this._disposables.indexOf(e);-1!==t&&this._disposables.splice(t,1)},e}();t.Disposable=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_COLOR=256,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(8),o=i(3),a=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.content=0,t.fg=0,t.bg=0,t.combinedData="",t}return n(t,e),t.fromCharData=function(e){var i=new t;return i.setFromCharData(e),i},t.prototype.isCombined=function(){return 2097152&this.content},t.prototype.getWidth=function(){return this.content>>22},t.prototype.getChars=function(){return 2097152&this.content?this.combinedData:2097151&this.content?s.stringFromCodePoint(2097151&this.content):""},t.prototype.getCode=function(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content},t.prototype.setFromCharData=function(e){this.fg=e[o.CHAR_DATA_ATTR_INDEX],this.bg=0;var t=!1;if(e[o.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(2===e[o.CHAR_DATA_CHAR_INDEX].length){var i=e[o.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){var r=e[o.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(i-55296)+r-56320+65536|e[o.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[o.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[o.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[o.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[o.CHAR_DATA_WIDTH_INDEX]<<22)},t.prototype.getAsCharData=function(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]},t}(i(6).AttributeData);t.CellData=a},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(13);t.ICharSizeService=r.createDecorator("CharSizeService"),t.IMouseService=r.createDecorator("MouseService"),t.IRenderService=r.createDecorator("RenderService"),t.ISelectionService=r.createDecorator("SelectionService"),t.ISoundService=r.createDecorator("SoundService")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.fg=0,this.bg=0}return e.toColorRGB=function(e){return[e>>>16&255,e>>>8&255,255&e]},e.fromColorRGB=function(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]},e.prototype.clone=function(){var t=new e;return t.fg=this.fg,t.bg=this.bg,t},e.prototype.isInverse=function(){return 67108864&this.fg},e.prototype.isBold=function(){return 134217728&this.fg},e.prototype.isUnderline=function(){return 268435456&this.fg},e.prototype.isBlink=function(){return 536870912&this.fg},e.prototype.isInvisible=function(){return 1073741824&this.fg},e.prototype.isItalic=function(){return 67108864&this.bg},e.prototype.isDim=function(){return 134217728&this.bg},e.prototype.getFgColorMode=function(){return 50331648&this.fg},e.prototype.getBgColorMode=function(){return 50331648&this.bg},e.prototype.isFgRGB=function(){return 50331648==(50331648&this.fg)},e.prototype.isBgRGB=function(){return 50331648==(50331648&this.bg)},e.prototype.isFgPalette=function(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)},e.prototype.isBgPalette=function(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)},e.prototype.isFgDefault=function(){return 0==(50331648&this.fg)},e.prototype.isBgDefault=function(){return 0==(50331648&this.bg)},e.prototype.getFgColor=function(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}},e.prototype.getBgColor=function(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}},e}();t.AttributeData=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDisposableDomListener=function(e,t,i,r){return e.addEventListener(t,i,r),{dispose:function(){i&&e.removeEventListener(t,i,r)}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=e.length);for(var r="",n=t;n<i;++n){var s=e[n];s>65535?(s-=65536,r+=String.fromCharCode(55296+(s>>10))+String.fromCharCode(s%1024+56320)):r+=String.fromCharCode(s)}return r};var r=function(){function e(){this._interim=0}return e.prototype.clear=function(){this._interim=0},e.prototype.decode=function(e,t){var i=e.length;if(!i)return 0;var r=0,n=0;this._interim&&(56320<=(a=e.charCodeAt(n++))&&a<=57343?t[r++]=1024*(this._interim-55296)+a-56320+65536:(t[r++]=this._interim,t[r++]=a),this._interim=0);for(var s=n;s<i;++s){var o=e.charCodeAt(s);if(55296<=o&&o<=56319){if(++s>=i)return this._interim=o,r;var a;56320<=(a=e.charCodeAt(s))&&a<=57343?t[r++]=1024*(o-55296)+a-56320+65536:(t[r++]=o,t[r++]=a)}else t[r++]=o}return r},e}();t.StringToUtf32=r;var n=function(){function e(){this.interim=new Uint8Array(3)}return e.prototype.clear=function(){this.interim.fill(0)},e.prototype.decode=function(e,t){var i=e.length;if(!i)return 0;var r,n,s,o,a=0,c=0,l=0;if(this.interim[0]){var h=!1,u=this.interim[0];u&=192==(224&u)?31:224==(240&u)?15:7;for(var f=0,_=void 0;(_=63&this.interim[++f])&&f<4;)u<<=6,u|=_;for(var d=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,p=d-f;l<p;){if(l>=i)return 0;if(128!=(192&(_=e[l++]))){l--,h=!0;break}this.interim[f++]=_,u<<=6,u|=63&_}h||(2===d?u<128?l--:t[a++]=u:3===d?u<2048||u>=55296&&u<=57343||(t[a++]=u):u<65536||u>1114111||(t[a++]=u)),this.interim.fill(0)}for(var v=i-4,g=l;g<i;){for(;!(!(g<v)||128&(r=e[g])||128&(n=e[g+1])||128&(s=e[g+2])||128&(o=e[g+3]));)t[a++]=r,t[a++]=n,t[a++]=s,t[a++]=o,g+=4;if((r=e[g++])<128)t[a++]=r;else if(192==(224&r)){if(g>=i)return this.interim[0]=r,a;if(128!=(192&(n=e[g++]))){g--;continue}if((c=(31&r)<<6|63&n)<128){g--;continue}t[a++]=c}else if(224==(240&r)){if(g>=i)return this.interim[0]=r,a;if(128!=(192&(n=e[g++]))){g--;continue}if(g>=i)return this.interim[0]=r,this.interim[1]=n,a;if(128!=(192&(s=e[g++]))){g--;continue}if((c=(15&r)<<12|(63&n)<<6|63&s)<2048||c>=55296&&c<=57343)continue;t[a++]=c}else if(240==(248&r)){if(g>=i)return this.interim[0]=r,a;if(128!=(192&(n=e[g++]))){g--;continue}if(g>=i)return this.interim[0]=r,this.interim[1]=n,a;if(128!=(192&(s=e[g++]))){g--;continue}if(g>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=s,a;if(128!=(192&(o=e[g++]))){g--;continue}if((c=(7&r)<<18|(63&n)<<12|(63&s)<<6|63&o)<65536||c>1114111)continue;t[a++]=c}}return a},e}();t.Utf8ToUtf32=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.INVERTED_DEFAULT_COLOR=257,t.DIM_OPACITY=.5,t.CHAR_ATLAS_CELL_SPACING=1},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="undefined"==typeof navigator,n=r?"node":navigator.userAgent,s=r?"node":navigator.platform;function o(e,t){return e.indexOf(t)>=0}t.isFirefox=!!~n.indexOf("Firefox"),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.isMac=o(["Macintosh","MacIntel","MacPPC","Mac68K"],s),t.isIpad="iPad"===s,t.isIphone="iPhone"===s,t.isWindows=o(["Windows","Win16","Win32","WinCE"],s),t.isLinux=s.indexOf("Linux")>=0},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.NUL="\0",e.SOH="\ 1",e.STX="\ 2",e.ETX="\ 3",e.EOT="\ 4",e.ENQ="\ 5",e.ACK="\ 6",e.BEL="\a",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="\ e",e.SI="\ f",e.DLE="\10",e.DC1="\11",e.DC2="\12",e.DC3="\13",e.DC4="\14",e.NAK="\15",e.SYN="\16",e.ETB="\17",e.CAN="\18",e.EM="\19",e.SUB="\1a",e.ESC="\e",e.FS="\1c",e.GS="\1d",e.RS="\1e",e.US="\1f",e.SP=" ",e.DEL="\7f"}(t.C0||(t.C0={})),function(e){e.PAD="\80",e.HOP="\81",e.BPH="\82",e.NBH="\83",e.IND="\84",e.NEL="\85",e.SSA="\86",e.ESA="\87",e.HTS="\88",e.HTJ="\89",e.VTS="\8a",e.PLD="\8b",e.PLU="\8c",e.RI="\8d",e.SS2="\8e",e.SS3="\8f",e.DCS="\90",e.PU1="\91",e.PU2="\92",e.STS="\93",e.CCH="\94",e.MW="\95",e.SPA="\96",e.EPA="\97",e.SOS="\98",e.SGCI="\99",e.SCI="\9a",e.CSI="\9b",e.ST="\9c",e.OSC="\9d",e.PM="\9e",e.APC="\9f"}(t.C1||(t.C1={}))},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(3),n=i(9),s=i(23),o=i(6),a=i(26),c=function(){function e(e,t,i,r,n,s,o,a){this._container=e,this._alpha=r,this._colors=n,this._rendererId=s,this._bufferService=o,this._optionsService=a,this._scaledCharWidth=0,this._scaledCharHeight=0,this._scaledCellWidth=0,this._scaledCellHeight=0,this._scaledCharLeft=0,this._scaledCharTop=0,this._currentGlyphIdentifier={chars:"",code:0,bg:0,fg:0,bold:!1,dim:!1,italic:!1},this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-"+t+"-layer"),this._canvas.style.zIndex=i.toString(),this._initCanvas(),this._container.appendChild(this._canvas)}return e.prototype.dispose=function(){this._container.removeChild(this._canvas),this._charAtlas&&this._charAtlas.dispose()},e.prototype._initCanvas=function(){this._ctx=a.throwIfFalsy(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()},e.prototype.onOptionsChanged=function(){},e.prototype.onBlur=function(){},e.prototype.onFocus=function(){},e.prototype.onCursorMove=function(){},e.prototype.onGridChanged=function(e,t){},e.prototype.onSelectionChanged=function(e,t,i){void 0===i&&(i=!1)},e.prototype.setColors=function(e){this._refreshCharAtlas(e)},e.prototype._setTransparency=function(e){if(e!==this._alpha){var t=this._canvas;this._alpha=e,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,t),this._refreshCharAtlas(this._colors),this.onGridChanged(0,this._bufferService.rows-1)}},e.prototype._refreshCharAtlas=function(e){this._scaledCharWidth<=0&&this._scaledCharHeight<=0||(this._charAtlas=s.acquireCharAtlas(this._optionsService.options,this._rendererId,e,this._scaledCharWidth,this._scaledCharHeight),this._charAtlas.warmUp())},e.prototype.resize=function(e){this._scaledCellWidth=e.scaledCellWidth,this._scaledCellHeight=e.scaledCellHeight,this._scaledCharWidth=e.scaledCharWidth,this._scaledCharHeight=e.scaledCharHeight,this._scaledCharLeft=e.scaledCharLeft,this._scaledCharTop=e.scaledCharTop,this._canvas.width=e.scaledCanvasWidth,this._canvas.height=e.scaledCanvasHeight,this._canvas.style.width=e.canvasWidth+"px",this._canvas.style.height=e.canvasHeight+"px",this._alpha||this._clearAll(),this._refreshCharAtlas(this._colors)},e.prototype._fillCells=function(e,t,i,r){this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,i*this._scaledCellWidth,r*this._scaledCellHeight)},e.prototype._fillBottomLineAtCells=function(e,t,i){void 0===i&&(i=1),this._ctx.fillRect(e*this._scaledCellWidth,(t+1)*this._scaledCellHeight-window.devicePixelRatio-1,i*this._scaledCellWidth,window.devicePixelRatio)},e.prototype._fillLeftLineAtCell=function(e,t){this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,window.devicePixelRatio,this._scaledCellHeight)},e.prototype._strokeRectAtCell=function(e,t,i,r){this._ctx.lineWidth=window.devicePixelRatio,this._ctx.strokeRect(e*this._scaledCellWidth+window.devicePixelRatio/2,t*this._scaledCellHeight+window.devicePixelRatio/2,i*this._scaledCellWidth-window.devicePixelRatio,r*this._scaledCellHeight-window.devicePixelRatio)},e.prototype._clearAll=function(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))},e.prototype._clearCells=function(e,t,i,r){this._alpha?this._ctx.clearRect(e*this._scaledCellWidth,t*this._scaledCellHeight,i*this._scaledCellWidth,r*this._scaledCellHeight):(this._ctx.fillStyle=this._colors.background.css,this._ctx.fillRect(e*this._scaledCellWidth,t*this._scaledCellHeight,i*this._scaledCellWidth,r*this._scaledCellHeight))},e.prototype._fillCharTrueColor=function(e,t,i){this._ctx.font=this._getFont(!1,!1),this._ctx.textBaseline="middle",this._clipRow(i),this._ctx.fillText(e.getChars(),t*this._scaledCellWidth+this._scaledCharLeft,i*this._scaledCellHeight+this._scaledCharTop+this._scaledCharHeight/2)},e.prototype._drawChars=function(e,t,i){var s,o;e.isFgRGB()||e.isBgRGB()?this._drawUncachedChars(e,t,i):(e.isInverse()?(s=e.isBgDefault()?n.INVERTED_DEFAULT_COLOR:e.getBgColor(),o=e.isFgDefault()?n.INVERTED_DEFAULT_COLOR:e.getFgColor()):(o=e.isBgDefault()?r.DEFAULT_COLOR:e.getBgColor(),s=e.isFgDefault()?r.DEFAULT_COLOR:e.getFgColor()),s+=this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&s<8&&s!==n.INVERTED_DEFAULT_COLOR?8:0,this._currentGlyphIdentifier.chars=e.getChars()||r.WHITESPACE_CELL_CHAR,this._currentGlyphIdentifier.code=e.getCode()||r.WHITESPACE_CELL_CODE,this._currentGlyphIdentifier.bg=o,this._currentGlyphIdentifier.fg=s,this._currentGlyphIdentifier.bold=!!e.isBold(),this._currentGlyphIdentifier.dim=!!e.isDim(),this._currentGlyphIdentifier.italic=!!e.isItalic(),this._charAtlas&&this._charAtlas.draw(this._ctx,this._currentGlyphIdentifier,t*this._scaledCellWidth+this._scaledCharLeft,i*this._scaledCellHeight+this._scaledCharTop)||this._drawUncachedChars(e,t,i))},e.prototype._drawUncachedChars=function(e,t,i){if(this._ctx.save(),this._ctx.font=this._getFont(!!e.isBold(),!!e.isItalic()),this._ctx.textBaseline="middle",e.isInverse())e.isBgDefault()?this._ctx.fillStyle=this._colors.background.css:e.isBgRGB()?this._ctx.fillStyle="rgb("+o.AttributeData.toColorRGB(e.getBgColor()).join(",")+")":this._ctx.fillStyle=this._colors.ansi[e.getBgColor()].css;else if(e.isFgDefault())this._ctx.fillStyle=this._colors.foreground.css;else if(e.isFgRGB())this._ctx.fillStyle="rgb("+o.AttributeData.toColorRGB(e.getFgColor()).join(",")+")";else{var r=e.getFgColor();this._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&r<8&&(r+=8),this._ctx.fillStyle=this._colors.ansi[r].css}this._clipRow(i),e.isDim()&&(this._ctx.globalAlpha=n.DIM_OPACITY),this._ctx.fillText(e.getChars(),t*this._scaledCellWidth+this._scaledCharLeft,i*this._scaledCellHeight+this._scaledCharTop+this._scaledCharHeight/2),this._ctx.restore()},e.prototype._clipRow=function(e){this._ctx.beginPath(),this._ctx.rect(0,e*this._scaledCellHeight,this._bufferService.cols*this._scaledCellWidth,this._scaledCellHeight),this._ctx.clip()},e.prototype._getFont=function(e,t){return(t?"italic":"")+" "+(e?this._optionsService.options.fontWeightBold:this._optionsService.options.fontWeight)+" "+this._optionsService.options.fontSize*window.devicePixelRatio+"px "+this._optionsService.options.fontFamily},e}();t.BaseRenderLayer=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="di$target",n="di$dependencies";function s(e,t,i){t[r]===t?t[n].push({id:e,index:i}):(t[n]=[{id:e,index:i}],t[r]=t)}t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[n]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);var i=function(e,t,r){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");s(i,e,r)};return i.toString=function(){return e},t.serviceRegistry.set(e,i),i}},function(e,t,i){"use strict";function r(e,t,i,r){if(void 0===i&&(i=0),void 0===r&&(r=e.length),i>=e.length)return e;i=(e.length+i)%e.length,r=r>=e.length?e.length:(e.length+r)%e.length;for(var n=i;n<r;++n)e[n]=t;return e}Object.defineProperty(t,"__esModule",{value:!0}),t.fill=function(e,t,i,n){return e.fill?e.fill(t,i,n):r(e,t,i,n)},t.fillFallback=r,t.concat=function(e,t){var i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(8),n=i(3),s=i(4),o=i(6),a=3;t.DEFAULT_ATTR_DATA=Object.freeze(new o.AttributeData);var c=function(){function e(e,t,i){void 0===i&&(i=!1),this.isWrapped=i,this._combined={},this._data=new Uint32Array(e*a);for(var r=t||s.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]),o=0;o<e;++o)this.setCell(o,r);this.length=e}return e.prototype.get=function(e){var t=this._data[e*a+0],i=2097151&t;return[this._data[e*a+1],2097152&t?this._combined[e]:i?r.stringFromCodePoint(i):"",t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]},e.prototype.set=function(e,t){this._data[e*a+1]=t[n.CHAR_DATA_ATTR_INDEX],t[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[e*a+0]=2097152|e|t[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[e*a+0]=t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[n.CHAR_DATA_WIDTH_INDEX]<<22},e.prototype.getWidth=function(e){return this._data[e*a+0]>>22},e.prototype.hasWidth=function(e){return 12582912&this._data[e*a+0]},e.prototype.getFg=function(e){return this._data[e*a+1]},e.prototype.getBg=function(e){return this._data[e*a+2]},e.prototype.hasContent=function(e){return 4194303&this._data[e*a+0]},e.prototype.getCodePoint=function(e){var t=this._data[e*a+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t},e.prototype.isCombined=function(e){return 2097152&this._data[e*a+0]},e.prototype.getString=function(e){var t=this._data[e*a+0];return 2097152&t?this._combined[e]:2097151&t?r.stringFromCodePoint(2097151&t):""},e.prototype.loadCell=function(e,t){var i=e*a;return t.content=this._data[i+0],t.fg=this._data[i+1],t.bg=this._data[i+2],2097152&t.content&&(t.combinedData=this._combined[e]),t},e.prototype.setCell=function(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),this._data[e*a+0]=t.content,this._data[e*a+1]=t.fg,this._data[e*a+2]=t.bg},e.prototype.setCellFromCodePoint=function(e,t,i,r,n){this._data[e*a+0]=t|i<<22,this._data[e*a+1]=r,this._data[e*a+2]=n},e.prototype.addCodepointToCell=function(e,t){var i=this._data[e*a+0];2097152&i?this._combined[e]+=r.stringFromCodePoint(t):(2097151&i?(this._combined[e]=r.stringFromCodePoint(2097151&i)+r.stringFromCodePoint(t),i&=-2097152,i|=2097152):i=t|1<<22,this._data[e*a+0]=i)},e.prototype.insertCells=function(e,t,i){if(e%=this.length,t<this.length-e){for(var r=new s.CellData,n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(n=0;n<t;++n)this.setCell(e+n,i)}else for(n=e;n<this.length;++n)this.setCell(n,i)},e.prototype.deleteCells=function(e,t,i){if(e%=this.length,t<this.length-e){for(var r=new s.CellData,n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(n=this.length-t;n<this.length;++n)this.setCell(n,i)}else for(n=e;n<this.length;++n)this.setCell(n,i)},e.prototype.replaceCells=function(e,t,i){for(;e<t&&e<this.length;)this.setCell(e++,i)},e.prototype.resize=function(e,t){if(e!==this.length){if(e>this.length){var i=new Uint32Array(e*a);this.length&&(e*a<this._data.length?i.set(this._data.subarray(0,e*a)):i.set(this._data)),this._data=i;for(var r=this.length;r<e;++r)this.setCell(r,t)}else if(e){(i=new Uint32Array(e*a)).set(this._data.subarray(0,e*a)),this._data=i;var n=Object.keys(this._combined);for(r=0;r<n.length;r++){var s=parseInt(n[r],10);s>=e&&delete this._combined[s]}}else this._data=new Uint32Array(0),this._combined={};this.length=e}},e.prototype.fill=function(e){this._combined={};for(var t=0;t<this.length;++t)this.setCell(t,e)},e.prototype.copyFrom=function(e){for(var t in this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];this.isWrapped=e.isWrapped},e.prototype.clone=function(){var t=new e(0);for(var i in t._data=new Uint32Array(this._data),t.length=this.length,this._combined)t._combined[i]=this._combined[i];return t.isWrapped=this.isWrapped,t},e.prototype.getTrimmedLength=function(){for(var e=this.length-1;e>=0;--e)if(4194303&this._data[e*a+0])return e+(this._data[e*a+0]>>22);return 0},e.prototype.copyCellsFrom=function(e,t,i,r,n){var s=e._data;if(n)for(var o=r-1;o>=0;o--)for(var c=0;c<a;c++)this._data[(i+o)*a+c]=s[(t+o)*a+c];else for(o=0;o<r;o++)for(c=0;c<a;c++)this._data[(i+o)*a+c]=s[(t+o)*a+c];var l=Object.keys(e._combined);for(c=0;c<l.length;c++){var h=parseInt(l[c],10);h>=t&&(this._combined[h-t+i]=e._combined[h])}},e.prototype.translateToString=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=0),void 0===i&&(i=this.length),e&&(i=Math.min(i,this.getTrimmedLength()));for(var s="";t<i;){var o=this._data[t*a+0],c=2097151&o;s+=2097152&o?this._combined[t]:c?r.stringFromCodePoint(c):n.WHITESPACE_CELL_CHAR,t+=o>>22||1}return s},e}();t.BufferLine=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.promptLabel="Terminal input",t.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"◆",a:"▒",b:"\t",c:"\f",d:"\r",e:"\n",f:"°",g:"±",h:"␤",i:"\v",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},t.CHARSETS.A={"#":"£"},t.CHARSETS.B=null,t.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},t.CHARSETS.C=t.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},t.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},t.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},t.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},t.CHARSETS.E=t.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},t.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},t.CHARSETS.H=t.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(14);t.wcwidth=function(e){var t=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],i=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];var n=0|e.control,s=new Uint8Array(65536);r.fill(s,1),s[0]=e.nul,r.fill(s,e.control,1,32),r.fill(s,e.control,127,160),r.fill(s,2,4352,4448),s[9001]=2,s[9002]=2,r.fill(s,2,11904,42192),s[12351]=1,r.fill(s,2,44032,55204),r.fill(s,2,63744,64256),r.fill(s,2,65040,65050),r.fill(s,2,65072,65136),r.fill(s,2,65280,65377),r.fill(s,2,65504,65511);for(var o=0;o<t.length;++o)r.fill(s,0,t[o][0],t[o][1]+1);return function(e){return e<32?0|n:e<127?1:e<65536?s[e]:function(e,t){var i,r=0,n=t.length-1;if(e<t[0][0]||e>t[n][1])return!1;for(;n>=r;)if(e>t[i=r+n>>1][1])r=i+1;else{if(!(e<t[i][0]))return!0;n=i-1}return!1}(t=e,i)?0:t>=131072&&t<=196605||t>=196608&&t<=262141?2:1;var t}}({nul:0,control:0}),t.getStringCellWidth=function(e){for(var i=0,r=e.length,n=0;n<r;++n){var s=e.charCodeAt(n);if(55296<=s&&s<=56319){if(++n>=r)return i+t.wcwidth(s);var o=e.charCodeAt(n);56320<=o&&o<=57343?s=1024*(s-55296)+o-56320+65536:i+=t.wcwidth(o)}i+=t.wcwidth(s)}return i}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=256,n=function(){function e(e,t){if(void 0===e&&(e=32),void 0===t&&(t=32),this.maxLength=e,this.maxSubParamsLength=t,t>r)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}return e.fromArray=function(t){var i=new e;if(!t.length)return i;for(var r=t[0]instanceof Array?1:0;r<t.length;++r){var n=t[r];if(n instanceof Array)for(var s=0;s<n.length;++s)i.addSubParam(n[s]);else i.addParam(n)}return i},e.prototype.clone=function(){var t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t},e.prototype.toArray=function(){for(var e=[],t=0;t<this.length;++t){e.push(this.params[t]);var i=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,r))}return e},e.prototype.reset=function(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1},e.prototype.addParam=function(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>2147483647?2147483647:e}},e.prototype.addSubParam=function(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>2147483647?2147483647:e,this._subParamsIdx[this.length-1]++}},e.prototype.hasSubParams=function(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0},e.prototype.getSubParams=function(e){var t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null},e.prototype.getSubParamsAll=function(){for(var e={},t=0;t<this.length;++t){var i=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-i>0&&(e[t]=this._subParams.slice(i,r))}return e},e.prototype.addDigit=function(e){var t;if(!(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)){var i=this._digitIsSub?this._subParams:this.params,r=i[t-1];i[t-1]=~r?Math.min(10*r+e,2147483647):e}},e}();t.Params=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(21),n=i(8),s=function(){function e(){this._state=0,this._id=-1,this._handlers=Object.create(null),this._handlerFb=function(){}}return e.prototype.addHandler=function(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);var i=this._handlers[e];return i.push(t),{dispose:function(){var e=i.indexOf(t);-1!==e&&i.splice(e,1)}}},e.prototype.setHandler=function(e,t){this._handlers[e]=[t]},e.prototype.clearHandler=function(e){this._handlers[e]&&delete this._handlers[e]},e.prototype.setHandlerFallback=function(e){this._handlerFb=e},e.prototype.dispose=function(){this._handlers=Object.create(null),this._handlerFb=function(){}},e.prototype.reset=function(){2===this._state&&this.end(!1),this._id=-1,this._state=0},e.prototype._start=function(){var e=this._handlers[this._id];if(e)for(var t=e.length-1;t>=0;t--)e[t].start();else this._handlerFb(this._id,"START")},e.prototype._put=function(e,t,i){var r=this._handlers[this._id];if(r)for(var s=r.length-1;s>=0;s--)r[s].put(e,t,i);else this._handlerFb(this._id,"PUT",n.utf32ToString(e,t,i))},e.prototype._end=function(e){var t=this._handlers[this._id];if(t){for(var i=t.length-1;i>=0&&!1===t[i].end(e);i--);for(i--;i>=0;i--)t[i].end(!1)}else this._handlerFb(this._id,"END",e)},e.prototype.start=function(){this.reset(),this._id=-1,this._state=1},e.prototype.put=function(e,t,i){if(3!==this._state){if(1===this._state)for(;t<i;){var r=e[t++];if(59===r){this._state=2,this._start();break}if(r<48||57<r)return void(this._state=3);-1===this._id&&(this._id=0),this._id=10*this._id+r-48}2===this._state&&i-t>0&&this._put(e,t,i)}},e.prototype.end=function(e){0!==this._state&&(3!==this._state&&(1===this._state&&this._start(),this._end(e)),this._id=-1,this._state=0)},e}();t.OscParser=s;var o=function(){function e(e){this._handler=e,this._data="",this._hitLimit=!1}return e.prototype.start=function(){this._data="",this._hitLimit=!1},e.prototype.put=function(e,t,i){this._hitLimit||(this._data+=n.utf32ToString(e,t,i),this._data.length>r.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))},e.prototype.end=function(e){var t;return this._hitLimit?t=!1:e&&(t=this._handler(this._data)),this._data="",this._hitLimit=!1,t},e}();t.OscHandler=o},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=1e7},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(8),n=i(19),s=i(21),o=[],a=function(){function e(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=function(){}}return e.prototype.dispose=function(){this._handlers=Object.create(null),this._handlerFb=function(){}},e.prototype.addHandler=function(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);var i=this._handlers[e];return i.push(t),{dispose:function(){var e=i.indexOf(t);-1!==e&&i.splice(e,1)}}},e.prototype.setHandler=function(e,t){this._handlers[e]=[t]},e.prototype.clearHandler=function(e){this._handlers[e]&&delete this._handlers[e]},e.prototype.setHandlerFallback=function(e){this._handlerFb=e},e.prototype.reset=function(){this._active.length&&this.unhook(!1),this._active=o,this._ident=0},e.prototype.hook=function(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(var i=this._active.length-1;i>=0;i--)this._active[i].hook(t);else this._handlerFb(this._ident,"HOOK",t)},e.prototype.put=function(e,t,i){if(this._active.length)for(var n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i);else this._handlerFb(this._ident,"PUT",r.utf32ToString(e,t,i))},e.prototype.unhook=function(e){if(this._active.length){for(var t=this._active.length-1;t>=0&&!1===this._active[t].unhook(e);t--);for(t--;t>=0;t--)this._active[t].unhook(!1)}else this._handlerFb(this._ident,"UNHOOK",e);this._active=o,this._ident=0},e}();t.DcsParser=a;var c=function(){function e(e){this._handler=e,this._data="",this._hitLimit=!1}return e.prototype.hook=function(e){this._params=e.clone(),this._data="",this._hitLimit=!1},e.prototype.put=function(e,t,i){this._hitLimit||(this._data+=r.utf32ToString(e,t,i),this._data.length>s.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))},e.prototype.unhook=function(e){var t;return this._hitLimit?t=!1:e&&(t=this._handler(this._data,this._params?this._params:new n.Params)),this._params=void 0,this._data="",this._hitLimit=!1,t},e}();t.DcsHandler=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(24),n=i(42),s=[];t.acquireCharAtlas=function(e,t,i,o,a){for(var c=r.generateConfig(o,a,e,i),l=0;l<s.length;l++){var h=(u=s[l]).ownedBy.indexOf(t);if(h>=0){if(r.configEquals(u.config,c))return u.atlas;1===u.ownedBy.length?(u.atlas.dispose(),s.splice(l,1)):u.ownedBy.splice(h,1);break}}for(l=0;l<s.length;l++){var u=s[l];if(r.configEquals(u.config,c))return u.ownedBy.push(t),u.atlas}var f={atlas:new n.DynamicCharAtlas(document,c),config:c,ownedBy:[t]};return s.push(f),f.atlas},t.removeTerminalFromCache=function(e){for(var t=0;t<s.length;t++){var i=s[t].ownedBy.indexOf(e);if(-1!==i){1===s[t].ownedBy.length?(s[t].atlas.dispose(),s.splice(t,1)):s[t].ownedBy.splice(i,1);break}}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(3);t.generateConfig=function(e,t,i,r){var n={foreground:r.foreground,background:r.background,cursor:void 0,cursorAccent:void 0,selection:void 0,ansi:r.ansi.slice(0,16)};return{devicePixelRatio:window.devicePixelRatio,scaledCharWidth:e,scaledCharHeight:t,fontFamily:i.fontFamily,fontSize:i.fontSize,fontWeight:i.fontWeight,fontWeightBold:i.fontWeightBold,allowTransparency:i.allowTransparency,colors:n}},t.configEquals=function(e,t){for(var i=0;i<e.colors.ansi.length;i++)if(e.colors.ansi[i].rgba!==t.colors.ansi[i].rgba)return!1;return e.devicePixelRatio===t.devicePixelRatio&&e.fontFamily===t.fontFamily&&e.fontSize===t.fontSize&&e.fontWeight===t.fontWeight&&e.fontWeightBold===t.fontWeightBold&&e.allowTransparency===t.allowTransparency&&e.scaledCharWidth===t.scaledCharWidth&&e.scaledCharHeight===t.scaledCharHeight&&e.colors.foreground===t.colors.foreground&&e.colors.background===t.colors.background},t.is256Color=function(e){return e<r.DEFAULT_COLOR}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=c("#ffffff"),n=c("#000000"),s=c("#ffffff"),o=c("#000000"),a={css:"rgba(255, 255, 255, 0.3)",rgba:4294967159};function c(e){return{css:e,rgba:parseInt(e.slice(1),16)<<8|255}}function l(e){var t=e.toString(16);return t.length<2?"0"+t:t}t.DEFAULT_ANSI_COLORS=function(){for(var e=[c("#2e3436"),c("#cc0000"),c("#4e9a06"),c("#c4a000"),c("#3465a4"),c("#75507b"),c("#06989a"),c("#d3d7cf"),c("#555753"),c("#ef2929"),c("#8ae234"),c("#fce94f"),c("#729fcf"),c("#ad7fa8"),c("#34e2e2"),c("#eeeeec")],t=[0,95,135,175,215,255],i=0;i<216;i++){var r=t[i/36%6|0],n=t[i/6%6|0],s=t[i%6];e.push({css:"#"+l(r)+l(n)+l(s),rgba:(r<<24|n<<16|s<<8|255)>>>0})}for(i=0;i<24;i++){var o=8+10*i,a=l(o);e.push({css:"#"+a+a+a,rgba:(o<<24|o<<16|o<<8|255)>>>0})}return e}();var h=function(){function e(e,i){this.allowTransparency=i;var c=e.createElement("canvas");c.width=1,c.height=1;var l=c.getContext("2d");if(!l)throw new Error("Could not get rendering context");this._ctx=l,this._ctx.globalCompositeOperation="copy",this._litmusColor=this._ctx.createLinearGradient(0,0,1,1),this.colors={foreground:r,background:n,cursor:s,cursorAccent:o,selection:a,ansi:t.DEFAULT_ANSI_COLORS.slice()}}return e.prototype.setTheme=function(e){void 0===e&&(e={}),this.colors.foreground=this._parseColor(e.foreground,r),this.colors.background=this._parseColor(e.background,n),this.colors.cursor=this._parseColor(e.cursor,s,!0),this.colors.cursorAccent=this._parseColor(e.cursorAccent,o,!0),this.colors.selection=this._parseColor(e.selection,a,!0),this.colors.ansi[0]=this._parseColor(e.black,t.DEFAULT_ANSI_COLORS[0]),this.colors.ansi[1]=this._parseColor(e.red,t.DEFAULT_ANSI_COLORS[1]),this.colors.ansi[2]=this._parseColor(e.green,t.DEFAULT_ANSI_COLORS[2]),this.colors.ansi[3]=this._parseColor(e.yellow,t.DEFAULT_ANSI_COLORS[3]),this.colors.ansi[4]=this._parseColor(e.blue,t.DEFAULT_ANSI_COLORS[4]),this.colors.ansi[5]=this._parseColor(e.magenta,t.DEFAULT_ANSI_COLORS[5]),this.colors.ansi[6]=this._parseColor(e.cyan,t.DEFAULT_ANSI_COLORS[6]),this.colors.ansi[7]=this._parseColor(e.white,t.DEFAULT_ANSI_COLORS[7]),this.colors.ansi[8]=this._parseColor(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),this.colors.ansi[9]=this._parseColor(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),this.colors.ansi[10]=this._parseColor(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),this.colors.ansi[11]=this._parseColor(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),this.colors.ansi[12]=this._parseColor(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),this.colors.ansi[13]=this._parseColor(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),this.colors.ansi[14]=this._parseColor(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),this.colors.ansi[15]=this._parseColor(e.brightWhite,t.DEFAULT_ANSI_COLORS[15])},e.prototype._parseColor=function(e,t,i){if(void 0===i&&(i=this.allowTransparency),void 0===e)return t;if(this._ctx.fillStyle=this._litmusColor,this._ctx.fillStyle=e,"string"!=typeof this._ctx.fillStyle)return console.warn("Color: "+e+" is invalid using fallback "+t.css),t;this._ctx.fillRect(0,0,1,1);var r=this._ctx.getImageData(0,0,1,1).data;return i||255===r[3]?{css:e,rgba:(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0}:(console.warn("Color: "+e+" is using transparency, but allowTransparency is false. Using fallback "+t.css+"."),t)},e}();t.ColorManager=h},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.throwIfFalsy=function(e){if(!e)throw new Error("value must not be falsy");return e}},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(6),o=i(3),a=i(4),c=function(e){function t(t,i,r){var n=e.call(this)||this;return n.content=0,n.combinedData="",n.fg=t.fg,n.bg=t.bg,n.combinedData=i,n._width=r,n}return n(t,e),t.prototype.isCombined=function(){return 2097152},t.prototype.getWidth=function(){return this._width},t.prototype.getChars=function(){return this.combinedData},t.prototype.getCode=function(){return 2097151},t.prototype.setFromCharData=function(e){throw new Error("not implemented")},t.prototype.getAsCharData=function(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]},t}(s.AttributeData);t.JoinedCellData=c;var l=function(){function e(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new a.CellData}return e.prototype.registerCharacterJoiner=function(e){var t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id},e.prototype.deregisterCharacterJoiner=function(e){for(var t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1},e.prototype.getJoinedCharacters=function(e){if(0===this._characterJoiners.length)return[];var t=this._bufferService.buffer.lines.get(e);if(!t||0===t.length)return[];for(var i=[],r=t.translateToString(!0),n=0,s=0,a=0,c=t.getFg(0),l=t.getBg(0),h=0;h<t.getTrimmedLength();h++)if(t.loadCell(h,this._workCell),0!==this._workCell.getWidth()){if(this._workCell.fg!==c||this._workCell.bg!==l){if(h-n>1)for(var u=this._getJoinedRanges(r,a,s,t,n),f=0;f<u.length;f++)i.push(u[f]);n=h,a=s,c=this._workCell.fg,l=this._workCell.bg}s+=this._workCell.getChars().length||o.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-n>1)for(u=this._getJoinedRanges(r,a,s,t,n),f=0;f<u.length;f++)i.push(u[f]);return i},e.prototype._getJoinedRanges=function(t,i,r,n,s){for(var o=t.substring(i,r),a=this._characterJoiners[0].handler(o),c=1;c<this._characterJoiners.length;c++)for(var l=this._characterJoiners[c].handler(o),h=0;h<l.length;h++)e._mergeRanges(a,l[h]);return this._stringRangesToCellRanges(a,n,s),a},e.prototype._stringRangesToCellRanges=function(e,t,i){var r=0,n=!1,s=0,a=e[r];if(a){for(var c=i;c<this._bufferService.cols;c++){var l=t.getWidth(c),h=t.getString(c).length||o.WHITESPACE_CELL_CHAR.length;if(0!==l){if(!n&&a[0]<=s&&(a[0]=c,n=!0),a[1]<=s){if(a[1]=c,!(a=e[++r]))break;a[0]<=s?(a[0]=c,n=!0):n=!1}s+=h}}a&&(a[1]=this._bufferService.cols)}},e._mergeRanges=function(e,t){for(var i=!1,r=0;r<e.length;r++){var n=e[r];if(i){if(t[1]<=n[0])return e[r-1][1]=t[1],e;if(t[1]<=n[1])return e[r-1][1]=Math.max(t[1],n[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=n[0])return e.splice(r,0,t),e;if(t[1]<=n[1])return n[0]=Math.min(t[0],n[0]),e;t[0]<n[1]&&(n[0]=Math.min(t[0],n[0]),i=!0)}}return i?e[e.length-1][1]=t[1]:e.push(t),e},e}();t.CharacterJoinerRegistry=l},function(e,t,i){"use strict";function r(e,t){var i=t.getBoundingClientRect();return[e.clientX-i.left,e.clientY-i.top]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoordsRelativeToElement=r,t.getCoords=function(e,t,i,n,s,o,a,c){if(s){var l=r(e,t);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/a),l[0]=Math.min(Math.max(l[0],1),i+(c?1:0)),l[1]=Math.min(Math.max(l[1],1),n),l}},t.getRawByteCoords=function(e){if(e)return{x:e[0]+32,y:e[1]+32}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this._renderCallback=e}return e.prototype.dispose=function(){this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)},e.prototype.refresh=function(e,t,i){var r=this;this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,this._animationFrame||(this._animationFrame=window.requestAnimationFrame(function(){return r._innerRefresh()}))},e.prototype._innerRefresh=function(){void 0!==this._rowStart&&void 0!==this._rowEnd&&void 0!==this._rowCount&&(this._rowStart=Math.max(this._rowStart,0),this._rowEnd=Math.min(this._rowEnd,this._rowCount-1),this._renderCallback(this._rowStart,this._rowEnd),this._rowStart=void 0,this._rowEnd=void 0,this._animationFrame=void 0)},e}();t.RenderDebouncer=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._currentDevicePixelRatio=window.devicePixelRatio,t}return n(t,e),t.prototype.setListener=function(e){var t=this;this._listener&&this.clearListener(),this._listener=e,this._outerListener=function(){t._listener&&(t._listener(window.devicePixelRatio,t._currentDevicePixelRatio),t._updateDpr())},this._updateDpr()},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.clearListener()},t.prototype._updateDpr=function(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._currentDevicePixelRatio=window.devicePixelRatio,this._resolutionMediaMatchList=window.matchMedia("screen and (resolution: "+window.devicePixelRatio+"dppx)"),this._resolutionMediaMatchList.addListener(this._outerListener))},t.prototype.clearListener=function(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)},t}(i(2).Disposable);t.ScreenDprMonitor=s},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=function e(t,i){if(void 0===i&&(i=5),"object"!=typeof t)return t;var r=Array.isArray(t)?[]:{};for(var n in t)r[n]=i<=1?t[n]:t[n]?e(t[n],i-1):t[n];return r}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(33),n=i(16),s=i(75),o=function(){function e(e){this._core=new r.Terminal(e),this._addonManager=new s.AddonManager}return Object.defineProperty(e.prototype,"onCursorMove",{get:function(){return this._core.onCursorMove},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onLineFeed",{get:function(){return this._core.onLineFeed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onSelectionChange",{get:function(){return this._core.onSelectionChange},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onData",{get:function(){return this._core.onData},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTitleChange",{get:function(){return this._core.onTitleChange},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onScroll",{get:function(){return this._core.onScroll},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onKey",{get:function(){return this._core.onKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onRender",{get:function(){return this._core.onRender},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onResize",{get:function(){return this._core.onResize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){return this._core.element},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parser",{get:function(){return this._parser||(this._parser=new h(this._core)),this._parser},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textarea",{get:function(){return this._core.textarea},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rows",{get:function(){return this._core.rows},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cols",{get:function(){return this._core.cols},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"buffer",{get:function(){return new a(this._core.buffer)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"markers",{get:function(){return this._core.markers},enumerable:!0,configurable:!0}),e.prototype.blur=function(){this._core.blur()},e.prototype.focus=function(){this._core.focus()},e.prototype.resize=function(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)},e.prototype.open=function(e){this._core.open(e)},e.prototype.attachCustomKeyEventHandler=function(e){this._core.attachCustomKeyEventHandler(e)},e.prototype.registerLinkMatcher=function(e,t,i){return this._core.registerLinkMatcher(e,t,i)},e.prototype.deregisterLinkMatcher=function(e){this._core.deregisterLinkMatcher(e)},e.prototype.registerCharacterJoiner=function(e){return this._core.registerCharacterJoiner(e)},e.prototype.deregisterCharacterJoiner=function(e){this._core.deregisterCharacterJoiner(e)},e.prototype.addMarker=function(e){return this._verifyIntegers(e),this._core.addMarker(e)},e.prototype.hasSelection=function(){return this._core.hasSelection()},e.prototype.select=function(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)},e.prototype.getSelection=function(){return this._core.getSelection()},e.prototype.getSelectionPosition=function(){return this._core.getSelectionPosition()},e.prototype.clearSelection=function(){this._core.clearSelection()},e.prototype.selectAll=function(){this._core.selectAll()},e.prototype.selectLines=function(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)},e.prototype.dispose=function(){this._addonManager.dispose(),this._core.dispose()},e.prototype.scrollLines=function(e){this._verifyIntegers(e),this._core.scrollLines(e)},e.prototype.scrollPages=function(e){this._verifyIntegers(e),this._core.scrollPages(e)},e.prototype.scrollToTop=function(){this._core.scrollToTop()},e.prototype.scrollToBottom=function(){this._core.scrollToBottom()},e.prototype.scrollToLine=function(e){this._verifyIntegers(e),this._core.scrollToLine(e)},e.prototype.clear=function(){this._core.clear()},e.prototype.write=function(e,t){this._core.write(e,t)},e.prototype.writeUtf8=function(e,t){this._core.write(e,t)},e.prototype.writeln=function(e,t){this._core.write(e),this._core.write("\r\n",t)},e.prototype.paste=function(e){this._core.paste(e)},e.prototype.getOption=function(e){return this._core.optionsService.getOption(e)},e.prototype.setOption=function(e,t){this._core.optionsService.setOption(e,t)},e.prototype.refresh=function(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)},e.prototype.reset=function(){this._core.reset()},e.prototype.loadAddon=function(e){return this._addonManager.loadAddon(this,e)},Object.defineProperty(e,"strings",{get:function(){return n},enumerable:!0,configurable:!0}),e.prototype._verifyIntegers=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];e.forEach(function(e){if(e===1/0||isNaN(e)||e%1!=0)throw new Error("This API only accepts integers")})},e}();t.Terminal=o;var a=function(){function e(e){this._buffer=e}return Object.defineProperty(e.prototype,"cursorY",{get:function(){return this._buffer.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cursorX",{get:function(){return this._buffer.x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"viewportY",{get:function(){return this._buffer.ydisp},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"baseY",{get:function(){return this._buffer.ybase},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return this._buffer.lines.length},enumerable:!0,configurable:!0}),e.prototype.getLine=function(e){var t=this._buffer.lines.get(e);if(t)return new c(t)},e}(),c=function(){function e(e){this._line=e}return Object.defineProperty(e.prototype,"isWrapped",{get:function(){return this._line.isWrapped},enumerable:!0,configurable:!0}),e.prototype.getCell=function(e){if(!(e<0||e>=this._line.length))return new l(this._line,e)},e.prototype.translateToString=function(e,t,i){return this._line.translateToString(e,t,i)},e}(),l=function(){function e(e,t){this._line=e,this._x=t}return Object.defineProperty(e.prototype,"char",{get:function(){return this._line.getString(this._x)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._line.getWidth(this._x)},enumerable:!0,configurable:!0}),e}(),h=function(){function e(e){this._core=e}return e.prototype.addCsiHandler=function(e,t){return this._core.addCsiHandler(e,function(e){return t(e.toArray())})},e.prototype.addDcsHandler=function(e,t){return this._core.addDcsHandler(e,function(e,i){return t(e,i.toArray())})},e.prototype.addEscHandler=function(e,t){return this._core.addEscHandler(e,t)},e.prototype.addOscHandler=function(e,t){return this._core.addOscHandler(e,t)},e}()},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(34),o=i(35),a=i(36),c=i(11),l=i(37),h=i(39),u=i(48),f=i(49),_=i(10),d=i(7),p=i(16),v=i(52),g=i(53),y=i(54),m=i(55),b=i(57),C=i(1),S=i(15),w=i(58),E=i(25),L=i(59),A=i(0),x=i(60),k=i(5),D=i(61),T=i(62),R=i(2),M=i(68),O=i(69),P=i(70),H=i(71),I=i(72),B=i(73),F=i(74),j="undefined"!=typeof window?window.document:null,W=function(e){function t(t){void 0===t&&(t={});var i=e.call(this)||this;return i.browser=_,i.mouseEvents=0,i._keyDownHandled=!1,i._blankLine=null,i._onCursorMove=new C.EventEmitter,i._onData=new C.EventEmitter,i._onKey=new C.EventEmitter,i._onLineFeed=new C.EventEmitter,i._onRender=new C.EventEmitter,i._onResize=new C.EventEmitter,i._onScroll=new C.EventEmitter,i._onSelectionChange=new C.EventEmitter,i._onTitleChange=new C.EventEmitter,i._onFocus=new C.EventEmitter,i._onBlur=new C.EventEmitter,i.onA11yCharEmitter=new C.EventEmitter,i.onA11yTabEmitter=new C.EventEmitter,i._instantiationService=new I.InstantiationService,i.optionsService=new x.OptionsService(t),i._instantiationService.setService(A.IOptionsService,i.optionsService),i._bufferService=i._instantiationService.createInstance(T.BufferService),i._instantiationService.setService(A.IBufferService,i._bufferService),i._logService=i._instantiationService.createInstance(P.LogService),i._instantiationService.setService(A.ILogService,i._logService),i._coreService=i._instantiationService.createInstance(O.CoreService,function(){return i.scrollToBottom()}),i._instantiationService.setService(A.ICoreService,i._coreService),i._coreService.onData(function(e){return i._onData.fire(e)}),i._coreMouseService=i._instantiationService.createInstance(B.CoreMouseService),i._instantiationService.setService(A.ICoreMouseService,i._coreMouseService),i._dirtyRowService=i._instantiationService.createInstance(H.DirtyRowService),i._instantiationService.setService(A.IDirtyRowService,i._dirtyRowService),i._setupOptionsListeners(),i._setup(),i._writeBuffer=new F.WriteBuffer(function(e){return i._inputHandler.parse(e)}),i}return n(t,e),Object.defineProperty(t.prototype,"options",{get:function(){return this.optionsService.options},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cols",{get:function(){return this._bufferService.cols},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rows",{get:function(){return this._bufferService.rows},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onCursorMove",{get:function(){return this._onCursorMove.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onData",{get:function(){return this._onData.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onKey",{get:function(){return this._onKey.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onLineFeed",{get:function(){return this._onLineFeed.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRender",{get:function(){return this._onRender.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onResize",{get:function(){return this._onResize.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onSelectionChange",{get:function(){return this._onSelectionChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onTitleChange",{get:function(){return this._onTitleChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onFocus",{get:function(){return this._onFocus.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBlur",{get:function(){return this._onBlur.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onA11yChar",{get:function(){return this.onA11yCharEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onA11yTab",{get:function(){return this.onA11yTabEmitter.event},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this._isDisposed||(e.prototype.dispose.call(this),this._windowsMode&&(this._windowsMode.dispose(),this._windowsMode=void 0),this._renderService&&this._renderService.dispose(),this._customKeyEventHandler=null,this.write=function(){},this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element))},t.prototype._setup=function(){var e=this;this._parent=j?j.body:null,this.cursorState=0,this.cursorHidden=!1,this._customKeyEventHandler=null,this.applicationKeypad=!1,this.originMode=!1,this.insertMode=!1,this.wraparoundMode=!0,this.bracketedPasteMode=!1,this.charset=null,this.gcharset=null,this.glevel=0,this.charsets=[null],this.curAttrData=S.DEFAULT_ATTR_DATA.clone(),this._eraseAttrData=S.DEFAULT_ATTR_DATA.clone(),this.params=[],this.currentParam=0,this._userScrolling=!1,this._inputHandler=new l.InputHandler(this,this._bufferService,this._coreService,this._dirtyRowService,this._logService,this.optionsService,this._coreMouseService),this._inputHandler.onCursorMove(function(){return e._onCursorMove.fire()}),this._inputHandler.onLineFeed(function(){return e._onLineFeed.fire()}),this.register(this._inputHandler),this.linkifier=this.linkifier||new u.Linkifier(this._bufferService,this._logService),this.options.windowsMode&&(this._windowsMode=w.applyWindowsMode(this))},Object.defineProperty(t.prototype,"buffer",{get:function(){return this.buffers.active},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buffers",{get:function(){return this._bufferService.buffers},enumerable:!0,configurable:!0}),t.prototype.eraseAttrData=function(){return this._eraseAttrData.bg&=-67108864,this._eraseAttrData.bg|=67108863&this.curAttrData.bg,this._eraseAttrData},t.prototype.focus=function(){this.textarea&&this.textarea.focus({preventScroll:!0})},Object.defineProperty(t.prototype,"isFocused",{get:function(){return j.activeElement===this.textarea&&j.hasFocus()},enumerable:!0,configurable:!0}),t.prototype._setupOptionsListeners=function(){var e=this;this.optionsService.onOptionChange(function(t){switch(t){case"fontFamily":case"fontSize":e._renderService&&e._renderService.clear(),e._charSizeService&&e._charSizeService.measure();break;case"drawBoldTextInBrightColors":case"letterSpacing":case"lineHeight":case"fontWeight":case"fontWeightBold":e._renderService&&(e._renderService.clear(),e._renderService.onResize(e.cols,e.rows),e.refresh(0,e.rows-1));break;case"rendererType":e._renderService&&(e._renderService.setRenderer(e._createRenderer()),e._renderService.onResize(e.cols,e.rows));break;case"scrollback":e.buffers.resize(e.cols,e.rows),e.viewport&&e.viewport.syncScrollArea();break;case"screenReaderMode":e.optionsService.options.screenReaderMode?!e._accessibilityManager&&e._renderService&&(e._accessibilityManager=new y.AccessibilityManager(e,e._renderService)):e._accessibilityManager&&(e._accessibilityManager.dispose(),e._accessibilityManager=null);break;case"tabStopWidth":e.buffers.setupTabStops();break;case"theme":e._setTheme(e.optionsService.options.theme);break;case"windowsMode":e.optionsService.options.windowsMode?e._windowsMode||(e._windowsMode=w.applyWindowsMode(e)):e._windowsMode&&(e._windowsMode.dispose(),e._windowsMode=void 0)}})},t.prototype._onTextAreaFocus=function(e){this.sendFocus&&this._coreService.triggerDataEvent(c.C0.ESC+"[I"),this.updateCursorStyle(e),this.element.classList.add("focus"),this.showCursor(),this._onFocus.fire()},t.prototype.blur=function(){return this.textarea.blur()},t.prototype._onTextAreaBlur=function(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.sendFocus&&this._coreService.triggerDataEvent(c.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()},t.prototype._initGlobal=function(){var e=this;this._bindKeys(),this.register(d.addDisposableDomListener(this.element,"copy",function(t){e.hasSelection()&&a.copyHandler(t,e._selectionService)}));var t=function(t){return a.handlePasteEvent(t,e.textarea,e.bracketedPasteMode,e._coreService)};this.register(d.addDisposableDomListener(this.textarea,"paste",t)),this.register(d.addDisposableDomListener(this.element,"paste",t)),_.isFirefox?this.register(d.addDisposableDomListener(this.element,"mousedown",function(t){2===t.button&&a.rightClickHandler(t,e.textarea,e.screenElement,e._selectionService,e.options.rightClickSelectsWord)})):this.register(d.addDisposableDomListener(this.element,"contextmenu",function(t){a.rightClickHandler(t,e.textarea,e.screenElement,e._selectionService,e.options.rightClickSelectsWord)})),_.isLinux&&this.register(d.addDisposableDomListener(this.element,"auxclick",function(t){1===t.button&&a.moveTextAreaUnderMouseCursor(t,e.textarea,e.screenElement)}))},t.prototype._bindKeys=function(){var e=this;this.register(d.addDisposableDomListener(this.textarea,"keyup",function(t){return e._keyUp(t)},!0)),this.register(d.addDisposableDomListener(this.textarea,"keydown",function(t){return e._keyDown(t)},!0)),this.register(d.addDisposableDomListener(this.textarea,"keypress",function(t){return e._keyPress(t)},!0)),this.register(d.addDisposableDomListener(this.textarea,"compositionstart",function(){return e._compositionHelper.compositionstart()})),this.register(d.addDisposableDomListener(this.textarea,"compositionupdate",function(t){return e._compositionHelper.compositionupdate(t)})),this.register(d.addDisposableDomListener(this.textarea,"compositionend",function(){return e._compositionHelper.compositionend()})),this.register(this.onRender(function(){return e._compositionHelper.updateCompositionElements()})),this.register(this.onRender(function(t){return e._queueLinkification(t.start,t.end)}))},t.prototype.open=function(e){var t=this;if(this._parent=e||this._parent,!this._parent)throw new Error("Terminal requires a parent element.");j.body.contains(e)||this._logService.warn("Terminal.open was called on an element that was not attached to the DOM"),this._document=this._parent.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),this.element.setAttribute("tabindex","0"),this._parent.appendChild(this.element);var i=j.createDocumentFragment();this._viewportElement=j.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this._viewportScrollArea=j.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=j.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=j.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement),this.textarea=j.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",p.promptLabel),this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this.register(d.addDisposableDomListener(this.textarea,"focus",function(e){return t._onTextAreaFocus(e)})),this.register(d.addDisposableDomListener(this.textarea,"blur",function(){return t._onTextAreaBlur()})),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(D.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(k.ICharSizeService,this._charSizeService),this._compositionView=j.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(s.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild(i),this._theme=this.options.theme||this._theme,this.options.theme=void 0,this._colorManager=new E.ColorManager(j,this.options.allowTransparency),this._colorManager.setTheme(this._theme);var r=this._createRenderer();this._renderService=this._instantiationService.createInstance(L.RenderService,r,this.rows,this.screenElement),this._instantiationService.setService(k.IRenderService,this._renderService),this._renderService.onRender(function(e){return t._onRender.fire(e)}),this.onResize(function(e){return t._renderService.resize(e.cols,e.rows)}),this._soundService=this._instantiationService.createInstance(v.SoundService),this._instantiationService.setService(k.ISoundService,this._soundService),this._mouseService=this._instantiationService.createInstance(M.MouseService),this._instantiationService.setService(k.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(o.Viewport,function(e,i){return t.scrollLines(e,i)},this._viewportElement,this._viewportScrollArea),this.viewport.onThemeChange(this._colorManager.colors),this.register(this.viewport),this.register(this.onCursorMove(function(){return t._renderService.onCursorMove()})),this.register(this.onResize(function(){return t._renderService.onResize(t.cols,t.rows)})),this.register(this.onBlur(function(){return t._renderService.onBlur()})),this.register(this.onFocus(function(){return t._renderService.onFocus()})),this.register(this._renderService.onDimensionsChange(function(){return t.viewport.syncScrollArea()})),this._selectionService=this._instantiationService.createInstance(f.SelectionService,function(e,i){return t.scrollLines(e,i)},this.element,this.screenElement),this._instantiationService.setService(k.ISelectionService,this._selectionService),this.register(this._selectionService.onSelectionChange(function(){return t._onSelectionChange.fire()})),this.register(this._selectionService.onRedrawRequest(function(e){return t._renderService.onSelectionChanged(e.start,e.end,e.columnSelectMode)})),this.register(this._selectionService.onLinuxMouseSelection(function(e){t.textarea.value=e,t.textarea.focus(),t.textarea.select()})),this.register(this.onScroll(function(){t.viewport.syncScrollArea(),t._selectionService.refresh()})),this.register(d.addDisposableDomListener(this._viewportElement,"scroll",function(){return t._selectionService.refresh()})),this._mouseZoneManager=this._instantiationService.createInstance(g.MouseZoneManager,this.element,this.screenElement),this.register(this._mouseZoneManager),this.register(this.onScroll(function(){return t._mouseZoneManager.clearAll()})),this.linkifier.attachToDom(this.element,this._mouseZoneManager),this.register(d.addDisposableDomListener(this.element,"mousedown",function(e){return t._selectionService.onMouseDown(e)})),this.mouseEvents?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager=new y.AccessibilityManager(this,this._renderService)),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()},t.prototype._createRenderer=function(){switch(this.options.rendererType){case"canvas":return new h.Renderer(this._colorManager.colors,this,this._bufferService,this._charSizeService,this.optionsService);case"dom":return new m.DomRenderer(this,this._colorManager.colors,this._charSizeService,this.optionsService);default:throw new Error('Unrecognized rendererType "'+this.options.rendererType+'"')}},t.prototype._setTheme=function(e){this._theme=e,this._colorManager&&this._colorManager.setTheme(e),this._renderService&&this._renderService.setColors(this._colorManager.colors),this.viewport&&this.viewport.onThemeChange(this._colorManager.colors)},t.prototype.bindMouse=function(){var e=this,t=this,i=this.element;function r(e){var i,r,n;if(!(i=t._mouseService.getRawByteCoords(e,t.screenElement,t.cols,t.rows)))return!1;switch(e.overrideType||e.type){case"mousemove":n=32,void 0===e.buttons?(r=3,void 0!==e.button&&(r=e.button<3?e.button:3)):r=1&e.buttons?0:4&e.buttons?1:2&e.buttons?2:3;break;case"mouseup":n=0,r=e.button<3?e.button:3;break;case"mousedown":n=1,r=e.button<3?e.button:3;break;case"wheel":0!==e.deltaY&&(n=e.deltaY<0?0:1),r=4;break;default:return!1}return!(void 0===n||void 0===r||r>4)&&t._coreMouseService.triggerMouseEvent({col:i.x-33,row:i.y-33,button:r,action:n,ctrl:e.ctrlKey,alt:e.altKey,shift:e.shiftKey})}var n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s=function(t){return r(t),t.buttons||(e._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&e._document.removeEventListener("mousemove",n.mousedrag)),e.cancel(t)},o=function(t){return r(t),t.preventDefault(),e.cancel(t)},a=function(e){e.buttons&&r(e)},l=function(e){e.buttons||r(e)};this._coreMouseService.onProtocolChange(function(t){e.mouseEvents=t,t?("debug"===e.optionsService.options.logLevel&&e._logService.debug("Binding to mouse events:",e._coreMouseService.explainEvents(t)),e.element.classList.add("enable-mouse-events"),e._selectionService.disable()):(e._logService.debug("Unbinding from mouse events."),e.element.classList.remove("enable-mouse-events"),e._selectionService.enable()),8&t?n.mousemove||(i.addEventListener("mousemove",l),n.mousemove=l):(i.removeEventListener("mousemove",n.mousemove),n.mousemove=null),16&t?n.wheel||(i.addEventListener("wheel",o),n.wheel=o):(i.removeEventListener("wheel",n.wheel),n.wheel=null),2&t?n.mouseup||(n.mouseup=s):(e._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),4&t?n.mousedrag||(n.mousedrag=a):(e._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)}),this._coreMouseService.activeProtocol=this._coreMouseService.activeProtocol,this.register(d.addDisposableDomListener(i,"mousedown",function(t){if(t.preventDefault(),e.focus(),e.mouseEvents&&!e._selectionService.shouldForceSelection(t))return r(t),n.mouseup&&e._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&e._document.addEventListener("mousemove",n.mousedrag),e.cancel(t)})),this.register(d.addDisposableDomListener(i,"wheel",function(t){if(n.wheel);else if(!e.buffer.hasScrollback){var i=e.viewport.getLinesScrolled(t);if(0===i)return;for(var r=c.C0.ESC+(e._coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(t.deltaY<0?"A":"B"),s="",o=0;o<Math.abs(i);o++)s+=r;e._coreService.triggerDataEvent(s,!0)}})),this.register(d.addDisposableDomListener(i,"wheel",function(t){if(!n.wheel)return e.viewport.onWheel(t)?void 0:e.cancel(t)})),this.register(d.addDisposableDomListener(i,"touchstart",function(t){if(!e.mouseEvents)return e.viewport.onTouchStart(t),e.cancel(t)})),this.register(d.addDisposableDomListener(i,"touchmove",function(t){if(!e.mouseEvents)return e.viewport.onTouchMove(t)?void 0:e.cancel(t)}))},t.prototype.refresh=function(e,t){this._renderService&&this._renderService.refreshRows(e,t)},t.prototype._queueLinkification=function(e,t){this.linkifier&&this.linkifier.linkifyRows(e,t)},t.prototype.updateCursorStyle=function(e){this._selectionService&&this._selectionService.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")},t.prototype.showCursor=function(){this.cursorState||(this.cursorState=1,this.refresh(this.buffer.y,this.buffer.y))},t.prototype.scroll=function(e){var t;void 0===e&&(e=!1),t=this._blankLine;var i=this.eraseAttrData();t&&t.length===this.cols&&t.getFg(0)===i.fg&&t.getBg(0)===i.bg||(t=this.buffer.getBlankLine(i,e),this._blankLine=t),t.isWrapped=e;var r=this.buffer.ybase+this.buffer.scrollTop,n=this.buffer.ybase+this.buffer.scrollBottom;if(0===this.buffer.scrollTop){var s=this.buffer.lines.isFull;n===this.buffer.lines.length-1?s?this.buffer.lines.recycle().copyFrom(t):this.buffer.lines.push(t.clone()):this.buffer.lines.splice(n+1,0,t.clone()),s?this._userScrolling&&(this.buffer.ydisp=Math.max(this.buffer.ydisp-1,0)):(this.buffer.ybase++,this._userScrolling||this.buffer.ydisp++)}else{var o=n-r+1;this.buffer.lines.shiftElements(r+1,o-1,-1),this.buffer.lines.set(n,t.clone())}this._userScrolling||(this.buffer.ydisp=this.buffer.ybase),this._dirtyRowService.markRangeDirty(this.buffer.scrollTop,this.buffer.scrollBottom),this._onScroll.fire(this.buffer.ydisp)},t.prototype.scrollLines=function(e,t){if(e<0){if(0===this.buffer.ydisp)return;this._userScrolling=!0}else e+this.buffer.ydisp>=this.buffer.ybase&&(this._userScrolling=!1);var i=this.buffer.ydisp;this.buffer.ydisp=Math.max(Math.min(this.buffer.ydisp+e,this.buffer.ybase),0),i!==this.buffer.ydisp&&(t||this._onScroll.fire(this.buffer.ydisp),this.refresh(0,this.rows-1))},t.prototype.scrollPages=function(e){this.scrollLines(e*(this.rows-1))},t.prototype.scrollToTop=function(){this.scrollLines(-this.buffer.ydisp)},t.prototype.scrollToBottom=function(){this.scrollLines(this.buffer.ybase-this.buffer.ydisp)},t.prototype.scrollToLine=function(e){var t=e-this.buffer.ydisp;0!==t&&this.scrollLines(t)},t.prototype.paste=function(e){a.paste(e,this.textarea,this.bracketedPasteMode,this._coreService)},t.prototype.attachCustomKeyEventHandler=function(e){this._customKeyEventHandler=e},t.prototype.addEscHandler=function(e,t){return this._inputHandler.addEscHandler(e,t)},t.prototype.addDcsHandler=function(e,t){return this._inputHandler.addDcsHandler(e,t)},t.prototype.addCsiHandler=function(e,t){return this._inputHandler.addCsiHandler(e,t)},t.prototype.addOscHandler=function(e,t){return this._inputHandler.addOscHandler(e,t)},t.prototype.registerLinkMatcher=function(e,t,i){var r=this.linkifier.registerLinkMatcher(e,t,i);return this.refresh(0,this.rows-1),r},t.prototype.deregisterLinkMatcher=function(e){this.linkifier.deregisterLinkMatcher(e)&&this.refresh(0,this.rows-1)},t.prototype.registerCharacterJoiner=function(e){var t=this._renderService.registerCharacterJoiner(e);return this.refresh(0,this.rows-1),t},t.prototype.deregisterCharacterJoiner=function(e){this._renderService.deregisterCharacterJoiner(e)&&this.refresh(0,this.rows-1)},Object.defineProperty(t.prototype,"markers",{get:function(){return this.buffer.markers},enumerable:!0,configurable:!0}),t.prototype.addMarker=function(e){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)},t.prototype.hasSelection=function(){return!!this._selectionService&&this._selectionService.hasSelection},t.prototype.select=function(e,t,i){this._selectionService.setSelection(e,t,i)},t.prototype.getSelection=function(){return this._selectionService?this._selectionService.selectionText:""},t.prototype.getSelectionPosition=function(){if(this._selectionService.hasSelection)return{startColumn:this._selectionService.selectionStart[0],startRow:this._selectionService.selectionStart[1],endColumn:this._selectionService.selectionEnd[0],endRow:this._selectionService.selectionEnd[1]}},t.prototype.clearSelection=function(){this._selectionService&&this._selectionService.clearSelection()},t.prototype.selectAll=function(){this._selectionService&&this._selectionService.selectAll()},t.prototype.selectLines=function(e,t){this._selectionService&&this._selectionService.selectLines(e,t)},t.prototype._keyDown=function(e){if(this._keyDownHandled=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(!this._compositionHelper.keydown(e))return this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;var t=b.evaluateKeyboardEvent(e,this._coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===t.type||2===t.type){var i=this.rows-1;return this.scrollLines(2===t.type?-i:i),this.cancel(e,!0)}return 1===t.type&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(t.cancel&&this.cancel(e,!0),!t.key||(t.key!==c.C0.ETX&&t.key!==c.C0.CR||(this.textarea.value=""),this._onKey.fire({key:t.key,domEvent:e}),this.showCursor(),this._coreService.triggerDataEvent(t.key,!0),this.optionsService.options.screenReaderMode?void(this._keyDownHandled=!0):this.cancel(e,!0)))},t.prototype._isThirdLevelShift=function(e,t){var i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey;return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)},t.prototype.setgLevel=function(e){this.glevel=e,this.charset=this.charsets[e]},t.prototype.setgCharset=function(e,t){this.charsets[e]=t,this.glevel===e&&(this.charset=t)},t.prototype._keyUp=function(e){this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e))},t.prototype._keyPress=function(e){var t;if(this._keyDownHandled)return!1;if(this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e))&&(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this.showCursor(),this._coreService.triggerDataEvent(t,!0),!0)},t.prototype.bell=function(){var e=this;this._soundBell()&&this._soundService.playBellSound(),this._visualBell()&&(this.element.classList.add("visual-bell-active"),clearTimeout(this._visualBellTimer),this._visualBellTimer=window.setTimeout(function(){e.element.classList.remove("visual-bell-active")},200))},t.prototype.resize=function(e,t){isNaN(e)||isNaN(t)||(e!==this.cols||t!==this.rows?(e<T.MINIMUM_COLS&&(e=T.MINIMUM_COLS),t<T.MINIMUM_ROWS&&(t=T.MINIMUM_ROWS),this.buffers.resize(e,t),this._bufferService.resize(e,t),this.buffers.setupTabStops(this.cols),this._charSizeService&&this._charSizeService.measure(),this.viewport.syncScrollArea(!0),this.refresh(0,this.rows-1),this._onResize.fire({cols:e,rows:t})):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure())},t.prototype.clear=function(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(var e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(S.DEFAULT_ATTR_DATA));this.refresh(0,this.rows-1),this._onScroll.fire(this.buffer.ydisp)}},t.prototype.is=function(e){return 0===(this.options.termName+"").indexOf(e)},t.prototype.handleTitle=function(e){this._onTitleChange.fire(e)},t.prototype.reset=function(){this.options.rows=this.rows,this.options.cols=this.cols;var e=this._customKeyEventHandler,t=this._inputHandler,i=this.cursorState,r=this._userScrolling;this._setup(),this._bufferService.reset(),this._coreService.reset(),this._coreMouseService.reset(),this._selectionService&&this._selectionService.reset(),this._customKeyEventHandler=e,this._inputHandler=t,this.cursorState=i,this._userScrolling=r,this.refresh(0,this.rows-1),this.viewport&&this.viewport.syncScrollArea()},t.prototype.cancel=function(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1},t.prototype._visualBell=function(){return!1},t.prototype._soundBell=function(){return"sound"===this.options.bellStyle},t.prototype.write=function(e,t){this._writeBuffer.write(e,t)},t.prototype.writeSync=function(e){this._writeBuffer.writeSync(e)},t}(R.Disposable);t.Terminal=W},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(5),o=i(0),a=function(){function e(e,t,i,r,n,s){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=r,this._charSizeService=n,this._coreService=s,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0}}return e.prototype.compositionstart=function(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._compositionView.classList.add("active")},e.prototype.compositionupdate=function(e){var t=this;this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(function(){t._compositionPosition.end=t._textarea.value.length},0)},e.prototype.compositionend=function(){this._finalizeComposition(!0)},e.prototype.keydown=function(e){if(this._isComposing||this._isSendingComposition){if(229===e.keyCode)return!1;if(16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)},e.prototype._finalizeComposition=function(e){var t=this;if(this._compositionView.classList.remove("active"),this._isComposing=!1,this._clearTextareaPosition(),e){var i={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(function(){if(t._isSendingComposition){t._isSendingComposition=!1;var e=void 0;e=t._isComposing?t._textarea.value.substring(i.start,i.end):t._textarea.value.substring(i.start),t._coreService.triggerDataEvent(e,!0)}},0)}else{this._isSendingComposition=!1;var r=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(r,!0)}},e.prototype._handleAnyTextareaChanges=function(){var e=this,t=this._textarea.value;setTimeout(function(){if(!e._isComposing){var i=e._textarea.value.replace(t,"");i.length>0&&e._coreService.triggerDataEvent(i,!0)}},0)},e.prototype.updateCompositionElements=function(e){var t=this;if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){var i=Math.ceil(this._charSizeService.height*this._optionsService.options.lineHeight),r=this._bufferService.buffer.y*i,n=this._bufferService.buffer.x*this._charSizeService.width;this._compositionView.style.left=n+"px",this._compositionView.style.top=r+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.options.fontFamily,this._compositionView.style.fontSize=this._optionsService.options.fontSize+"px";var s=this._compositionView.getBoundingClientRect();this._textarea.style.left=n+"px",this._textarea.style.top=r+"px",this._textarea.style.width=s.width+"px",this._textarea.style.height=s.height+"px",this._textarea.style.lineHeight=s.height+"px"}e||setTimeout(function(){return t.updateCompositionElements(!0)},0)}},e.prototype._clearTextareaPosition=function(){this._textarea.style.left="",this._textarea.style.top=""},e=r([n(2,o.IBufferService),n(3,o.IOptionsService),n(4,s.ICharSizeService),n(5,o.ICoreService)],e)}();t.CompositionHelper=a},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(2),c=i(7),l=i(5),h=i(0),u=15,f=function(e){function t(t,i,r,n,s,o,a){var l=e.call(this)||this;return l._scrollLines=t,l._viewportElement=i,l._scrollArea=r,l._bufferService=n,l._optionsService=s,l._charSizeService=o,l._renderService=a,l.scrollBarWidth=0,l._currentRowHeight=0,l._lastRecordedBufferLength=0,l._lastRecordedViewportHeight=0,l._lastRecordedBufferHeight=0,l._lastTouchY=0,l._lastScrollTop=0,l._wheelPartialScroll=0,l._refreshAnimationFrame=null,l._ignoreNextScrollEvent=!1,l.scrollBarWidth=l._viewportElement.offsetWidth-l._scrollArea.offsetWidth||u,l.register(c.addDisposableDomListener(l._viewportElement,"scroll",l._onScroll.bind(l))),setTimeout(function(){return l.syncScrollArea()},0),l}return n(t,e),t.prototype.onThemeChange=function(e){this._viewportElement.style.backgroundColor=e.background.css},t.prototype._refresh=function(e){var t=this;if(e)return this._innerRefresh(),void(null!==this._refreshAnimationFrame&&cancelAnimationFrame(this._refreshAnimationFrame));null===this._refreshAnimationFrame&&(this._refreshAnimationFrame=requestAnimationFrame(function(){return t._innerRefresh()}))},t.prototype._innerRefresh=function(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.scaledCellHeight/window.devicePixelRatio,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;var e=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.canvasHeight);this._lastRecordedBufferHeight!==e&&(this._lastRecordedBufferHeight=e,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}var t=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==t&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=t),this._refreshAnimationFrame=null},t.prototype.syncScrollArea=function(e){if(void 0===e&&(e=!1),this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(e);if(this._lastRecordedViewportHeight===this._renderService.dimensions.canvasHeight){var t=this._bufferService.buffer.ydisp*this._currentRowHeight;this._lastScrollTop===t&&this._lastScrollTop===this._viewportElement.scrollTop&&this._renderService.dimensions.scaledCellHeight/window.devicePixelRatio===this._currentRowHeight||this._refresh(e)}else this._refresh(e)},t.prototype._onScroll=function(e){if(this._lastScrollTop=this._viewportElement.scrollTop,this._viewportElement.offsetParent)if(this._ignoreNextScrollEvent)this._ignoreNextScrollEvent=!1;else{var t=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._scrollLines(t,!0)}},t.prototype._bubbleScroll=function(e,t){var i=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(t<0&&0!==this._viewportElement.scrollTop||t>0&&i<this._lastRecordedBufferHeight)||(e.cancelable&&e.preventDefault(),!1)},t.prototype.onWheel=function(e){var t=this._getPixelsScrolled(e);return 0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))},t.prototype._getPixelsScrolled=function(e){if(0===e.deltaY)return 0;var t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_LINE?t*=this._currentRowHeight:e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._currentRowHeight*this._bufferService.rows),t},t.prototype.getLinesScrolled=function(e){if(0===e.deltaY)return 0;var t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(t/=this._currentRowHeight+0,this._wheelPartialScroll+=t,t=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._bufferService.rows),t},t.prototype._applyScrollModifier=function(e,t){var i=this._optionsService.options.fastScrollModifier;return"alt"===i&&t.altKey||"ctrl"===i&&t.ctrlKey||"shift"===i&&t.shiftKey?e*this._optionsService.options.fastScrollSensitivity*this._optionsService.options.scrollSensitivity:e*this._optionsService.options.scrollSensitivity},t.prototype.onTouchStart=function(e){this._lastTouchY=e.touches[0].pageY},t.prototype.onTouchMove=function(e){var t=this._lastTouchY-e.touches[0].pageY;return this._lastTouchY=e.touches[0].pageY,0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))},t=s([o(3,h.IBufferService),o(4,h.IOptionsService),o(5,l.ICharSizeService),o(6,l.IRenderService)],t)}(a.Disposable);t.Viewport=f},function(e,t,i){"use strict";function r(e){return e.replace(/\r?\n/g,"\r")}function n(e,t){return t?"\e[200~"+e+"\e[201~":e}function s(e,t,i,s){e=n(e=r(e),i),s.triggerDataEvent(e,!0),t.value=""}function o(e,t,i){var r=i.getBoundingClientRect(),n=e.clientX-r.left-10,s=e.clientY-r.top-10;t.style.position="absolute",t.style.width="20px",t.style.height="20px",t.style.left=n+"px",t.style.top=s+"px",t.style.zIndex="1000",t.focus(),setTimeout(function(){t.style.position=null,t.style.width=null,t.style.height=null,t.style.left=null,t.style.top=null,t.style.zIndex=null},200)}Object.defineProperty(t,"__esModule",{value:!0}),t.prepareTextForTerminal=r,t.bracketTextForPaste=n,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,i,r){e.stopPropagation(),e.clipboardData&&s(e.clipboardData.getData("text/plain"),t,i,r)},t.paste=s,t.moveTextAreaUnderMouseCursor=o,t.rightClickHandler=function(e,t,i,r,n){o(e,t,i),n&&!r.isClickInSelection(e)&&r.selectWordAtCursor(e),t.value=r.selectionText,t.select()}},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(11),o=i(17),a=i(18),c=i(38),l=i(2),h=i(14),u=i(8),f=i(15),_=i(1),d=i(3),p=i(4),v=i(6),g=i(20),y=i(22),m={"(":0,")":1,"*":2,"+":3,"-":1,".":2},b=function(){function e(e,t,i,r){this._bufferService=e,this._coreService=t,this._logService=i,this._optionsService=r,this._data=new Uint32Array(0)}return e.prototype.hook=function(e){this._data=new Uint32Array(0)},e.prototype.put=function(e,t,i){this._data=h.concat(this._data,e.subarray(t,i))},e.prototype.unhook=function(e){if(e){var t=u.utf32ToString(this._data);switch(this._data=new Uint32Array(0),t){case'"q':return this._coreService.triggerDataEvent(s.C0.ESC+'P1$r0"q'+s.C0.ESC+"\\");case'"p':return this._coreService.triggerDataEvent(s.C0.ESC+'P1$r61"p'+s.C0.ESC+"\\");case"r":var i=this._bufferService.buffer.scrollTop+1+";"+(this._bufferService.buffer.scrollBottom+1)+"r";return this._coreService.triggerDataEvent(s.C0.ESC+"P1$r"+i+s.C0.ESC+"\\");case"m":return this._coreService.triggerDataEvent(s.C0.ESC+"P1$r0m"+s.C0.ESC+"\\");case" q":var r={block:2,underline:4,bar:6}[this._optionsService.options.cursorStyle];return r-=this._optionsService.options.cursorBlink?1:0,this._coreService.triggerDataEvent(s.C0.ESC+"P1$r"+r+" q"+s.C0.ESC+"\\");default:this._logService.debug("Unknown DCS $q %s",t),this._coreService.triggerDataEvent(s.C0.ESC+"P0$r"+s.C0.ESC+"\\")}}else this._data=new Uint32Array(0)},e}(),C=function(e){function t(t,i,r,n,a,l,h,f){void 0===f&&(f=new c.EscapeSequenceParser);var d=e.call(this)||this;d._terminal=t,d._bufferService=i,d._coreService=r,d._dirtyRowService=n,d._logService=a,d._optionsService=l,d._coreMouseService=h,d._parser=f,d._parseBuffer=new Uint32Array(4096),d._stringDecoder=new u.StringToUtf32,d._utf8Decoder=new u.Utf8ToUtf32,d._workCell=new p.CellData,d._onCursorMove=new _.EventEmitter,d._onLineFeed=new _.EventEmitter,d._onScroll=new _.EventEmitter,d.register(d._parser),d._parser.setCsiHandlerFallback(function(e,t){d._logService.debug("Unknown CSI code: ",{identifier:d._parser.identToString(e),params:t.toArray()})}),d._parser.setEscHandlerFallback(function(e){d._logService.debug("Unknown ESC code: ",{identifier:d._parser.identToString(e)})}),d._parser.setExecuteHandlerFallback(function(e){d._logService.debug("Unknown EXECUTE code: ",{code:e})}),d._parser.setOscHandlerFallback(function(e,t,i){d._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})}),d._parser.setDcsHandlerFallback(function(e,t,i){"HOOK"===t&&(i=i.toArray()),d._logService.debug("Unknown DCS code: ",{identifier:d._parser.identToString(e),action:t,payload:i})}),d._parser.setPrintHandler(function(e,t,i){return d.print(e,t,i)}),d._parser.setCsiHandler({final:"@"},function(e){return d.insertChars(e)}),d._parser.setCsiHandler({intermediates:" ",final:"@"},function(e){return d.scrollLeft(e)}),d._parser.setCsiHandler({final:"A"},function(e){return d.cursorUp(e)}),d._parser.setCsiHandler({intermediates:" ",final:"A"},function(e){return d.scrollRight(e)}),d._parser.setCsiHandler({final:"B"},function(e){return d.cursorDown(e)}),d._parser.setCsiHandler({final:"C"},function(e){return d.cursorForward(e)}),d._parser.setCsiHandler({final:"D"},function(e){return d.cursorBackward(e)}),d._parser.setCsiHandler({final:"E"},function(e){return d.cursorNextLine(e)}),d._parser.setCsiHandler({final:"F"},function(e){return d.cursorPrecedingLine(e)}),d._parser.setCsiHandler({final:"G"},function(e){return d.cursorCharAbsolute(e)}),d._parser.setCsiHandler({final:"H"},function(e){return d.cursorPosition(e)}),d._parser.setCsiHandler({final:"I"},function(e){return d.cursorForwardTab(e)}),d._parser.setCsiHandler({final:"J"},function(e){return d.eraseInDisplay(e)}),d._parser.setCsiHandler({prefix:"?",final:"J"},function(e){return d.eraseInDisplay(e)}),d._parser.setCsiHandler({final:"K"},function(e){return d.eraseInLine(e)}),d._parser.setCsiHandler({prefix:"?",final:"K"},function(e){return d.eraseInLine(e)}),d._parser.setCsiHandler({final:"L"},function(e){return d.insertLines(e)}),d._parser.setCsiHandler({final:"M"},function(e){return d.deleteLines(e)}),d._parser.setCsiHandler({final:"P"},function(e){return d.deleteChars(e)}),d._parser.setCsiHandler({final:"S"},function(e){return d.scrollUp(e)}),d._parser.setCsiHandler({final:"T"},function(e){return d.scrollDown(e)}),d._parser.setCsiHandler({final:"X"},function(e){return d.eraseChars(e)}),d._parser.setCsiHandler({final:"Z"},function(e){return d.cursorBackwardTab(e)}),d._parser.setCsiHandler({final:"`"},function(e){return d.charPosAbsolute(e)}),d._parser.setCsiHandler({final:"a"},function(e){return d.hPositionRelative(e)}),d._parser.setCsiHandler({final:"b"},function(e){return d.repeatPrecedingCharacter(e)}),d._parser.setCsiHandler({final:"c"},function(e){return d.sendDeviceAttributesPrimary(e)}),d._parser.setCsiHandler({prefix:">",final:"c"},function(e){return d.sendDeviceAttributesSecondary(e)}),d._parser.setCsiHandler({final:"d"},function(e){return d.linePosAbsolute(e)}),d._parser.setCsiHandler({final:"e"},function(e){return d.vPositionRelative(e)}),d._parser.setCsiHandler({final:"f"},function(e){return d.hVPosition(e)}),d._parser.setCsiHandler({final:"g"},function(e){return d.tabClear(e)}),d._parser.setCsiHandler({final:"h"},function(e){return d.setMode(e)}),d._parser.setCsiHandler({prefix:"?",final:"h"},function(e){return d.setModePrivate(e)}),d._parser.setCsiHandler({final:"l"},function(e){return d.resetMode(e)}),d._parser.setCsiHandler({prefix:"?",final:"l"},function(e){return d.resetModePrivate(e)}),d._parser.setCsiHandler({final:"m"},function(e){return d.charAttributes(e)}),d._parser.setCsiHandler({final:"n"},function(e){return d.deviceStatus(e)}),d._parser.setCsiHandler({prefix:"?",final:"n"},function(e){return d.deviceStatusPrivate(e)}),d._parser.setCsiHandler({intermediates:"!",final:"p"},function(e){return d.softReset(e)}),d._parser.setCsiHandler({intermediates:" ",final:"q"},function(e){return d.setCursorStyle(e)}),d._parser.setCsiHandler({final:"r"},function(e){return d.setScrollRegion(e)}),d._parser.setCsiHandler({final:"s"},function(e){return d.saveCursor(e)}),d._parser.setCsiHandler({final:"u"},function(e){return d.restoreCursor(e)}),d._parser.setCsiHandler({intermediates:"'",final:"}"},function(e){return d.insertColumns(e)}),d._parser.setCsiHandler({intermediates:"'",final:"~"},function(e){return d.deleteColumns(e)}),d._parser.setExecuteHandler(s.C0.BEL,function(){return d.bell()}),d._parser.setExecuteHandler(s.C0.LF,function(){return d.lineFeed()}),d._parser.setExecuteHandler(s.C0.VT,function(){return d.lineFeed()}),d._parser.setExecuteHandler(s.C0.FF,function(){return d.lineFeed()}),d._parser.setExecuteHandler(s.C0.CR,function(){return d.carriageReturn()}),d._parser.setExecuteHandler(s.C0.BS,function(){return d.backspace()}),d._parser.setExecuteHandler(s.C0.HT,function(){return d.tab()}),d._parser.setExecuteHandler(s.C0.SO,function(){return d.shiftOut()}),d._parser.setExecuteHandler(s.C0.SI,function(){return d.shiftIn()}),d._parser.setExecuteHandler(s.C1.IND,function(){return d.index()}),d._parser.setExecuteHandler(s.C1.NEL,function(){return d.nextLine()}),d._parser.setExecuteHandler(s.C1.HTS,function(){return d.tabSet()}),d._parser.setOscHandler(0,new g.OscHandler(function(e){return d.setTitle(e)})),d._parser.setOscHandler(2,new g.OscHandler(function(e){return d.setTitle(e)})),d._parser.setEscHandler({final:"7"},function(){return d.saveCursor()}),d._parser.setEscHandler({final:"8"},function(){return d.restoreCursor()}),d._parser.setEscHandler({final:"D"},function(){return d.index()}),d._parser.setEscHandler({final:"E"},function(){return d.nextLine()}),d._parser.setEscHandler({final:"H"},function(){return d.tabSet()}),d._parser.setEscHandler({final:"M"},function(){return d.reverseIndex()}),d._parser.setEscHandler({final:"="},function(){return d.keypadApplicationMode()}),d._parser.setEscHandler({final:">"},function(){return d.keypadNumericMode()}),d._parser.setEscHandler({final:"c"},function(){return d.reset()}),d._parser.setEscHandler({final:"n"},function(){return d.setgLevel(2)}),d._parser.setEscHandler({final:"o"},function(){return d.setgLevel(3)}),d._parser.setEscHandler({final:"|"},function(){return d.setgLevel(3)}),d._parser.setEscHandler({final:"}"},function(){return d.setgLevel(2)}),d._parser.setEscHandler({final:"~"},function(){return d.setgLevel(1)}),d._parser.setEscHandler({intermediates:"%",final:"@"},function(){return d.selectDefaultCharset()}),d._parser.setEscHandler({intermediates:"%",final:"G"},function(){return d.selectDefaultCharset()});var v=function(e){y._parser.setEscHandler({intermediates:"(",final:e},function(){return d.selectCharset("("+e)}),y._parser.setEscHandler({intermediates:")",final:e},function(){return d.selectCharset(")"+e)}),y._parser.setEscHandler({intermediates:"*",final:e},function(){return d.selectCharset("*"+e)}),y._parser.setEscHandler({intermediates:"+",final:e},function(){return d.selectCharset("+"+e)}),y._parser.setEscHandler({intermediates:"-",final:e},function(){return d.selectCharset("-"+e)}),y._parser.setEscHandler({intermediates:".",final:e},function(){return d.selectCharset("."+e)}),y._parser.setEscHandler({intermediates:"/",final:e},function(){return d.selectCharset("/"+e)})},y=this;for(var m in o.CHARSETS)v(m);return d._parser.setEscHandler({intermediates:"#",final:"8"},function(){return d.screenAlignmentPattern()}),d._parser.setErrorHandler(function(e){return d._logService.error("Parsing error: ",e),e}),d._parser.setDcsHandler({intermediates:"$",final:"q"},new b(d._bufferService,d._coreService,d._logService,d._optionsService)),d}return n(t,e),Object.defineProperty(t.prototype,"onCursorMove",{get:function(){return this._onCursorMove.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onLineFeed",{get:function(){return this._onLineFeed.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.parse=function(e){var t=this._bufferService.buffer,i=t.x,r=t.y;if(this._logService.debug("parsing data",e),this._parseBuffer.length<e.length&&this._parseBuffer.length<131072&&(this._parseBuffer=new Uint32Array(Math.min(e.length,131072))),e.length>131072)for(var n=0;n<e.length;n+=131072){var s=n+131072<e.length?n+131072:e.length,o="string"==typeof e?this._stringDecoder.decode(e.substring(n,s),this._parseBuffer):this._utf8Decoder.decode(e.subarray(n,s),this._parseBuffer);this._parser.parse(this._parseBuffer,o)}else{o="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);this._parser.parse(this._parseBuffer,o)}(t=this._bufferService.buffer).x===i&&t.y===r||this._onCursorMove.fire(),this._terminal.refresh(this._dirtyRowService.start,this._dirtyRowService.end)},t.prototype.print=function(e,t,i){var r,n,s=this._bufferService.buffer,o=this._terminal.charset,c=this._optionsService.options.screenReaderMode,l=this._bufferService.cols,h=this._terminal.wraparoundMode,f=this._terminal.insertMode,_=this._terminal.curAttrData,p=s.lines.get(s.y+s.ybase);this._dirtyRowService.markDirty(s.y);for(var v=t;v<i;++v){if(r=e[v],n=a.wcwidth(r),r<127&&o){var g=o[String.fromCharCode(r)];g&&(r=g.charCodeAt(0))}if(c&&this._terminal.onA11yCharEmitter.fire(u.stringFromCodePoint(r)),n||!s.x){if(s.x+n-1>=l)if(h)s.x=0,s.y++,s.y===s.scrollBottom+1?(s.y--,this._terminal.scroll(!0)):(s.y>=this._bufferService.rows&&(s.y=this._bufferService.rows-1),s.lines.get(s.y).isWrapped=!0),p=s.lines.get(s.y+s.ybase);else if(s.x=l-1,2===n)continue;if(f&&(p.insertCells(s.x,n,s.getNullCell(_)),2===p.getWidth(l-1)&&p.setCellFromCodePoint(l-1,d.NULL_CELL_CODE,d.NULL_CELL_WIDTH,_.fg,_.bg)),p.setCellFromCodePoint(s.x++,r,n,_.fg,_.bg),n>0)for(;--n;)p.setCellFromCodePoint(s.x++,0,0,_.fg,_.bg)}else p.getWidth(s.x-1)?p.addCodepointToCell(s.x-1,r):p.addCodepointToCell(s.x-2,r)}i&&(p.loadCell(s.x-1,this._workCell),2===this._workCell.getWidth()||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._dirtyRowService.markDirty(s.y)},t.prototype.addCsiHandler=function(e,t){return this._parser.addCsiHandler(e,t)},t.prototype.addDcsHandler=function(e,t){return this._parser.addDcsHandler(e,new y.DcsHandler(t))},t.prototype.addEscHandler=function(e,t){return this._parser.addEscHandler(e,t)},t.prototype.addOscHandler=function(e,t){return this._parser.addOscHandler(e,new g.OscHandler(t))},t.prototype.bell=function(){this._terminal.bell()},t.prototype.lineFeed=function(){var e=this._bufferService.buffer;this._optionsService.options.convertEol&&(e.x=0),e.y++,e.y===e.scrollBottom+1?(e.y--,this._terminal.scroll()):e.y>=this._bufferService.rows&&(e.y=this._bufferService.rows-1),e.x>=this._bufferService.cols&&e.x--,this._onLineFeed.fire()},t.prototype.carriageReturn=function(){this._bufferService.buffer.x=0},t.prototype.backspace=function(){this._restrictCursor(),this._bufferService.buffer.x>0&&this._bufferService.buffer.x--},t.prototype.tab=function(){if(!(this._bufferService.buffer.x>=this._bufferService.cols)){var e=this._bufferService.buffer.x;this._bufferService.buffer.x=this._bufferService.buffer.nextStop(),this._optionsService.options.screenReaderMode&&this._terminal.onA11yTabEmitter.fire(this._bufferService.buffer.x-e)}},t.prototype.shiftOut=function(){this._terminal.setgLevel(1)},t.prototype.shiftIn=function(){this._terminal.setgLevel(0)},t.prototype._restrictCursor=function(){this._bufferService.buffer.x=Math.min(this._bufferService.cols-1,Math.max(0,this._bufferService.buffer.x)),this._bufferService.buffer.y=this._terminal.originMode?Math.min(this._bufferService.buffer.scrollBottom,Math.max(this._bufferService.buffer.scrollTop,this._bufferService.buffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._bufferService.buffer.y))},t.prototype._setCursor=function(e,t){this._terminal.originMode?(this._bufferService.buffer.x=e,this._bufferService.buffer.y=this._bufferService.buffer.scrollTop+t):(this._bufferService.buffer.x=e,this._bufferService.buffer.y=t),this._restrictCursor()},t.prototype._moveCursor=function(e,t){this._restrictCursor(),this._setCursor(this._bufferService.buffer.x+e,this._bufferService.buffer.y+t)},t.prototype.cursorUp=function(e){var t=this._bufferService.buffer.y-this._bufferService.buffer.scrollTop;t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1))},t.prototype.cursorDown=function(e){var t=this._bufferService.buffer.scrollBottom-this._bufferService.buffer.y;t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1)},t.prototype.cursorForward=function(e){this._moveCursor(e.params[0]||1,0)},t.prototype.cursorBackward=function(e){this._moveCursor(-(e.params[0]||1),0)},t.prototype.cursorNextLine=function(e){this.cursorDown(e),this._bufferService.buffer.x=0},t.prototype.cursorPrecedingLine=function(e){this.cursorUp(e),this._bufferService.buffer.x=0},t.prototype.cursorCharAbsolute=function(e){this._setCursor((e.params[0]||1)-1,this._bufferService.buffer.y)},t.prototype.cursorPosition=function(e){this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1)},t.prototype.charPosAbsolute=function(e){this._setCursor((e.params[0]||1)-1,this._bufferService.buffer.y)},t.prototype.hPositionRelative=function(e){this._moveCursor(e.params[0]||1,0)},t.prototype.linePosAbsolute=function(e){this._setCursor(this._bufferService.buffer.x,(e.params[0]||1)-1)},t.prototype.vPositionRelative=function(e){this._moveCursor(0,e.params[0]||1)},t.prototype.hVPosition=function(e){this.cursorPosition(e)},t.prototype.tabClear=function(e){var t=e.params[0];0===t?delete this._bufferService.buffer.tabs[this._bufferService.buffer.x]:3===t&&(this._bufferService.buffer.tabs={})},t.prototype.cursorForwardTab=function(e){if(!(this._bufferService.buffer.x>=this._bufferService.cols))for(var t=e.params[0]||1;t--;)this._bufferService.buffer.x=this._bufferService.buffer.nextStop()},t.prototype.cursorBackwardTab=function(e){if(!(this._bufferService.buffer.x>=this._bufferService.cols))for(var t=e.params[0]||1,i=this._bufferService.buffer;t--;)i.x=i.prevStop()},t.prototype._eraseInBufferLine=function(e,t,i,r){void 0===r&&(r=!1);var n=this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase+e);n.replaceCells(t,i,this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),r&&(n.isWrapped=!1)},t.prototype._resetBufferLine=function(e){var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase+e);t.fill(this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),t.isWrapped=!1},t.prototype.eraseInDisplay=function(e){var t;switch(this._restrictCursor(),e.params[0]){case 0:for(t=this._bufferService.buffer.y,this._dirtyRowService.markDirty(t),this._eraseInBufferLine(t++,this._bufferService.buffer.x,this._bufferService.cols,0===this._bufferService.buffer.x);t<this._bufferService.rows;t++)this._resetBufferLine(t);this._dirtyRowService.markDirty(t);break;case 1:for(t=this._bufferService.buffer.y,this._dirtyRowService.markDirty(t),this._eraseInBufferLine(t,0,this._bufferService.buffer.x+1,!0),this._bufferService.buffer.x+1>=this._bufferService.cols&&(this._bufferService.buffer.lines.get(t+1).isWrapped=!1);t--;)this._resetBufferLine(t);this._dirtyRowService.markDirty(0);break;case 2:for(t=this._bufferService.rows,this._dirtyRowService.markDirty(t-1);t--;)this._resetBufferLine(t);this._dirtyRowService.markDirty(0);break;case 3:var i=this._bufferService.buffer.lines.length-this._bufferService.rows;i>0&&(this._bufferService.buffer.lines.trimStart(i),this._bufferService.buffer.ybase=Math.max(this._bufferService.buffer.ybase-i,0),this._bufferService.buffer.ydisp=Math.max(this._bufferService.buffer.ydisp-i,0),this._onScroll.fire(0))}},t.prototype.eraseInLine=function(e){switch(this._restrictCursor(),e.params[0]){case 0:this._eraseInBufferLine(this._bufferService.buffer.y,this._bufferService.buffer.x,this._bufferService.cols);break;case 1:this._eraseInBufferLine(this._bufferService.buffer.y,0,this._bufferService.buffer.x+1);break;case 2:this._eraseInBufferLine(this._bufferService.buffer.y,0,this._bufferService.cols)}this._dirtyRowService.markDirty(this._bufferService.buffer.y)},t.prototype.insertLines=function(e){this._restrictCursor();var t=e.params[0]||1,i=this._bufferService.buffer;if(!(i.y>i.scrollBottom||i.y<i.scrollTop)){for(var r=i.y+i.ybase,n=this._bufferService.rows-1-i.scrollBottom,s=this._bufferService.rows-1+i.ybase-n+1;t--;)i.lines.splice(s-1,1),i.lines.splice(r,0,i.getBlankLine(this._terminal.eraseAttrData()));this._dirtyRowService.markRangeDirty(i.y,i.scrollBottom),i.x=0}},t.prototype.deleteLines=function(e){this._restrictCursor();var t=e.params[0]||1,i=this._bufferService.buffer;if(!(i.y>i.scrollBottom||i.y<i.scrollTop)){var r,n=i.y+i.ybase;for(r=this._bufferService.rows-1-i.scrollBottom,r=this._bufferService.rows-1+i.ybase-r;t--;)i.lines.splice(n,1),i.lines.splice(r,0,i.getBlankLine(this._terminal.eraseAttrData()));this._dirtyRowService.markRangeDirty(i.y,i.scrollBottom),i.x=0}},t.prototype.insertChars=function(e){this._restrictCursor();var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.y+this._bufferService.buffer.ybase);t&&(t.insertCells(this._bufferService.buffer.x,e.params[0]||1,this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),this._dirtyRowService.markDirty(this._bufferService.buffer.y))},t.prototype.deleteChars=function(e){this._restrictCursor();var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.y+this._bufferService.buffer.ybase);t&&(t.deleteCells(this._bufferService.buffer.x,e.params[0]||1,this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),this._dirtyRowService.markDirty(this._bufferService.buffer.y))},t.prototype.scrollUp=function(e){for(var t=e.params[0]||1,i=this._bufferService.buffer;t--;)i.lines.splice(i.ybase+i.scrollTop,1),i.lines.splice(i.ybase+i.scrollBottom,0,i.getBlankLine(this._terminal.eraseAttrData()));this._dirtyRowService.markRangeDirty(i.scrollTop,i.scrollBottom)},t.prototype.scrollDown=function(e){for(var t=e.params[0]||1,i=this._bufferService.buffer;t--;)i.lines.splice(i.ybase+i.scrollBottom,1),i.lines.splice(i.ybase+i.scrollTop,0,i.getBlankLine(f.DEFAULT_ATTR_DATA));this._dirtyRowService.markRangeDirty(i.scrollTop,i.scrollBottom)},t.prototype.scrollLeft=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=t.lines.get(t.ybase+r);n.deleteCells(0,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.scrollRight=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=t.lines.get(t.ybase+r);n.insertCells(0,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.insertColumns=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=this._bufferService.buffer.lines.get(t.ybase+r);n.insertCells(t.x,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.deleteColumns=function(e){var t=this._bufferService.buffer;if(!(t.y>t.scrollBottom||t.y<t.scrollTop)){for(var i=e.params[0]||1,r=t.scrollTop;r<=t.scrollBottom;++r){var n=t.lines.get(t.ybase+r);n.deleteCells(t.x,i,t.getNullCell(this._terminal.eraseAttrData())),n.isWrapped=!1}this._dirtyRowService.markRangeDirty(t.scrollTop,t.scrollBottom)}},t.prototype.eraseChars=function(e){this._restrictCursor();var t=this._bufferService.buffer.lines.get(this._bufferService.buffer.y+this._bufferService.buffer.ybase);t&&(t.replaceCells(this._bufferService.buffer.x,this._bufferService.buffer.x+(e.params[0]||1),this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())),this._dirtyRowService.markDirty(this._bufferService.buffer.y))},t.prototype.repeatPrecedingCharacter=function(e){if(this._parser.precedingCodepoint){for(var t=e.params[0]||1,i=new Uint32Array(t),r=0;r<t;++r)i[r]=this._parser.precedingCodepoint;this.print(i,0,i.length)}},t.prototype.sendDeviceAttributesPrimary=function(e){e.params[0]>0||(this._terminal.is("xterm")||this._terminal.is("rxvt-unicode")||this._terminal.is("screen")?this._coreService.triggerDataEvent(s.C0.ESC+"[?1;2c"):this._terminal.is("linux")&&this._coreService.triggerDataEvent(s.C0.ESC+"[?6c"))},t.prototype.sendDeviceAttributesSecondary=function(e){e.params[0]>0||(this._terminal.is("xterm")?this._coreService.triggerDataEvent(s.C0.ESC+"[>0;276;0c"):this._terminal.is("rxvt-unicode")?this._coreService.triggerDataEvent(s.C0.ESC+"[>85;95;0c"):this._terminal.is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._terminal.is("screen")&&this._coreService.triggerDataEvent(s.C0.ESC+"[>83;40003;0c"))},t.prototype.setMode=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 4:this._terminal.insertMode=!0}},t.prototype.setModePrivate=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._terminal.setgCharset(0,o.DEFAULT_CHARSET),this._terminal.setgCharset(1,o.DEFAULT_CHARSET),this._terminal.setgCharset(2,o.DEFAULT_CHARSET),this._terminal.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._terminal.savedCols=this._bufferService.cols,this._terminal.resize(132,this._bufferService.rows),this._terminal.reset();break;case 6:this._terminal.originMode=!0,this._setCursor(0,0);break;case 7:this._terminal.wraparoundMode=!0;break;case 12:break;case 66:this._logService.debug("Serial port requested application keypad."),this._terminal.applicationKeypad=!0,this._terminal.viewport&&this._terminal.viewport.syncScrollArea();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._terminal.sendFocus=!0;break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 25:this._terminal.cursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._terminal.eraseAttrData()),this._terminal.refresh(0,this._bufferService.rows-1),this._terminal.viewport&&this._terminal.viewport.syncScrollArea(),this._terminal.showCursor();break;case 2004:this._terminal.bracketedPasteMode=!0}},t.prototype.resetMode=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 4:this._terminal.insertMode=!1}},t.prototype.resetModePrivate=function(e){for(var t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:132===this._bufferService.cols&&this._terminal.savedCols&&this._terminal.resize(this._terminal.savedCols,this._bufferService.rows),delete this._terminal.savedCols,this._terminal.reset();break;case 6:this._terminal.originMode=!1,this._setCursor(0,0);break;case 7:this._terminal.wraparoundMode=!1;break;case 12:break;case 66:this._logService.debug("Switching back to normal keypad."),this._terminal.applicationKeypad=!1,this._terminal.viewport&&this._terminal.viewport.syncScrollArea();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._terminal.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._terminal.cursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[t]&&this.restoreCursor(),this._terminal.refresh(0,this._bufferService.rows-1),this._terminal.viewport&&this._terminal.viewport.syncScrollArea(),this._terminal.showCursor();break;case 2004:this._terminal.bracketedPasteMode=!1}},t.prototype._extractColor=function(e,t,i){var r=[0,0,-1,0,0,0],n=0,s=0;do{if(r[s+n]=e.params[t+s],e.hasSubParams(t+s)){var o=e.getSubParams(t+s),a=0;do{5===r[1]&&(n=1),r[s+a+1+n]=o[a]}while(++a<o.length&&a+s+1+n<r.length);break}if(5===r[1]&&s+n>=2||2===r[1]&&s+n>=5)break;r[1]&&(n=1)}while(++s+t<e.length&&s+n<r.length);for(a=2;a<r.length;++a)-1===r[a]&&(r[a]=0);return 38===r[0]?2===r[1]?(i.fg|=50331648,i.fg&=-16777216,i.fg|=v.AttributeData.fromColorRGB([r[3],r[4],r[5]])):5===r[1]&&(i.fg&=-50331904,i.fg|=33554432|255&r[3]):48===r[0]&&(2===r[1]?(i.bg|=50331648,i.bg&=-16777216,i.bg|=v.AttributeData.fromColorRGB([r[3],r[4],r[5]])):5===r[1]&&(i.bg&=-50331904,i.bg|=33554432|255&r[3])),s},t.prototype.charAttributes=function(e){if(1===e.length&&0===e.params[0])return this._terminal.curAttrData.fg=f.DEFAULT_ATTR_DATA.fg,void(this._terminal.curAttrData.bg=f.DEFAULT_ATTR_DATA.bg);for(var t,i=e.length,r=this._terminal.curAttrData,n=0;n<i;n++)(t=e.params[n])>=30&&t<=37?(r.fg&=-50331904,r.fg|=16777216|t-30):t>=40&&t<=47?(r.bg&=-50331904,r.bg|=16777216|t-40):t>=90&&t<=97?(r.fg&=-50331904,r.fg|=16777224|t-90):t>=100&&t<=107?(r.bg&=-50331904,r.bg|=16777224|t-100):0===t?(r.fg=f.DEFAULT_ATTR_DATA.fg,r.bg=f.DEFAULT_ATTR_DATA.bg):1===t?r.fg|=134217728:3===t?r.bg|=67108864:4===t?r.fg|=268435456:5===t?r.fg|=536870912:7===t?r.fg|=67108864:8===t?r.fg|=1073741824:2===t?r.bg|=134217728:22===t?(r.fg&=-134217729,r.bg&=-134217729):23===t?r.bg&=-67108865:24===t?r.fg&=-268435457:25===t?r.fg&=-536870913:27===t?r.fg&=-67108865:28===t?r.fg&=-1073741825:39===t?(r.fg&=-67108864,r.fg|=16777215&f.DEFAULT_ATTR_DATA.fg):49===t?(r.bg&=-67108864,r.bg|=16777215&f.DEFAULT_ATTR_DATA.bg):38===t||48===t?n+=this._extractColor(e,n,r):100===t?(r.fg&=-67108864,r.fg|=16777215&f.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&f.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",t)},t.prototype.deviceStatus=function(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(s.C0.ESC+"[0n");break;case 6:var t=this._bufferService.buffer.y+1,i=this._bufferService.buffer.x+1;this._coreService.triggerDataEvent(s.C0.ESC+"["+t+";"+i+"R")}},t.prototype.deviceStatusPrivate=function(e){switch(e.params[0]){case 6:var t=this._bufferService.buffer.y+1,i=this._bufferService.buffer.x+1;this._coreService.triggerDataEvent(s.C0.ESC+"[?"+t+";"+i+"R")}},t.prototype.softReset=function(e){this._terminal.cursorHidden=!1,this._terminal.insertMode=!1,this._terminal.originMode=!1,this._terminal.wraparoundMode=!0,this._terminal.applicationKeypad=!1,this._terminal.viewport&&this._terminal.viewport.syncScrollArea(),this._coreService.decPrivateModes.applicationCursorKeys=!1,this._bufferService.buffer.scrollTop=0,this._bufferService.buffer.scrollBottom=this._bufferService.rows-1,this._terminal.curAttrData=f.DEFAULT_ATTR_DATA.clone(),this._bufferService.buffer.x=this._bufferService.buffer.y=0,this._terminal.charset=null,this._terminal.glevel=0,this._terminal.charsets=[null]},t.prototype.setCursorStyle=function(e){var t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}var i=t%2==1;this._optionsService.options.cursorBlink=i},t.prototype.setScrollRegion=function(e){var t,i=e.params[0]||1;(e.length<2||(t=e.params[1])>this._bufferService.rows||0===t)&&(t=this._bufferService.rows),t>i&&(this._bufferService.buffer.scrollTop=i-1,this._bufferService.buffer.scrollBottom=t-1,this._setCursor(0,0))},t.prototype.saveCursor=function(e){this._bufferService.buffer.savedX=this._bufferService.buffer.x,this._bufferService.buffer.savedY=this._bufferService.buffer.ybase+this._bufferService.buffer.y,this._bufferService.buffer.savedCurAttrData.fg=this._terminal.curAttrData.fg,this._bufferService.buffer.savedCurAttrData.bg=this._terminal.curAttrData.bg,this._bufferService.buffer.savedCharset=this._terminal.charset},t.prototype.restoreCursor=function(e){this._bufferService.buffer.x=this._bufferService.buffer.savedX||0,this._bufferService.buffer.y=Math.max(this._bufferService.buffer.savedY-this._bufferService.buffer.ybase,0),this._terminal.curAttrData.fg=this._bufferService.buffer.savedCurAttrData.fg,this._terminal.curAttrData.bg=this._bufferService.buffer.savedCurAttrData.bg,this._terminal.charset=this._savedCharset,this._bufferService.buffer.savedCharset&&(this._terminal.charset=this._bufferService.buffer.savedCharset),this._restrictCursor()},t.prototype.setTitle=function(e){this._terminal.handleTitle(e)},t.prototype.nextLine=function(){this._bufferService.buffer.x=0,this.index()},t.prototype.keypadApplicationMode=function(){this._logService.debug("Serial port requested application keypad."),this._terminal.applicationKeypad=!0,this._terminal.viewport&&this._terminal.viewport.syncScrollArea()},t.prototype.keypadNumericMode=function(){this._logService.debug("Switching back to normal keypad."),this._terminal.applicationKeypad=!1,this._terminal.viewport&&this._terminal.viewport.syncScrollArea()},t.prototype.selectDefaultCharset=function(){this._terminal.setgLevel(0),this._terminal.setgCharset(0,o.DEFAULT_CHARSET)},t.prototype.selectCharset=function(e){2===e.length?"/"!==e[0]&&this._terminal.setgCharset(m[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET):this.selectDefaultCharset()},t.prototype.index=function(){this._restrictCursor();var e=this._bufferService.buffer;this._bufferService.buffer.y++,e.y===e.scrollBottom+1?(e.y--,this._terminal.scroll()):e.y>=this._bufferService.rows&&(e.y=this._bufferService.rows-1),this._restrictCursor()},t.prototype.tabSet=function(){this._bufferService.buffer.tabs[this._bufferService.buffer.x]=!0},t.prototype.reverseIndex=function(){this._restrictCursor();var e=this._bufferService.buffer;if(e.y===e.scrollTop){var t=e.scrollBottom-e.scrollTop;e.lines.shiftElements(e.y+e.ybase,t,1),e.lines.set(e.y+e.ybase,e.getBlankLine(this._terminal.eraseAttrData())),this._dirtyRowService.markRangeDirty(e.scrollTop,e.scrollBottom)}else e.y--,this._restrictCursor()},t.prototype.reset=function(){this._parser.reset(),this._terminal.reset()},t.prototype.setgLevel=function(e){this._terminal.setgLevel(e)},t.prototype.screenAlignmentPattern=function(){var e=new p.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._terminal.curAttrData.fg,e.bg=this._terminal.curAttrData.bg;var t=this._bufferService.buffer;this._setCursor(0,0);for(var i=0;i<this._bufferService.rows;++i){var r=t.y+t.ybase+i;t.lines.get(r).fill(e),t.lines.get(r).isWrapped=!1}this._dirtyRowService.markAllDirty(),this._setCursor(0,0)},t}(l.Disposable);t.InputHandler=C},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(2),o=i(14),a=i(19),c=i(20),l=i(22),h=function(){function e(e){this.table=new Uint8Array(e)}return e.prototype.setDefault=function(e,t){o.fill(this.table,e<<4|t)},e.prototype.add=function(e,t,i,r){this.table[t<<8|e]=i<<4|r},e.prototype.addMany=function(e,t,i,r){for(var n=0;n<e.length;n++)this.table[t<<8|e[n]]=i<<4|r},e}();t.TransitionTable=h;t.VT500_TRANSITION_TABLE=function(){var e=new h(4095),t=Array.apply(null,Array(256)).map(function(e,t){return t}),i=function(e,i){return t.slice(e,i)},r=i(32,127),n=i(0,24);n.push(25),n.push.apply(n,i(28,32));var s,o=i(0,14);for(s in e.setDefault(1,0),e.addMany(r,0,2,0),o)e.addMany([24,26,153,154],s,3,0),e.addMany(i(128,144),s,3,0),e.addMany(i(144,152),s,3,0),e.add(156,s,0,0),e.add(27,s,11,1),e.add(157,s,4,8),e.addMany([152,158,159],s,0,7),e.add(155,s,11,3),e.add(144,s,11,9);return e.addMany(n,0,3,0),e.addMany(n,1,3,1),e.add(127,1,0,1),e.addMany(n,8,0,8),e.addMany(n,3,3,3),e.add(127,3,0,3),e.addMany(n,4,3,4),e.add(127,4,0,4),e.addMany(n,6,3,6),e.addMany(n,5,3,5),e.add(127,5,0,5),e.addMany(n,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(n,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(n,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(n,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(n,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(n,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(n,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}();var u=function(e){function i(i){void 0===i&&(i=t.VT500_TRANSITION_TABLE);var r=e.call(this)||this;return r.TRANSITIONS=i,r.initialState=0,r.currentState=r.initialState,r._params=new a.Params,r._params.addParam(0),r._collect=0,r.precedingCodepoint=0,r._printHandlerFb=function(e,t,i){},r._executeHandlerFb=function(e){},r._csiHandlerFb=function(e,t){},r._escHandlerFb=function(e){},r._errorHandlerFb=function(e){return e},r._printHandler=r._printHandlerFb,r._executeHandlers=Object.create(null),r._csiHandlers=Object.create(null),r._escHandlers=Object.create(null),r._oscParser=new c.OscParser,r._dcsParser=new l.DcsParser,r._errorHandler=r._errorHandlerFb,r.setEscHandler({final:"\\"},function(){}),r}return n(i,e),i.prototype._identifier=function(e,t){void 0===t&&(t=[64,126]);var i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if((i=e.prefix.charCodeAt(0))&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(var r=0;r<e.intermediates.length;++r){var n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=n}}if(1!==e.final.length)throw new Error("final must be a single byte");var s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error("final must be in range "+t[0]+" .. "+t[1]);return i<<=8,i|=s},i.prototype.identToString=function(e){for(var t=[];e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")},i.prototype.dispose=function(){this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null),this._oscParser.dispose(),this._dcsParser.dispose()},i.prototype.setPrintHandler=function(e){this._printHandler=e},i.prototype.clearPrintHandler=function(){this._printHandler=this._printHandlerFb},i.prototype.addEscHandler=function(e,t){var i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);var r=this._escHandlers[i];return r.push(t),{dispose:function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}}},i.prototype.setEscHandler=function(e,t){this._escHandlers[this._identifier(e,[48,126])]=[t]},i.prototype.clearEscHandler=function(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]},i.prototype.setEscHandlerFallback=function(e){this._escHandlerFb=e},i.prototype.setExecuteHandler=function(e,t){this._executeHandlers[e.charCodeAt(0)]=t},i.prototype.clearExecuteHandler=function(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]},i.prototype.setExecuteHandlerFallback=function(e){this._executeHandlerFb=e},i.prototype.addCsiHandler=function(e,t){var i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);var r=this._csiHandlers[i];return r.push(t),{dispose:function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)}}},i.prototype.setCsiHandler=function(e,t){this._csiHandlers[this._identifier(e)]=[t]},i.prototype.clearCsiHandler=function(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]},i.prototype.setCsiHandlerFallback=function(e){this._csiHandlerFb=e},i.prototype.addDcsHandler=function(e,t){return this._dcsParser.addHandler(this._identifier(e),t)},i.prototype.setDcsHandler=function(e,t){this._dcsParser.setHandler(this._identifier(e),t)},i.prototype.clearDcsHandler=function(e){this._dcsParser.clearHandler(this._identifier(e))},i.prototype.setDcsHandlerFallback=function(e){this._dcsParser.setHandlerFallback(e)},i.prototype.addOscHandler=function(e,t){return this._oscParser.addHandler(e,t)},i.prototype.setOscHandler=function(e,t){this._oscParser.setHandler(e,t)},i.prototype.clearOscHandler=function(e){this._oscParser.clearHandler(e)},i.prototype.setOscHandlerFallback=function(e){this._oscParser.setHandlerFallback(e)},i.prototype.setErrorHandler=function(e){this._errorHandler=e},i.prototype.clearErrorHandler=function(){this._errorHandler=this._errorHandlerFb},i.prototype.reset=function(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0},i.prototype.parse=function(e,t){for(var i=0,r=0,n=this.currentState,s=this._oscParser,o=this._dcsParser,a=this._collect,c=this._params,l=this.TRANSITIONS.table,h=0;h<t;++h){switch((r=l[n<<8|((i=e[h])<160?i:160)])>>4){case 2:for(var u=h+1;;++u){if(u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<160){this._printHandler(e,h,u),h=u-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingCodepoint=0;break;case 0:break;case 1:if(this._errorHandler({position:h,code:i,currentState:n,collect:a,params:c,abort:!1}).abort)return;break;case 7:for(var f=this._csiHandlers[a<<8|i],_=f?f.length-1:-1;_>=0&&!1===f[_](c);_--);_<0&&this._csiHandlerFb(a<<8|i,c),this.precedingCodepoint=0;break;case 8:do{switch(i){case 59:c.addParam(0);break;case 58:c.addSubParam(-1);break;default:c.addDigit(i-48)}}while(++h<t&&(i=e[h])>47&&i<60);h--;break;case 9:a<<=8,a|=i;break;case 10:for(var d=this._escHandlers[a<<8|i],p=d?d.length-1:-1;p>=0&&!1===d[p]();p--);p<0&&this._escHandlerFb(a<<8|i),this.precedingCodepoint=0;break;case 11:c.reset(),c.addParam(0),a=0;break;case 12:o.hook(a<<8|i,c);break;case 13:for(var v=h+1;;++v)if(v>=t||24===(i=e[v])||26===i||27===i||i>127&&i<160){o.put(e,h,v),h=v-1;break}break;case 14:o.unhook(24!==i&&26!==i),27===i&&(r|=1),c.reset(),c.addParam(0),a=0,this.precedingCodepoint=0;break;case 4:s.start();break;case 5:for(var g=h+1;;g++)if(g>=t||(i=e[g])<32||i>127&&i<=159){s.put(e,h,g),h=g-1;break}break;case 6:s.end(24!==i&&26!==i),27===i&&(r|=1),c.reset(),c.addParam(0),a=0,this.precedingCodepoint=0}n=15&r}this._collect=a,this.currentState=n},i}(s.Disposable);t.EscapeSequenceParser=u},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(40),o=i(45),a=i(46),c=i(47),l=i(27),h=i(2),u=i(23),f=1,_=function(e){function t(t,i,r,n,h){var u=e.call(this)||this;u._colors=t,u._terminal=i,u.bufferService=r,u._charSizeService=n,u.optionsService=h,u._id=f++;var _=u._terminal.options.allowTransparency;return u._characterJoinerRegistry=new l.CharacterJoinerRegistry(r),u._renderLayers=[new s.TextRenderLayer(u._terminal.screenElement,0,u._colors,u._characterJoinerRegistry,_,u._id,r,h),new o.SelectionRenderLayer(u._terminal.screenElement,1,u._colors,u._id,r,h),new c.LinkRenderLayer(u._terminal.screenElement,2,u._colors,u._id,u._terminal.linkifier,r,h),new a.CursorRenderLayer(u._terminal.screenElement,3,u._colors,u._terminal,u._id,r,h)],u.dimensions={scaledCharWidth:null,scaledCharHeight:null,scaledCellWidth:null,scaledCellHeight:null,scaledCharLeft:null,scaledCharTop:null,scaledCanvasWidth:null,scaledCanvasHeight:null,canvasWidth:null,canvasHeight:null,actualCellWidth:null,actualCellHeight:null},u._devicePixelRatio=window.devicePixelRatio,u._updateDimensions(),u.onOptionsChanged(),u}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._renderLayers.forEach(function(e){return e.dispose()}),u.removeTerminalFromCache(this._id)},t.prototype.onDevicePixelRatioChange=function(){this._devicePixelRatio!==window.devicePixelRatio&&(this._devicePixelRatio=window.devicePixelRatio,this.onResize(this._terminal.cols,this._terminal.rows))},t.prototype.setColors=function(e){var t=this;this._colors=e,this._renderLayers.forEach(function(e){e.setColors(t._colors),e.reset()})},t.prototype.onResize=function(e,t){var i=this;this._updateDimensions(),this._renderLayers.forEach(function(e){return e.resize(i.dimensions)}),this._terminal.screenElement.style.width=this.dimensions.canvasWidth+"px",this._terminal.screenElement.style.height=this.dimensions.canvasHeight+"px"},t.prototype.onCharSizeChanged=function(){this.onResize(this._terminal.cols,this._terminal.rows)},t.prototype.onBlur=function(){this._runOperation(function(e){return e.onBlur()})},t.prototype.onFocus=function(){this._runOperation(function(e){return e.onFocus()})},t.prototype.onSelectionChanged=function(e,t,i){void 0===i&&(i=!1),this._runOperation(function(r){return r.onSelectionChanged(e,t,i)})},t.prototype.onCursorMove=function(){this._runOperation(function(e){return e.onCursorMove()})},t.prototype.onOptionsChanged=function(){this._runOperation(function(e){return e.onOptionsChanged()})},t.prototype.clear=function(){this._runOperation(function(e){return e.reset()})},t.prototype._runOperation=function(e){this._renderLayers.forEach(function(t){return e(t)})},t.prototype.renderRows=function(e,t){this._renderLayers.forEach(function(i){return i.onGridChanged(e,t)})},t.prototype._updateDimensions=function(){this._charSizeService.hasValidSize&&(this.dimensions.scaledCharWidth=Math.floor(this._charSizeService.width*window.devicePixelRatio),this.dimensions.scaledCharHeight=Math.ceil(this._charSizeService.height*window.devicePixelRatio),this.dimensions.scaledCellHeight=Math.floor(this.dimensions.scaledCharHeight*this._terminal.options.lineHeight),this.dimensions.scaledCharTop=1===this._terminal.options.lineHeight?0:Math.round((this.dimensions.scaledCellHeight-this.dimensions.scaledCharHeight)/2),this.dimensions.scaledCellWidth=this.dimensions.scaledCharWidth+Math.round(this._terminal.options.letterSpacing),this.dimensions.scaledCharLeft=Math.floor(this._terminal.options.letterSpacing/2),this.dimensions.scaledCanvasHeight=this._terminal.rows*this.dimensions.scaledCellHeight,this.dimensions.scaledCanvasWidth=this._terminal.cols*this.dimensions.scaledCellWidth,this.dimensions.canvasHeight=Math.round(this.dimensions.scaledCanvasHeight/window.devicePixelRatio),this.dimensions.canvasWidth=Math.round(this.dimensions.scaledCanvasWidth/window.devicePixelRatio),this.dimensions.actualCellHeight=this.dimensions.canvasHeight/this._terminal.rows,this.dimensions.actualCellWidth=this.dimensions.canvasWidth/this._terminal.cols)},t.prototype.registerCharacterJoiner=function(e){return this._characterJoinerRegistry.registerCharacterJoiner(e)},t.prototype.deregisterCharacterJoiner=function(e){return this._characterJoinerRegistry.deregisterCharacterJoiner(e)},t}(h.Disposable);t.Renderer=_},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(41),o=i(12),a=i(6),c=i(3),l=i(27),h=i(4),u=function(e){function t(t,i,r,n,o,a,c,l){var u=e.call(this,t,"text",i,o,r,a,c,l)||this;return u.bufferService=c,u.optionsService=l,u._characterWidth=0,u._characterFont="",u._characterOverlapCache={},u._workCell=new h.CellData,u._state=new s.GridCache,u._characterJoinerRegistry=n,u}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t);var i=this._getFont(!1,!1);this._characterWidth===t.scaledCharWidth&&this._characterFont===i||(this._characterWidth=t.scaledCharWidth,this._characterFont=i,this._characterOverlapCache={}),this._state.clear(),this._state.resize(this._bufferService.cols,this._bufferService.rows)},t.prototype.reset=function(){this._state.clear(),this._clearAll()},t.prototype._forEachCell=function(e,t,i,r){for(var n=e;n<=t;n++)for(var s=n+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.lines.get(s),a=i?i.getJoinedCharacters(s):[],h=0;h<this._bufferService.cols;h++){o.loadCell(h,this._workCell);var u=this._workCell,f=!1,_=h;if(0!==u.getWidth()){if(a.length>0&&h===a[0][0]){f=!0;var d=a.shift();u=new l.JoinedCellData(this._workCell,o.translateToString(!0,d[0],d[1]),d[1]-d[0]),_=d[1]-1}!f&&this._isOverlapping(u)&&_<o.length-1&&o.getCodePoint(_+1)===c.NULL_CELL_CODE&&(u.content&=-12582913,u.content|=2<<22),r(u,h,n),h=_}}},t.prototype._drawBackground=function(e,t){var i=this,r=this._ctx,n=this._bufferService.cols,s=0,o=0,c=null;r.save(),this._forEachCell(e,t,null,function(e,t,l){var h=null;e.isInverse()?h=e.isFgDefault()?i._colors.foreground.css:e.isFgRGB()?"rgb("+a.AttributeData.toColorRGB(e.getFgColor()).join(",")+")":i._colors.ansi[e.getFgColor()].css:e.isBgRGB()?h="rgb("+a.AttributeData.toColorRGB(e.getBgColor()).join(",")+")":e.isBgPalette()&&(h=i._colors.ansi[e.getBgColor()].css),null===c&&(s=t,o=l),l!==o?(r.fillStyle=c||"",i._fillCells(s,o,n-s,1),s=t,o=l):c!==h&&(r.fillStyle=c||"",i._fillCells(s,o,t-s,1),s=t,o=l),c=h}),null!==c&&(r.fillStyle=c,this._fillCells(s,o,n-s,1)),r.restore()},t.prototype._drawForeground=function(e,t){var i=this;this._forEachCell(e,t,this._characterJoinerRegistry,function(e,t,r){if(!e.isInvisible()&&(i._drawChars(e,t,r),e.isUnderline())){if(i._ctx.save(),e.isInverse())e.isBgDefault()?i._ctx.fillStyle=i._colors.background.css:e.isBgRGB()?i._ctx.fillStyle="rgb("+a.AttributeData.toColorRGB(e.getBgColor()).join(",")+")":i._ctx.fillStyle=i._colors.ansi[e.getBgColor()].css;else if(e.isFgDefault())i._ctx.fillStyle=i._colors.foreground.css;else if(e.isFgRGB())i._ctx.fillStyle="rgb("+a.AttributeData.toColorRGB(e.getFgColor()).join(",")+")";else{var n=e.getFgColor();i._optionsService.options.drawBoldTextInBrightColors&&e.isBold()&&n<8&&(n+=8),i._ctx.fillStyle=i._colors.ansi[n].css}i._fillBottomLineAtCells(t,r,e.getWidth()),i._ctx.restore()}})},t.prototype.onGridChanged=function(e,t){0!==this._state.cache.length&&(this._charAtlas&&this._charAtlas.beginFrame(),this._clearCells(0,e,this._bufferService.cols,t-e+1),this._drawBackground(e,t),this._drawForeground(e,t))},t.prototype.onOptionsChanged=function(){this._setTransparency(this._optionsService.options.allowTransparency)},t.prototype._isOverlapping=function(e){if(1!==e.getWidth())return!1;if(e.getCode()<256)return!1;var t=e.getChars();if(this._characterOverlapCache.hasOwnProperty(t))return this._characterOverlapCache[t];this._ctx.save(),this._ctx.font=this._characterFont;var i=Math.floor(this._ctx.measureText(t).width)>this._characterWidth;return this._ctx.restore(),this._characterOverlapCache[t]=i,i},t}(o.BaseRenderLayer);t.TextRenderLayer=u},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.cache=[]}return e.prototype.resize=function(e,t){for(var i=0;i<e;i++){this.cache.length<=i&&this.cache.push([]);for(var r=this.cache[i].length;r<t;r++)this.cache[i].push(void 0);this.cache[i].length=t}this.cache.length=e},e.prototype.clear=function(){for(var e=0;e<this.cache.length;e++)for(var t=0;t<this.cache[e].length;t++)this.cache[e][t]=void 0},e}();t.GridCache=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(9),o=i(43),a=i(25),c=i(44),l=i(10),h=i(26),u=1024,f=1024,_={css:"rgba(0, 0, 0, 0)",rgba:0};function d(e){return e.code<<21|e.bg<<12|e.fg<<3|(e.bold?0:4)+(e.dim?0:2)+(e.italic?0:1)}t.getGlyphCacheKey=d;var p=function(e){function t(t,i){var r=e.call(this)||this;r._config=i,r._drawToCacheCount=0,r._glyphsWaitingOnBitmap=[],r._bitmapCommitTimeout=null,r._bitmap=null,r._cacheCanvas=t.createElement("canvas"),r._cacheCanvas.width=u,r._cacheCanvas.height=f,r._cacheCtx=h.throwIfFalsy(r._cacheCanvas.getContext("2d",{alpha:!0}));var n=t.createElement("canvas");n.width=r._config.scaledCharWidth,n.height=r._config.scaledCharHeight,r._tmpCtx=h.throwIfFalsy(n.getContext("2d",{alpha:r._config.allowTransparency})),r._width=Math.floor(u/r._config.scaledCharWidth),r._height=Math.floor(f/r._config.scaledCharHeight);var s=r._width*r._height;return r._cacheMap=new c.LRUMap(s),r._cacheMap.prealloc(s),r}return n(t,e),t.prototype.dispose=function(){null!==this._bitmapCommitTimeout&&(window.clearTimeout(this._bitmapCommitTimeout),this._bitmapCommitTimeout=null)},t.prototype.beginFrame=function(){this._drawToCacheCount=0},t.prototype.draw=function(e,t,i,r){if(32===t.code)return!0;if(!this._canCache(t))return!1;var n=d(t),s=this._cacheMap.get(n);if(null!=s)return this._drawFromCache(e,s,i,r),!0;if(this._drawToCacheCount<100){var o=void 0;o=this._cacheMap.size<this._cacheMap.capacity?this._cacheMap.size:this._cacheMap.peek().index;var a=this._drawToCache(t,o);return this._cacheMap.set(n,a),this._drawFromCache(e,a,i,r),!0}return!1},t.prototype._canCache=function(e){return e.code<256},t.prototype._toCoordinateX=function(e){return e%this._width*this._config.scaledCharWidth},t.prototype._toCoordinateY=function(e){return Math.floor(e/this._width)*this._config.scaledCharHeight},t.prototype._drawFromCache=function(e,t,i,r){if(!t.isEmpty){var n=this._toCoordinateX(t.index),s=this._toCoordinateY(t.index);e.drawImage(t.inBitmap?this._bitmap:this._cacheCanvas,n,s,this._config.scaledCharWidth,this._config.scaledCharHeight,i,r,this._config.scaledCharWidth,this._config.scaledCharHeight)}},t.prototype._getColorFromAnsiIndex=function(e){return e<this._config.colors.ansi.length?this._config.colors.ansi[e]:a.DEFAULT_ANSI_COLORS[e]},t.prototype._getBackgroundColor=function(e){return this._config.allowTransparency?_:e.bg===s.INVERTED_DEFAULT_COLOR?this._config.colors.foreground:e.bg<256?this._getColorFromAnsiIndex(e.bg):this._config.colors.background},t.prototype._getForegroundColor=function(e){return e.fg===s.INVERTED_DEFAULT_COLOR?this._config.colors.background:e.fg<256?this._getColorFromAnsiIndex(e.fg):this._config.colors.foreground},t.prototype._drawToCache=function(e,t){this._drawToCacheCount++,this._tmpCtx.save();var i=this._getBackgroundColor(e);this._tmpCtx.globalCompositeOperation="copy",this._tmpCtx.fillStyle=i.css,this._tmpCtx.fillRect(0,0,this._config.scaledCharWidth,this._config.scaledCharHeight),this._tmpCtx.globalCompositeOperation="source-over";var r=e.bold?this._config.fontWeightBold:this._config.fontWeight,n=e.italic?"italic":"";this._tmpCtx.font=n+" "+r+" "+this._config.fontSize*this._config.devicePixelRatio+"px "+this._config.fontFamily,this._tmpCtx.textBaseline="middle",this._tmpCtx.fillStyle=this._getForegroundColor(e).css,e.dim&&(this._tmpCtx.globalAlpha=s.DIM_OPACITY),this._tmpCtx.fillText(e.chars,0,this._config.scaledCharHeight/2),this._tmpCtx.restore();var o=this._tmpCtx.getImageData(0,0,this._config.scaledCharWidth,this._config.scaledCharHeight),a=!1;this._config.allowTransparency||(a=function(e,t){for(var i=!0,r=t.rgba>>>24,n=t.rgba>>>16&255,s=t.rgba>>>8&255,o=0;o<e.data.length;o+=4)e.data[o]===r&&e.data[o+1]===n&&e.data[o+2]===s?e.data[o+3]=0:i=!1;return i}(o,i));var c=this._toCoordinateX(t),l=this._toCoordinateY(t);this._cacheCtx.putImageData(o,c,l);var h={index:t,isEmpty:a,inBitmap:!1};return this._addGlyphToBitmap(h),h},t.prototype._addGlyphToBitmap=function(e){var t=this;"createImageBitmap"in window&&!l.isFirefox&&!l.isSafari&&(this._glyphsWaitingOnBitmap.push(e),null===this._bitmapCommitTimeout&&(this._bitmapCommitTimeout=window.setTimeout(function(){return t._generateBitmap()},100)))},t.prototype._generateBitmap=function(){var e=this,t=this._glyphsWaitingOnBitmap;this._glyphsWaitingOnBitmap=[],window.createImageBitmap(this._cacheCanvas).then(function(i){e._bitmap=i;for(var r=0;r<t.length;r++){t[r].inBitmap=!0}}),this._bitmapCommitTimeout=null},t}(o.BaseCharAtlas);t.DynamicCharAtlas=p;var v=function(e){function t(t,i){return e.call(this)||this}return n(t,e),t.prototype.draw=function(e,t,i,r){return!1},t}(o.BaseCharAtlas);t.NoneCharAtlas=v},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._didWarmUp=!1}return e.prototype.dispose=function(){},e.prototype.warmUp=function(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)},e.prototype._doWarmUp=function(){},e.prototype.beginFrame=function(){},e}();t.BaseCharAtlas=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this.capacity=e,this._map={},this._head=null,this._tail=null,this._nodePool=[],this.size=0}return e.prototype._unlinkNode=function(e){var t=e.prev,i=e.next;e===this._head&&(this._head=i),e===this._tail&&(this._tail=t),null!==t&&(t.next=i),null!==i&&(i.prev=t)},e.prototype._appendNode=function(e){var t=this._tail;null!==t&&(t.next=e),e.prev=t,e.next=null,this._tail=e,null===this._head&&(this._head=e)},e.prototype.prealloc=function(e){for(var t=this._nodePool,i=0;i<e;i++)t.push({prev:null,next:null,key:null,value:null})},e.prototype.get=function(e){var t=this._map[e];return void 0!==t?(this._unlinkNode(t),this._appendNode(t),t.value):null},e.prototype.peekValue=function(e){var t=this._map[e];return void 0!==t?t.value:null},e.prototype.peek=function(){var e=this._head;return null===e?null:e.value},e.prototype.set=function(e,t){var i=this._map[e];if(void 0!==i)i=this._map[e],this._unlinkNode(i),i.value=t;else if(this.size>=this.capacity)i=this._head,this._unlinkNode(i),delete this._map[i.key],i.key=e,i.value=t,this._map[e]=i;else{var r=this._nodePool;r.length>0?((i=r.pop()).key=e,i.value=t):i={prev:null,next:null,key:e,value:t},this._map[e]=i,this.size++}this._appendNode(i)},e}();t.LRUMap=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=function(e){function t(t,i,r,n,s,o){var a=e.call(this,t,"selection",i,!0,r,n,s,o)||this;return a.bufferService=s,a.optionsService=o,a._clearState(),a}return n(t,e),t.prototype._clearState=function(){this._state={start:void 0,end:void 0,columnSelectMode:void 0,ydisp:void 0}},t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._clearState()},t.prototype.reset=function(){this._state.start&&this._state.end&&(this._clearState(),this._clearAll())},t.prototype.onSelectionChanged=function(e,t,i){if(this._didStateChange(e,t,i,this._bufferService.buffer.ydisp))if(this._clearAll(),e&&t){var r=e[1]-this._bufferService.buffer.ydisp,n=t[1]-this._bufferService.buffer.ydisp,s=Math.max(r,0),o=Math.min(n,this._bufferService.rows-1);if(!(s>=this._bufferService.rows||o<0)){if(this._ctx.fillStyle=this._colors.selection.css,i){var a=e[0],c=t[0]-a,l=o-s+1;this._fillCells(a,s,c,l)}else{a=r===s?e[0]:0;var h=s===o?t[0]:this._bufferService.cols;this._fillCells(a,s,h-a,1);var u=Math.max(o-s-1,0);if(this._fillCells(0,s+1,this._bufferService.cols,u),s!==o){var f=n===o?t[0]:this._bufferService.cols;this._fillCells(0,o,f,1)}}this._state.start=[e[0],e[1]],this._state.end=[t[0],t[1]],this._state.columnSelectMode=i,this._state.ydisp=this._bufferService.buffer.ydisp}}else this._clearState()},t.prototype._didStateChange=function(e,t,i,r){return!this._areCoordinatesEqual(e,this._state.start)||!this._areCoordinatesEqual(t,this._state.end)||i!==this._state.columnSelectMode||r!==this._state.ydisp},t.prototype._areCoordinatesEqual=function(e,t){return!(!e||!t)&&(e[0]===t[0]&&e[1]===t[1])},t}(i(12).BaseRenderLayer);t.SelectionRenderLayer=s},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(12),o=i(4),a=function(e){function t(t,i,r,n,s,a,c){var l=e.call(this,t,"cursor",i,!0,r,s,a,c)||this;return l._terminal=n,l.bufferService=a,l.optionsService=c,l._cell=new o.CellData,l._state={x:null,y:null,isFocused:null,style:null,width:null},l._cursorRenderers={bar:l._renderBarCursor.bind(l),block:l._renderBlockCursor.bind(l),underline:l._renderUnderlineCursor.bind(l)},l}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._state={x:null,y:null,isFocused:null,style:null,width:null}},t.prototype.reset=function(){this._clearCursor(),this._cursorBlinkStateManager&&(this._cursorBlinkStateManager.dispose(),this._cursorBlinkStateManager=null,this.onOptionsChanged())},t.prototype.onBlur=function(){this._cursorBlinkStateManager&&this._cursorBlinkStateManager.pause(),this._terminal.refresh(this._bufferService.buffer.y,this._bufferService.buffer.y)},t.prototype.onFocus=function(){this._cursorBlinkStateManager?this._cursorBlinkStateManager.resume():this._terminal.refresh(this._bufferService.buffer.y,this._bufferService.buffer.y)},t.prototype.onOptionsChanged=function(){var e=this;this._optionsService.options.cursorBlink?this._cursorBlinkStateManager||(this._cursorBlinkStateManager=new c(this._terminal.isFocused,function(){e._render(!0)})):this._cursorBlinkStateManager&&(this._cursorBlinkStateManager.dispose(),this._cursorBlinkStateManager=null),this._terminal.refresh(this._bufferService.buffer.y,this._bufferService.buffer.y)},t.prototype.onCursorMove=function(){this._cursorBlinkStateManager&&this._cursorBlinkStateManager.restartBlinkAnimation()},t.prototype.onGridChanged=function(e,t){!this._cursorBlinkStateManager||this._cursorBlinkStateManager.isPaused?this._render(!1):this._cursorBlinkStateManager.restartBlinkAnimation()},t.prototype._render=function(e){if(this._terminal.cursorState&&!this._terminal.cursorHidden){var t=this._bufferService.buffer.ybase+this._bufferService.buffer.y,i=t-this._bufferService.buffer.ydisp;if(i<0||i>=this._bufferService.rows)this._clearCursor();else if(this._bufferService.buffer.lines.get(t).loadCell(this._bufferService.buffer.x,this._cell),void 0!==this._cell.content){if(!this._terminal.isFocused){this._clearCursor(),this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css;var r=this._optionsService.options.cursorStyle;return r&&"block"!==r?this._cursorRenderers[r](this._bufferService.buffer.x,i,this._cell):this._renderBlurCursor(this._bufferService.buffer.x,i,this._cell),this._ctx.restore(),this._state.x=this._bufferService.buffer.x,this._state.y=i,this._state.isFocused=!1,this._state.style=r,void(this._state.width=this._cell.getWidth())}if(!this._cursorBlinkStateManager||this._cursorBlinkStateManager.isCursorVisible){if(this._state){if(this._state.x===this._bufferService.buffer.x&&this._state.y===i&&this._state.isFocused===this._terminal.isFocused&&this._state.style===this._optionsService.options.cursorStyle&&this._state.width===this._cell.getWidth())return;this._clearCursor()}this._ctx.save(),this._cursorRenderers[this._optionsService.options.cursorStyle||"block"](this._bufferService.buffer.x,i,this._cell),this._ctx.restore(),this._state.x=this._bufferService.buffer.x,this._state.y=i,this._state.isFocused=!1,this._state.style=this._optionsService.options.cursorStyle,this._state.width=this._cell.getWidth()}else this._clearCursor()}}else this._clearCursor()},t.prototype._clearCursor=function(){this._state&&(this._clearCells(this._state.x,this._state.y,this._state.width,1),this._state={x:null,y:null,isFocused:null,style:null,width:null})},t.prototype._renderBarCursor=function(e,t,i){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillLeftLineAtCell(e,t),this._ctx.restore()},t.prototype._renderBlockCursor=function(e,t,i){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillCells(e,t,i.getWidth(),1),this._ctx.fillStyle=this._colors.cursorAccent.css,this._fillCharTrueColor(i,e,t),this._ctx.restore()},t.prototype._renderUnderlineCursor=function(e,t,i){this._ctx.save(),this._ctx.fillStyle=this._colors.cursor.css,this._fillBottomLineAtCells(e,t),this._ctx.restore()},t.prototype._renderBlurCursor=function(e,t,i){this._ctx.save(),this._ctx.strokeStyle=this._colors.cursor.css,this._strokeRectAtCell(e,t,i.getWidth(),1),this._ctx.restore()},t}(s.BaseRenderLayer);t.CursorRenderLayer=a;var c=function(){function e(e,t){this._renderCallback=t,this.isCursorVisible=!0,e&&this._restartInterval()}return Object.defineProperty(e.prototype,"isPaused",{get:function(){return!(this._blinkStartTimeout||this._blinkInterval)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._blinkInterval&&(window.clearInterval(this._blinkInterval),this._blinkInterval=null),this._blinkStartTimeout&&(window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=null),this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=null)},e.prototype.restartBlinkAnimation=function(){var e=this;this.isPaused||(this._animationTimeRestarted=Date.now(),this.isCursorVisible=!0,this._animationFrame||(this._animationFrame=window.requestAnimationFrame(function(){e._renderCallback(),e._animationFrame=null})))},e.prototype._restartInterval=function(e){var t=this;void 0===e&&(e=600),this._blinkInterval&&window.clearInterval(this._blinkInterval),this._blinkStartTimeout=setTimeout(function(){if(t._animationTimeRestarted){var e=600-(Date.now()-t._animationTimeRestarted);if(t._animationTimeRestarted=null,e>0)return void t._restartInterval(e)}t.isCursorVisible=!1,t._animationFrame=window.requestAnimationFrame(function(){t._renderCallback(),t._animationFrame=null}),t._blinkInterval=setInterval(function(){if(t._animationTimeRestarted){var e=600-(Date.now()-t._animationTimeRestarted);return t._animationTimeRestarted=null,void t._restartInterval(e)}t.isCursorVisible=!t.isCursorVisible,t._animationFrame=window.requestAnimationFrame(function(){t._renderCallback(),t._animationFrame=null})},600)},e)},e.prototype.pause=function(){this.isCursorVisible=!0,this._blinkInterval&&(window.clearInterval(this._blinkInterval),this._blinkInterval=null),this._blinkStartTimeout&&(window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=null),this._animationFrame&&(window.cancelAnimationFrame(this._animationFrame),this._animationFrame=null)},e.prototype.resume=function(){this._animationTimeRestarted=null,this._restartInterval(),this.restartBlinkAnimation()},e}()},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(12),o=i(9),a=i(24),c=function(e){function t(t,i,r,n,s,o,a){var c=e.call(this,t,"link",i,!0,r,n,o,a)||this;return c.bufferService=o,c.optionsService=a,s.onLinkHover(function(e){return c._onLinkHover(e)}),s.onLinkLeave(function(e){return c._onLinkLeave(e)}),c}return n(t,e),t.prototype.resize=function(t){e.prototype.resize.call(this,t),this._state=void 0},t.prototype.reset=function(){this._clearCurrentLink()},t.prototype._clearCurrentLink=function(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);var e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}},t.prototype._onLinkHover=function(e){if(e.fg===o.INVERTED_DEFAULT_COLOR?this._ctx.fillStyle=this._colors.background.css:e.fg&&a.is256Color(e.fg)?this._ctx.fillStyle=this._colors.ansi[e.fg].css:this._ctx.fillStyle=this._colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(var t=e.y1+1;t<e.y2;t++)this._fillBottomLineAtCells(0,t,e.cols);this._fillBottomLineAtCells(0,e.y2,e.x2)}this._state=e},t.prototype._onLinkLeave=function(e){this._clearCurrentLink()},t}(s.BaseRenderLayer);t.LinkRenderLayer=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(18),n=i(1),s=function(){function e(e,t){this._bufferService=e,this._logService=t,this._linkMatchers=[],this._nextLinkMatcherId=0,this._onLinkHover=new n.EventEmitter,this._onLinkLeave=new n.EventEmitter,this._onLinkTooltip=new n.EventEmitter,this._rowsToLinkify={start:void 0,end:void 0}}return Object.defineProperty(e.prototype,"onLinkHover",{get:function(){return this._onLinkHover.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onLinkLeave",{get:function(){return this._onLinkLeave.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onLinkTooltip",{get:function(){return this._onLinkTooltip.event},enumerable:!0,configurable:!0}),e.prototype.attachToDom=function(e,t){this._element=e,this._mouseZoneManager=t},e.prototype.linkifyRows=function(t,i){var r=this;this._mouseZoneManager&&(void 0===this._rowsToLinkify.start||void 0===this._rowsToLinkify.end?(this._rowsToLinkify.start=t,this._rowsToLinkify.end=i):(this._rowsToLinkify.start=Math.min(this._rowsToLinkify.start,t),this._rowsToLinkify.end=Math.max(this._rowsToLinkify.end,i)),this._mouseZoneManager.clearAll(t,i),this._rowsTimeoutId&&clearTimeout(this._rowsTimeoutId),this._rowsTimeoutId=setTimeout(function(){return r._linkifyRows()},e._timeBeforeLatency))},e.prototype._linkifyRows=function(){this._rowsTimeoutId=void 0;var e=this._bufferService.buffer;if(void 0!==this._rowsToLinkify.start&&void 0!==this._rowsToLinkify.end){var t=e.ydisp+this._rowsToLinkify.start;if(!(t>=e.lines.length)){for(var i=e.ydisp+Math.min(this._rowsToLinkify.end,this._bufferService.rows)+1,r=Math.ceil(2e3/this._bufferService.cols),n=this._bufferService.buffer.iterator(!1,t,i,r,r);n.hasNext();)for(var s=n.next(),o=0;o<this._linkMatchers.length;o++)this._doLinkifyRow(s.range.first,s.content,this._linkMatchers[o]);this._rowsToLinkify.start=void 0,this._rowsToLinkify.end=void 0}}else this._logService.debug("_rowToLinkify was unset before _linkifyRows was called")},e.prototype.registerLinkMatcher=function(e,t,i){if(void 0===i&&(i={}),!t)throw new Error("handler must be defined");var r={id:this._nextLinkMatcherId++,regex:e,handler:t,matchIndex:i.matchIndex,validationCallback:i.validationCallback,hoverTooltipCallback:i.tooltipCallback,hoverLeaveCallback:i.leaveCallback,willLinkActivate:i.willLinkActivate,priority:i.priority||0};return this._addLinkMatcherToList(r),r.id},e.prototype._addLinkMatcherToList=function(e){if(0!==this._linkMatchers.length){for(var t=this._linkMatchers.length-1;t>=0;t--)if(e.priority<=this._linkMatchers[t].priority)return void this._linkMatchers.splice(t+1,0,e);this._linkMatchers.splice(0,0,e)}else this._linkMatchers.push(e)},e.prototype.deregisterLinkMatcher=function(e){for(var t=0;t<this._linkMatchers.length;t++)if(this._linkMatchers[t].id===e)return this._linkMatchers.splice(t,1),!0;return!1},e.prototype._doLinkifyRow=function(e,t,i){for(var r,n=this,s=new RegExp(i.regex.source,(i.regex.flags||"")+"g"),o=-1,a=function(){var a=r["number"!=typeof i.matchIndex?0:i.matchIndex];if(!a)return c._logService.debug("match found without corresponding matchIndex",r,i),"break";if(o=t.indexOf(a,o+1),s.lastIndex=o+a.length,o<0)return"break";var l=c._bufferService.buffer.stringIndexToBufferIndex(e,o);if(l[0]<0)return"break";var h=c._bufferService.buffer.lines.get(l[0]);if(!h)return"break";var u=h.getFg(l[1]),f=u?u>>9&511:void 0;i.validationCallback?i.validationCallback(a,function(e){n._rowsTimeoutId||e&&n._addLink(l[1],l[0]-n._bufferService.buffer.ydisp,a,i,f)}):c._addLink(l[1],l[0]-c._bufferService.buffer.ydisp,a,i,f)},c=this;null!==(r=s.exec(t));){if("break"===a())break}},e.prototype._addLink=function(e,t,i,n,s){var a=this;if(this._mouseZoneManager&&this._element){var c=r.getStringCellWidth(i),l=e%this._bufferService.cols,h=t+Math.floor(e/this._bufferService.cols),u=(l+c)%this._bufferService.cols,f=h+Math.floor((l+c)/this._bufferService.cols);0===u&&(u=this._bufferService.cols,f--),this._mouseZoneManager.add(new o(l+1,h+1,u+1,f+1,function(e){if(n.handler)return n.handler(e,i);window.open(i,"_blank")},function(){a._onLinkHover.fire(a._createLinkHoverEvent(l,h,u,f,s)),a._element.classList.add("xterm-cursor-pointer")},function(e){a._onLinkTooltip.fire(a._createLinkHoverEvent(l,h,u,f,s)),n.hoverTooltipCallback&&n.hoverTooltipCallback(e,i,{start:{x:l,y:h},end:{x:u,y:f}})},function(){a._onLinkLeave.fire(a._createLinkHoverEvent(l,h,u,f,s)),a._element.classList.remove("xterm-cursor-pointer"),n.hoverLeaveCallback&&n.hoverLeaveCallback()},function(e){return!n.willLinkActivate||n.willLinkActivate(e,i)}))}},e.prototype._createLinkHoverEvent=function(e,t,i,r,n){return{x1:e,y1:t,x2:i,y2:r,cols:this._bufferService.cols,fg:n}},e._timeBeforeLatency=200,e}();t.Linkifier=s;var o=function(e,t,i,r,n,s,o,a,c){this.x1=e,this.y1=t,this.x2=i,this.y2=r,this.clickCallback=n,this.hoverCallback=s,this.tooltipCallback=o,this.leaveCallback=a,this.willLinkActivate=c};t.MouseZone=o},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(10),o=i(50),a=i(4),c=i(1),l=i(5),h=i(0),u=i(28),f=i(51),_=String.fromCharCode(160),d=new RegExp(_,"g"),p=function(){function e(e,t,i,r,n,s,l,h){var u=this;this._scrollLines=e,this._element=t,this._screenElement=i,this._charSizeService=r,this._bufferService=n,this._coreService=s,this._mouseService=l,this._optionsService=h,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new a.CellData,this._mouseDownTimeStamp=0,this._onLinuxMouseSelection=new c.EventEmitter,this._onRedrawRequest=new c.EventEmitter,this._onSelectionChange=new c.EventEmitter,this._mouseMoveListener=function(e){return u._onMouseMove(e)},this._mouseUpListener=function(e){return u._onMouseUp(e)},this._coreService.onUserInput(function(){u.hasSelection&&u.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(function(e){return u._onTrim(e)}),this._bufferService.buffers.onBufferActivate(function(e){return u._onBufferActivate(e)}),this.enable(),this._model=new o.SelectionModel(this._bufferService),this._activeSelectionMode=0}return Object.defineProperty(e.prototype,"onLinuxMouseSelection",{get:function(){return this._onLinuxMouseSelection.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onRedrawRequest",{get:function(){return this._onRedrawRequest.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onSelectionChange",{get:function(){return this._onSelectionChange.event},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._removeMouseDownListeners()},e.prototype.reset=function(){this.clearSelection()},e.prototype.disable=function(){this.clearSelection(),this._enabled=!1},e.prototype.enable=function(){this._enabled=!0},Object.defineProperty(e.prototype,"selectionStart",{get:function(){return this._model.finalSelectionStart},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectionEnd",{get:function(){return this._model.finalSelectionEnd},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasSelection",{get:function(){var e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t)&&(e[0]!==t[0]||e[1]!==t[1])},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectionText",{get:function(){var e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";var i=this._bufferService.buffer,r=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";for(var n=e[1];n<=t[1];n++){var o=i.translateBufferLineToString(n,!0,e[0],t[0]);r.push(o)}}else{var a=e[1]===t[1]?t[0]:void 0;r.push(i.translateBufferLineToString(e[1],!0,e[0],a));for(n=e[1]+1;n<=t[1]-1;n++){var c=i.lines.get(n);o=i.translateBufferLineToString(n,!0);c&&c.isWrapped?r[r.length-1]+=o:r.push(o)}if(e[1]!==t[1]){c=i.lines.get(t[1]),o=i.translateBufferLineToString(t[1],!0,0,t[0]);c&&c.isWrapped?r[r.length-1]+=o:r.push(o)}}return r.map(function(e){return e.replace(d," ")}).join(s.isWindows?"\r\n":"\n")},enumerable:!0,configurable:!0}),e.prototype.clearSelection=function(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()},e.prototype.refresh=function(e){var t=this;(this._refreshAnimationFrame||(this._refreshAnimationFrame=window.requestAnimationFrame(function(){return t._refresh()})),s.isLinux&&e)&&(this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText))},e.prototype._refresh=function(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})},e.prototype.isClickInSelection=function(e){var t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!!(i&&r&&t)&&this._areCoordsInSelection(t,i,r)},e.prototype._areCoordsInSelection=function(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]},e.prototype.selectWordAtCursor=function(e){var t=this._getMouseBufferCoords(e);t&&(this._selectWordAt(t,!1),this._model.selectionEnd=void 0,this.refresh(!0))},e.prototype.selectAll=function(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()},e.prototype.selectLines=function(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()},e.prototype._onTrim=function(e){this._model.onTrim(e)&&this.refresh()},e.prototype._getMouseBufferCoords=function(e){var t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t},e.prototype._getMouseEventScrollAmount=function(e){var t=u.getCoordsRelativeToElement(e,this._screenElement)[1],i=this._bufferService.rows*Math.ceil(this._charSizeService.height*this._optionsService.options.lineHeight);return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),(t/=50)/Math.abs(t)+Math.round(14*t))},e.prototype.shouldForceSelection=function(e){return s.isMac?e.altKey&&this._optionsService.options.macOptionClickForcesSelection:e.shiftKey},e.prototype.onMouseDown=function(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._onIncrementalClick(e):1===e.detail?this._onSingleClick(e):2===e.detail?this._onDoubleClick(e):3===e.detail&&this._onTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}},e.prototype._addMouseDownListeners=function(){var e=this;this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=window.setInterval(function(){return e._dragScroll()},50)},e.prototype._removeMouseDownListeners=function(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0},e.prototype._onIncrementalClick=function(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))},e.prototype._onSingleClick=function(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),this._model.selectionStart){this._model.selectionEnd=void 0;var t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}},e.prototype._onDoubleClick=function(e){var t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=1,this._selectWordAt(t,!0))},e.prototype._onTripleClick=function(e){var t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))},e.prototype.shouldColumnSelect=function(e){return e.altKey&&!(s.isMac&&this._optionsService.options.macOptionClickForcesSelection)},e.prototype._onMouseMove=function(e){if(e.stopImmediatePropagation(),this._model.selectionStart){var t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),this._model.selectionEnd){2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));var i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){var r=i.lines.get(this._model.selectionEnd[1]);r&&0===r.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]++}t&&t[0]===this._model.selectionEnd[0]&&t[1]===this._model.selectionEnd[1]||this.refresh(!0)}else this.refresh(!0)}},e.prototype._dragScroll=function(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._scrollLines(this._dragScrollAmount,!1);var e=this._bufferService.buffer;this._dragScrollAmount>0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}},e.prototype._onMouseUp=function(e){var t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500){if(e.altKey&&this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){var i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&void 0!==i[0]&&void 0!==i[1]){var r=f.moveToCellSequence(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(r,!0)}}}else this.hasSelection&&this._onSelectionChange.fire()},e.prototype._onBufferActivate=function(e){var t=this;this.clearSelection(),this._trimListener&&this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(function(e){return t._onTrim(e)})},e.prototype._convertViewportColToCharacterIndex=function(e,t){for(var i=t[0],r=0;t[0]>=r;r++){var n=e.loadCell(r,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:n>1&&t[0]!==r&&(i+=n-1)}return i},e.prototype.setSelection=function(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh()},e.prototype._getWordAt=function(e,t,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=!0),!(e[0]>=this._bufferService.cols)){var n=this._bufferService.buffer,s=n.lines.get(e[1]);if(s){var o=n.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(s,e),c=a,l=e[0]-a,h=0,u=0,f=0,_=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;c<o.length&&" "===o.charAt(c+1);)c++}else{var d=e[0],p=e[0];0===s.getWidth(d)&&(h++,d--),2===s.getWidth(p)&&(u++,p++);var v=s.getString(p).length;for(v>1&&(_+=v-1,c+=v-1);d>0&&a>0&&!this._isCharWordSeparator(s.loadCell(d-1,this._workCell));){s.loadCell(d-1,this._workCell);var g=this._workCell.getChars().length;0===this._workCell.getWidth()?(h++,d--):g>1&&(f+=g-1,a-=g-1),a--,d--}for(;p<s.length&&c+1<o.length&&!this._isCharWordSeparator(s.loadCell(p+1,this._workCell));){s.loadCell(p+1,this._workCell);var y=this._workCell.getChars().length;2===this._workCell.getWidth()?(u++,p++):y>1&&(_+=y-1,c+=y-1),c++,p++}}c++;var m=a+l-h+f,b=Math.min(this._bufferService.cols,c-a+h+u-f-_);if(t||""!==o.slice(a,c).trim()){if(i&&0===m&&32!==s.getCodePoint(0)){var C=n.lines.get(e[1]-1);if(C&&s.isWrapped&&32!==C.getCodePoint(this._bufferService.cols-1)){var S=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(S){var w=this._bufferService.cols-S.start;m-=w,b+=w}}}if(r&&m+b===this._bufferService.cols&&32!==s.getCodePoint(this._bufferService.cols-1)){var E=n.lines.get(e[1]+1);if(E&&E.isWrapped&&32!==E.getCodePoint(0)){var L=this._getWordAt([0,e[1]+1],!1,!1,!0);L&&(b+=L.length)}}return{start:m,length:b}}}}},e.prototype._selectWordAt=function(e,t){var i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}},e.prototype._selectToWordAt=function(e){var t=this._getWordAt(e,!0);if(t){for(var i=e[1];t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}},e.prototype._isCharWordSeparator=function(e){return 0!==e.getWidth()&&this._optionsService.options.wordSeparator.indexOf(e.getChars())>=0},e.prototype._selectLineAt=function(e){var t=this._bufferService.buffer.getWrappedRangeForLine(e);this._model.selectionStart=[0,t.first],this._model.selectionEnd=[this._bufferService.cols,t.last],this._model.selectionStartLength=0},e=r([n(3,l.ICharSizeService),n(4,h.IBufferService),n(5,h.ICoreService),n(6,l.IMouseService),n(7,h.IOptionsService)],e)}();t.SelectionService=p},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}return e.prototype.clearSelection=function(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0},Object.defineProperty(e.prototype,"finalSelectionStart",{get:function(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"finalSelectionEnd",{get:function(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){var e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}return this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]?[Math.max(this.selectionStart[0]+this.selectionStartLength,this.selectionEnd[0]),this.selectionEnd[1]]:this.selectionEnd}},enumerable:!0,configurable:!0}),e.prototype.areSelectionValuesReversed=function(){var e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])},e.prototype.onTrim=function(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)},e}();t.SelectionModel=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(11);function n(e,t,i,r){var n=e-s(i,e),o=t-s(i,t);return h(Math.abs(n-o)-function(e,t,i){for(var r=0,n=e-s(i,e),o=t-s(i,t),c=0;c<Math.abs(n-o);c++){var l="A"===a(e,t)?-1:1,h=i.buffer.lines.get(n+l*c);h&&h.isWrapped&&r++}return r}(e,t,i),l(a(e,t),r))}function s(e,t){for(var i=0,r=e.buffer.lines.get(t),n=r&&r.isWrapped;n&&t>=0&&t<e.rows;)i++,n=(r=e.buffer.lines.get(--t))&&r.isWrapped;return i}function o(e,t,i,r,o,a){var c;return c=n(i,r,o,a).length>0?r-s(o,r):t,e<i&&c<=r||e>=i&&c<r?"C":"D"}function a(e,t){return e>t?"A":"B"}function c(e,t,i,r,n,s){for(var o=e,a=t,c="";o!==i||a!==r;)o+=n?1:-1,n&&o>s.cols-1?(c+=s.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!n&&o<0&&(c+=s.buffer.translateBufferLineToString(a,!1,0,e+1),e=o=s.cols-1,a--);return c+s.buffer.translateBufferLineToString(a,!1,e,o)}function l(e,t){var i=t?"O":"[";return r.C0.ESC+i+e}function h(e,t){e=Math.floor(e);for(var i="",r=0;r<e;r++)i+=t;return i}t.moveToCellSequence=function(e,t,i,r){var a=i.buffer.x,u=i.buffer.y;return i.buffer.hasScrollback?function(e,t,i,r,n,s){var a=o(e,t,i,r,n,s);return h(Math.abs(e-i),l(a,s))}(a,u,e,t,i,r):function(e,t,i,r,o,a){if(0===n(t,r,o,a).length)return"";return h(c(e,t,e,t-s(o,t),!1,o).length,l("D",a))}(a,u,0,t,i,r)+n(u,t,i,r)+function(e,t,i,r,a,u){var f;f=n(t,r,a,u).length>0?r-s(a,r):t;var _=r,d=o(e,t,i,r,a,u);return h(c(e,f,i,_,"C"===d,a).length,l(d,u))}(a,u,e,t,i,r)}},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=function(){function e(e){this._optionsService=e}return Object.defineProperty(e,"audioContext",{get:function(){if(!e._audioContext){var t=window.AudioContext||window.webkitAudioContext;if(!t)return console.warn("Web Audio API is not supported by this browser. Consider upgrading to the latest version"),null;e._audioContext=new t}return e._audioContext},enumerable:!0,configurable:!0}),e.prototype.playBellSound=function(){var t=e.audioContext;if(t){var i=t.createBufferSource();t.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)),function(e){i.buffer=e,i.connect(t.destination),i.start(0)})}},e.prototype._base64ToArrayBuffer=function(e){for(var t=window.atob(e),i=t.length,r=new Uint8Array(i),n=0;n<i;n++)r[n]=t.charCodeAt(n);return r.buffer},e.prototype._removeMimeType=function(e){return e.split(",")[1]},e=r([n(0,s.IOptionsService)],e)}();t.SoundService=o},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(2),c=i(7),l=i(5),h=i(0),u=function(e){function t(t,i,r,n,s){var o=e.call(this)||this;return o._element=t,o._screenElement=i,o._bufferService=r,o._mouseService=n,o._selectionService=s,o._zones=[],o._areZonesActive=!1,o._lastHoverCoords=[void 0,void 0],o._initialSelectionLength=0,o.register(c.addDisposableDomListener(o._element,"mousedown",function(e){return o._onMouseDown(e)})),o._mouseMoveListener=function(e){return o._onMouseMove(e)},o._mouseLeaveListener=function(e){return o._onMouseLeave(e)},o._clickListener=function(e){return o._onClick(e)},o}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._deactivate()},t.prototype.add=function(e){this._zones.push(e),1===this._zones.length&&this._activate()},t.prototype.clearAll=function(e,t){if(0!==this._zones.length){e&&t||(e=0,t=this._bufferService.rows-1);for(var i=0;i<this._zones.length;i++){var r=this._zones[i];(r.y1>e&&r.y1<=t+1||r.y2>e&&r.y2<=t+1||r.y1<e&&r.y2>t+1)&&(this._currentZone&&this._currentZone===r&&(this._currentZone.leaveCallback(),this._currentZone=void 0),this._zones.splice(i--,1))}0===this._zones.length&&this._deactivate()}},t.prototype._activate=function(){this._areZonesActive||(this._areZonesActive=!0,this._element.addEventListener("mousemove",this._mouseMoveListener),this._element.addEventListener("mouseleave",this._mouseLeaveListener),this._element.addEventListener("click",this._clickListener))},t.prototype._deactivate=function(){this._areZonesActive&&(this._areZonesActive=!1,this._element.removeEventListener("mousemove",this._mouseMoveListener),this._element.removeEventListener("mouseleave",this._mouseLeaveListener),this._element.removeEventListener("click",this._clickListener))},t.prototype._onMouseMove=function(e){this._lastHoverCoords[0]===e.pageX&&this._lastHoverCoords[1]===e.pageY||(this._onHover(e),this._lastHoverCoords=[e.pageX,e.pageY])},t.prototype._onHover=function(e){var t=this,i=this._findZoneEventAt(e);i!==this._currentZone&&(this._currentZone&&(this._currentZone.leaveCallback(),this._currentZone=void 0,this._tooltipTimeout&&clearTimeout(this._tooltipTimeout)),i&&(this._currentZone=i,i.hoverCallback&&i.hoverCallback(e),this._tooltipTimeout=setTimeout(function(){return t._onTooltip(e)},500)))},t.prototype._onTooltip=function(e){this._tooltipTimeout=void 0;var t=this._findZoneEventAt(e);t&&t.tooltipCallback&&t.tooltipCallback(e)},t.prototype._onMouseDown=function(e){if(this._initialSelectionLength=this._getSelectionLength(),this._areZonesActive){var t=this._findZoneEventAt(e);t&&t.willLinkActivate(e)&&(e.preventDefault(),e.stopImmediatePropagation())}},t.prototype._onMouseLeave=function(e){this._currentZone&&(this._currentZone.leaveCallback(),this._currentZone=void 0,this._tooltipTimeout&&clearTimeout(this._tooltipTimeout))},t.prototype._onClick=function(e){var t=this._findZoneEventAt(e),i=this._getSelectionLength();t&&i===this._initialSelectionLength&&(t.clickCallback(e),e.preventDefault(),e.stopImmediatePropagation())},t.prototype._getSelectionLength=function(){var e=this._selectionService.selectionText;return e?e.length:0},t.prototype._findZoneEventAt=function(e){var t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows);if(t)for(var i=t[0],r=t[1],n=0;n<this._zones.length;n++){var s=this._zones[n];if(s.y1===s.y2){if(r===s.y1&&i>=s.x1&&i<s.x2)return s}else if(r===s.y1&&i>=s.x1||r===s.y2&&i<s.x2||r>s.y1&&r<s.y2)return s}},t=s([o(2,h.IBufferService),o(3,l.IMouseService),o(4,l.ISelectionService)],t)}(a.Disposable);t.MouseZoneManager=u},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(16),o=i(10),a=i(29),c=i(7),l=i(2),h=i(30),u=function(e){function t(t,i){var r=e.call(this)||this;r._terminal=t,r._renderService=i,r._liveRegionLineCount=0,r._charsToConsume=[],r._charsToAnnounce="",r._accessibilityTreeRoot=document.createElement("div"),r._accessibilityTreeRoot.classList.add("xterm-accessibility"),r._rowContainer=document.createElement("div"),r._rowContainer.classList.add("xterm-accessibility-tree"),r._rowElements=[];for(var n=0;n<r._terminal.rows;n++)r._rowElements[n]=r._createAccessibilityTreeNode(),r._rowContainer.appendChild(r._rowElements[n]);return r._topBoundaryFocusListener=function(e){return r._onBoundaryFocus(e,0)},r._bottomBoundaryFocusListener=function(e){return r._onBoundaryFocus(e,1)},r._rowElements[0].addEventListener("focus",r._topBoundaryFocusListener),r._rowElements[r._rowElements.length-1].addEventListener("focus",r._bottomBoundaryFocusListener),r._refreshRowsDimensions(),r._accessibilityTreeRoot.appendChild(r._rowContainer),r._renderRowsDebouncer=new a.RenderDebouncer(r._renderRows.bind(r)),r._refreshRows(),r._liveRegion=document.createElement("div"),r._liveRegion.classList.add("live-region"),r._liveRegion.setAttribute("aria-live","assertive"),r._accessibilityTreeRoot.appendChild(r._liveRegion),r._terminal.element.insertAdjacentElement("afterbegin",r._accessibilityTreeRoot),r.register(r._renderRowsDebouncer),r.register(r._terminal.onResize(function(e){return r._onResize(e.rows)})),r.register(r._terminal.onRender(function(e){return r._refreshRows(e.start,e.end)})),r.register(r._terminal.onScroll(function(){return r._refreshRows()})),r.register(r._terminal.onA11yChar(function(e){return r._onChar(e)})),r.register(r._terminal.onLineFeed(function(){return r._onChar("\n")})),r.register(r._terminal.onA11yTab(function(e){return r._onTab(e)})),r.register(r._terminal.onKey(function(e){return r._onKey(e.key)})),r.register(r._terminal.onBlur(function(){return r._clearLiveRegion()})),r.register(r._renderService.onDimensionsChange(function(){return r._refreshRowsDimensions()})),r._screenDprMonitor=new h.ScreenDprMonitor,r.register(r._screenDprMonitor),r._screenDprMonitor.setListener(function(){return r._refreshRowsDimensions()}),r.register(c.addDisposableDomListener(window,"resize",function(){return r._refreshRowsDimensions()})),r}return n(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._terminal.element.removeChild(this._accessibilityTreeRoot),this._rowElements.length=0},t.prototype._onBoundaryFocus=function(e,t){var i=e.target,r=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")!==(0===t?"1":""+this._terminal.buffer.lines.length)&&e.relatedTarget===r){var n,s;if(0===t?(n=i,s=this._rowElements.pop(),this._rowContainer.removeChild(s)):(n=this._rowElements.shift(),s=i,this._rowContainer.removeChild(n)),n.removeEventListener("focus",this._topBoundaryFocusListener),s.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){var o=this._createAccessibilityTreeNode();this._rowElements.unshift(o),this._rowContainer.insertAdjacentElement("afterbegin",o)}else{o=this._createAccessibilityTreeNode();this._rowElements.push(o),this._rowContainer.appendChild(o)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}},t.prototype._onResize=function(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(var t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()},t.prototype._createAccessibilityTreeNode=function(){var e=document.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e},t.prototype._onTab=function(e){for(var t=0;t<e;t++)this._onChar(" ")},t.prototype._onChar=function(e){var t=this;if(this._liveRegionLineCount<21){if(this._charsToConsume.length>0)this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e);else this._charsToAnnounce+=e;"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=s.tooMuchOutput)),o.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(function(){t._accessibilityTreeRoot.appendChild(t._liveRegion)},0)}},t.prototype._clearLiveRegion=function(){this._liveRegion.textContent="",this._liveRegionLineCount=0,o.isMac&&this._liveRegion.parentNode&&this._accessibilityTreeRoot.removeChild(this._liveRegion)},t.prototype._onKey=function(e){this._clearLiveRegion(),this._charsToConsume.push(e)},t.prototype._refreshRows=function(e,t){this._renderRowsDebouncer.refresh(e,t,this._terminal.rows)},t.prototype._renderRows=function(e,t){for(var i=this._terminal.buffer,r=i.lines.length.toString(),n=e;n<=t;n++){var s=i.translateBufferLineToString(i.ydisp+n,!0),o=(i.ydisp+n+1).toString(),a=this._rowElements[n];a&&(0===s.length?a.innerHTML="&nbsp;":a.textContent=s,a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",r))}this._announceCharacters()},t.prototype._refreshRowsDimensions=function(){if(this._renderService.dimensions.actualCellHeight){this._rowElements.length!==this._terminal.rows&&this._onResize(this._terminal.rows);for(var e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e])}},t.prototype._refreshRowDimensions=function(e){e.style.height=this._renderService.dimensions.actualCellHeight+"px"},t.prototype._announceCharacters=function(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")},t}(l.Disposable);t.AccessibilityManager=u},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(56),o=i(9),a=i(2),c="xterm-dom-renderer-owner-",l="xterm-rows",h="xterm-selection",u=1,f=function(e){function t(t,i,r,n){var o=e.call(this)||this;return o._terminal=t,o._colors=i,o._charSizeService=r,o._optionsService=n,o._terminalClass=u++,o._rowElements=[],o._rowContainer=document.createElement("div"),o._rowContainer.classList.add(l),o._rowContainer.style.lineHeight="normal",o._rowContainer.setAttribute("aria-hidden","true"),o._refreshRowElements(o._terminal.cols,o._terminal.rows),o._selectionContainer=document.createElement("div"),o._selectionContainer.classList.add(h),o._selectionContainer.setAttribute("aria-hidden","true"),o.dimensions={scaledCharWidth:null,scaledCharHeight:null,scaledCellWidth:null,scaledCellHeight:null,scaledCharLeft:null,scaledCharTop:null,scaledCanvasWidth:null,scaledCanvasHeight:null,canvasWidth:null,canvasHeight:null,actualCellWidth:null,actualCellHeight:null},o._updateDimensions(),o._injectCss(),o._rowFactory=new s.DomRendererRowFactory(document,o._optionsService),o._terminal.element.classList.add(c+o._terminalClass),o._terminal.screenElement.appendChild(o._rowContainer),o._terminal.screenElement.appendChild(o._selectionContainer),o._terminal.linkifier.onLinkHover(function(e){return o._onLinkHover(e)}),o._terminal.linkifier.onLinkLeave(function(e){return o._onLinkLeave(e)}),o}return n(t,e),t.prototype.dispose=function(){this._terminal.element.classList.remove(c+this._terminalClass),this._terminal.screenElement.removeChild(this._rowContainer),this._terminal.screenElement.removeChild(this._selectionContainer),this._terminal.screenElement.removeChild(this._themeStyleElement),this._terminal.screenElement.removeChild(this._dimensionsStyleElement),e.prototype.dispose.call(this)},t.prototype._updateDimensions=function(){var e=this;this.dimensions.scaledCharWidth=this._charSizeService.width*window.devicePixelRatio,this.dimensions.scaledCharHeight=Math.ceil(this._charSizeService.height*window.devicePixelRatio),this.dimensions.scaledCellWidth=this.dimensions.scaledCharWidth+Math.round(this._terminal.options.letterSpacing),this.dimensions.scaledCellHeight=Math.floor(this.dimensions.scaledCharHeight*this._terminal.options.lineHeight),this.dimensions.scaledCharLeft=0,this.dimensions.scaledCharTop=0,this.dimensions.scaledCanvasWidth=this.dimensions.scaledCellWidth*this._terminal.cols,this.dimensions.scaledCanvasHeight=this.dimensions.scaledCellHeight*this._terminal.rows,this.dimensions.canvasWidth=Math.round(this.dimensions.scaledCanvasWidth/window.devicePixelRatio),this.dimensions.canvasHeight=Math.round(this.dimensions.scaledCanvasHeight/window.devicePixelRatio),this.dimensions.actualCellWidth=this.dimensions.canvasWidth/this._terminal.cols,this.dimensions.actualCellHeight=this.dimensions.canvasHeight/this._terminal.rows,this._rowElements.forEach(function(t){t.style.width=e.dimensions.canvasWidth+"px",t.style.height=e.dimensions.actualCellHeight+"px",t.style.lineHeight=e.dimensions.actualCellHeight+"px",t.style.overflow="hidden"}),this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._terminal.screenElement.appendChild(this._dimensionsStyleElement));var t=this._terminalSelector+" ."+l+" span { display: inline-block; height: 100%; vertical-align: top; width: "+this.dimensions.actualCellWidth+"px}";this._dimensionsStyleElement.innerHTML=t,this._selectionContainer.style.height=this._terminal._viewportElement.style.height,this._terminal.screenElement.style.width=this.dimensions.canvasWidth+"px",this._terminal.screenElement.style.height=this.dimensions.canvasHeight+"px"},t.prototype.setColors=function(e){this._colors=e,this._injectCss()},t.prototype._injectCss=function(){var e=this;this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._terminal.screenElement.appendChild(this._themeStyleElement));var t=this._terminalSelector+" ."+l+" { color: "+this._colors.foreground.css+"; background-color: "+this._colors.background.css+"; font-family: "+this._terminal.options.fontFamily+"; font-size: "+this._terminal.options.fontSize+"px;}";t+=this._terminalSelector+" span:not(."+s.BOLD_CLASS+") { font-weight: "+this._terminal.options.fontWeight+";}"+this._terminalSelector+" span."+s.BOLD_CLASS+" { font-weight: "+this._terminal.options.fontWeightBold+";}"+this._terminalSelector+" span."+s.ITALIC_CLASS+" { font-style: italic;}",t+="@keyframes blink_box_shadow { 50% {  box-shadow: none; }}",t+="@keyframes blink_block { 0% {  background-color: "+this._colors.cursor.css+";  color: "+this._colors.cursorAccent.css+"; } 50% {  background-color: "+this._colors.cursorAccent.css+";  color: "+this._colors.cursor.css+"; }}",t+=this._terminalSelector+" ."+l+":not(.xterm-focus) ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_BLOCK_CLASS+" { outline: 1px solid "+this._colors.cursor.css+"; outline-offset: -1px;}"+this._terminalSelector+" ."+l+".xterm-focus ."+s.CURSOR_CLASS+"."+s.CURSOR_BLINK_CLASS+":not(."+s.CURSOR_STYLE_BLOCK_CLASS+") { animation: blink_box_shadow 1s step-end infinite;}"+this._terminalSelector+" ."+l+".xterm-focus ."+s.CURSOR_CLASS+"."+s.CURSOR_BLINK_CLASS+"."+s.CURSOR_STYLE_BLOCK_CLASS+" { animation: blink_block 1s step-end infinite;}"+this._terminalSelector+" ."+l+".xterm-focus ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_BLOCK_CLASS+" { background-color: "+this._colors.cursor.css+"; color: "+this._colors.cursorAccent.css+";}"+this._terminalSelector+" ."+l+" ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_BAR_CLASS+" { box-shadow: 1px 0 0 "+this._colors.cursor.css+" inset;}"+this._terminalSelector+" ."+l+" ."+s.CURSOR_CLASS+"."+s.CURSOR_STYLE_UNDERLINE_CLASS+" { box-shadow: 0 -1px 0 "+this._colors.cursor.css+" inset;}",t+=this._terminalSelector+" ."+h+" { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}"+this._terminalSelector+" ."+h+" div { position: absolute; background-color: "+this._colors.selection.css+";}",this._colors.ansi.forEach(function(i,r){t+=e._terminalSelector+" .xterm-fg-"+r+" { color: "+i.css+"; }"+e._terminalSelector+" .xterm-bg-"+r+" { background-color: "+i.css+"; }"}),t+=this._terminalSelector+" .xterm-fg-"+o.INVERTED_DEFAULT_COLOR+" { color: "+this._colors.background.css+"; }"+this._terminalSelector+" .xterm-bg-"+o.INVERTED_DEFAULT_COLOR+" { background-color: "+this._colors.foreground.css+"; }",this._themeStyleElement.innerHTML=t},t.prototype.onDevicePixelRatioChange=function(){this._updateDimensions()},t.prototype._refreshRowElements=function(e,t){for(var i=this._rowElements.length;i<=t;i++){var r=document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())},t.prototype.onResize=function(e,t){this._refreshRowElements(e,t),this._updateDimensions()},t.prototype.onCharSizeChanged=function(){this._updateDimensions()},t.prototype.onBlur=function(){this._rowContainer.classList.remove("xterm-focus")},t.prototype.onFocus=function(){this._rowContainer.classList.add("xterm-focus")},t.prototype.onSelectionChanged=function(e,t,i){for(;this._selectionContainer.children.length;)this._selectionContainer.removeChild(this._selectionContainer.children[0]);if(e&&t){var r=e[1]-this._terminal.buffer.ydisp,n=t[1]-this._terminal.buffer.ydisp,s=Math.max(r,0),o=Math.min(n,this._terminal.rows-1);if(!(s>=this._terminal.rows||o<0)){var a=document.createDocumentFragment();if(i)a.appendChild(this._createSelectionElement(s,e[0],t[0],o-s+1));else{var c=r===s?e[0]:0,l=s===o?t[0]:this._terminal.cols;a.appendChild(this._createSelectionElement(s,c,l));var h=o-s-1;if(a.appendChild(this._createSelectionElement(s+1,0,this._terminal.cols,h)),s!==o){var u=n===o?t[0]:this._terminal.cols;a.appendChild(this._createSelectionElement(o,0,u))}}this._selectionContainer.appendChild(a)}}},t.prototype._createSelectionElement=function(e,t,i,r){void 0===r&&(r=1);var n=document.createElement("div");return n.style.height=r*this.dimensions.actualCellHeight+"px",n.style.top=e*this.dimensions.actualCellHeight+"px",n.style.left=t*this.dimensions.actualCellWidth+"px",n.style.width=this.dimensions.actualCellWidth*(i-t)+"px",n},t.prototype.onCursorMove=function(){},t.prototype.onOptionsChanged=function(){this._updateDimensions(),this._injectCss(),this._terminal.refresh(0,this._terminal.rows-1)},t.prototype.clear=function(){this._rowElements.forEach(function(e){return e.innerHTML=""})},t.prototype.renderRows=function(e,t){for(var i=this._terminal,r=i.buffer.ybase+i.buffer.y,n=this._terminal.buffer.x,s=this._terminal.options.cursorBlink,o=e;o<=t;o++){var a=this._rowElements[o];a.innerHTML="";var c=o+i.buffer.ydisp,l=i.buffer.lines.get(c),h=i.options.cursorStyle;a.appendChild(this._rowFactory.createRow(l,c===r,h,n,s,this.dimensions.actualCellWidth,i.cols))}},Object.defineProperty(t.prototype,"_terminalSelector",{get:function(){return"."+c+this._terminalClass},enumerable:!0,configurable:!0}),t.prototype.registerCharacterJoiner=function(e){return-1},t.prototype.deregisterCharacterJoiner=function(e){return!1},t.prototype._onLinkHover=function(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)},t.prototype._onLinkLeave=function(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)},t.prototype._setCellUnderline=function(e,t,i,r,n,s){for(;e!==t||i!==r;){var o=this._rowElements[i];if(!o)return;var a=o.children[e];a&&(a.style.textDecoration=s?"underline":"none"),++e>=n&&(e=0,i++)}},t}(a.Disposable);t.DomRenderer=f},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(9),n=i(6),s=i(3),o=i(4);t.BOLD_CLASS="xterm-bold",t.DIM_CLASS="xterm-dim",t.ITALIC_CLASS="xterm-italic",t.UNDERLINE_CLASS="xterm-underline",t.CURSOR_CLASS="xterm-cursor",t.CURSOR_BLINK_CLASS="xterm-cursor-blink",t.CURSOR_STYLE_BLOCK_CLASS="xterm-cursor-block",t.CURSOR_STYLE_BAR_CLASS="xterm-cursor-bar",t.CURSOR_STYLE_UNDERLINE_CLASS="xterm-cursor-underline";var a=function(){function e(e,t){this._document=e,this._optionsService=t,this._workCell=new o.CellData}return e.prototype.createRow=function(e,i,o,a,c,l,h){for(var u=this._document.createDocumentFragment(),f=0,_=Math.min(e.length,h)-1;_>=0;_--)if(e.loadCell(_,this._workCell).getCode()!==s.NULL_CELL_CODE||i&&_===a){f=_+1;break}for(_=0;_<f;_++){e.loadCell(_,this._workCell);var d=this._workCell.getWidth();if(0!==d){var p=this._document.createElement("span");if(d>1&&(p.style.width=l*d+"px"),i&&_===a)switch(p.classList.add(t.CURSOR_CLASS),c&&p.classList.add(t.CURSOR_BLINK_CLASS),o){case"bar":p.classList.add(t.CURSOR_STYLE_BAR_CLASS);break;case"underline":p.classList.add(t.CURSOR_STYLE_UNDERLINE_CLASS);break;default:p.classList.add(t.CURSOR_STYLE_BLOCK_CLASS)}this._workCell.isBold()&&p.classList.add(t.BOLD_CLASS),this._workCell.isItalic()&&p.classList.add(t.ITALIC_CLASS),this._workCell.isDim()&&p.classList.add(t.DIM_CLASS),this._workCell.isUnderline()&&p.classList.add(t.UNDERLINE_CLASS),p.textContent=this._workCell.getChars()||s.WHITESPACE_CELL_CHAR;var v=this._workCell.isInverse();if(this._workCell.isFgRGB()){var g=p.getAttribute("style")||"";g+=(v?"background-":"")+"color:rgb("+n.AttributeData.toColorRGB(this._workCell.getFgColor()).join(",")+");",p.setAttribute("style",g)}else if(this._workCell.isFgPalette()){var y=this._workCell.getFgColor();this._workCell.isBold()&&y<8&&!v&&this._optionsService.options.drawBoldTextInBrightColors&&(y+=8),p.classList.add("xterm-"+(v?"b":"f")+"g-"+y)}else v&&p.classList.add("xterm-bg-"+r.INVERTED_DEFAULT_COLOR);if(this._workCell.isBgRGB()){g=p.getAttribute("style")||"";g+=(v?"":"background-")+"color:rgb("+n.AttributeData.toColorRGB(this._workCell.getBgColor()).join(",")+");",p.setAttribute("style",g)}else this._workCell.isBgPalette()?p.classList.add("xterm-"+(v?"f":"b")+"g-"+this._workCell.getBgColor()):v&&p.classList.add("xterm-fg-"+r.INVERTED_DEFAULT_COLOR);u.appendChild(p)}}return u},e}();t.DomRendererRowFactory=a},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(11),n={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};t.evaluateKeyboardEvent=function(e,t,i,s){var o={type:0,cancel:!1,key:void 0},a=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?o.key=t?r.C0.ESC+"OA":r.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?o.key=t?r.C0.ESC+"OD":r.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?o.key=t?r.C0.ESC+"OC":r.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(o.key=t?r.C0.ESC+"OB":r.C0.ESC+"[B");break;case 8:if(e.shiftKey){o.key=r.C0.BS;break}if(e.altKey){o.key=r.C0.ESC+r.C0.DEL;break}o.key=r.C0.DEL;break;case 9:if(e.shiftKey){o.key=r.C0.ESC+"[Z";break}o.key=r.C0.HT,o.cancel=!0;break;case 13:o.key=r.C0.CR,o.cancel=!0;break;case 27:o.key=r.C0.ESC,o.cancel=!0;break;case 37:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"D",o.key===r.C0.ESC+"[1;3D"&&(o.key=r.C0.ESC+(i?"b":"[1;5D"))):o.key=t?r.C0.ESC+"OD":r.C0.ESC+"[D";break;case 39:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"C",o.key===r.C0.ESC+"[1;3C"&&(o.key=r.C0.ESC+(i?"f":"[1;5C"))):o.key=t?r.C0.ESC+"OC":r.C0.ESC+"[C";break;case 38:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"A",i||o.key!==r.C0.ESC+"[1;3A"||(o.key=r.C0.ESC+"[1;5A")):o.key=t?r.C0.ESC+"OA":r.C0.ESC+"[A";break;case 40:if(e.metaKey)break;a?(o.key=r.C0.ESC+"[1;"+(a+1)+"B",i||o.key!==r.C0.ESC+"[1;3B"||(o.key=r.C0.ESC+"[1;5B")):o.key=t?r.C0.ESC+"OB":r.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(o.key=r.C0.ESC+"[2~");break;case 46:o.key=a?r.C0.ESC+"[3;"+(a+1)+"~":r.C0.ESC+"[3~";break;case 36:o.key=a?r.C0.ESC+"[1;"+(a+1)+"H":t?r.C0.ESC+"OH":r.C0.ESC+"[H";break;case 35:o.key=a?r.C0.ESC+"[1;"+(a+1)+"F":t?r.C0.ESC+"OF":r.C0.ESC+"[F";break;case 33:e.shiftKey?o.type=2:o.key=r.C0.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:o.key=r.C0.ESC+"[6~";break;case 112:o.key=a?r.C0.ESC+"[1;"+(a+1)+"P":r.C0.ESC+"OP";break;case 113:o.key=a?r.C0.ESC+"[1;"+(a+1)+"Q":r.C0.ESC+"OQ";break;case 114:o.key=a?r.C0.ESC+"[1;"+(a+1)+"R":r.C0.ESC+"OR";break;case 115:o.key=a?r.C0.ESC+"[1;"+(a+1)+"S":r.C0.ESC+"OS";break;case 116:o.key=a?r.C0.ESC+"[15;"+(a+1)+"~":r.C0.ESC+"[15~";break;case 117:o.key=a?r.C0.ESC+"[17;"+(a+1)+"~":r.C0.ESC+"[17~";break;case 118:o.key=a?r.C0.ESC+"[18;"+(a+1)+"~":r.C0.ESC+"[18~";break;case 119:o.key=a?r.C0.ESC+"[19;"+(a+1)+"~":r.C0.ESC+"[19~";break;case 120:o.key=a?r.C0.ESC+"[20;"+(a+1)+"~":r.C0.ESC+"[20~";break;case 121:o.key=a?r.C0.ESC+"[21;"+(a+1)+"~":r.C0.ESC+"[21~";break;case 122:o.key=a?r.C0.ESC+"[23;"+(a+1)+"~":r.C0.ESC+"[23~";break;case 123:o.key=a?r.C0.ESC+"[24;"+(a+1)+"~":r.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!s||!e.altKey||e.metaKey)i&&!e.altKey&&!e.ctrlKey&&e.metaKey?65===e.keyCode&&(o.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?o.key=e.key:e.key&&e.ctrlKey&&"_"===e.key&&(o.key=r.C0.US);else{var c=n[e.keyCode],l=c&&c[e.shiftKey?1:0];if(l)o.key=r.C0.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){var h=e.ctrlKey?e.keyCode-64:e.keyCode+32;o.key=r.C0.ESC+String.fromCharCode(h)}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?o.key=r.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?o.key=r.C0.DEL:219===e.keyCode?o.key=r.C0.ESC:220===e.keyCode?o.key=r.C0.FS:221===e.keyCode&&(o.key=r.C0.GS)}return o}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(3);t.applyWindowsMode=function(e){return e.onLineFeed(function(){var t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1).get(e.cols-1);e.buffer.lines.get(e.buffer.ybase+e.buffer.y).isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE})}},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},o=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(29),c=i(1),l=i(2),h=i(30),u=i(7),f=i(0),_=i(5),d=function(e){function t(t,i,r,n,s){var o=e.call(this)||this;if(o._renderer=t,o._rowCount=i,o.screenElement=r,o.optionsService=n,o.charSizeService=s,o._isPaused=!1,o._needsFullRefresh=!1,o._canvasWidth=0,o._canvasHeight=0,o._onDimensionsChange=new c.EventEmitter,o._onRender=new c.EventEmitter,o._onRefreshRequest=new c.EventEmitter,o._renderDebouncer=new a.RenderDebouncer(function(e,t){return o._renderRows(e,t)}),o.register(o._renderDebouncer),o._screenDprMonitor=new h.ScreenDprMonitor,o._screenDprMonitor.setListener(function(){return o.onDevicePixelRatioChange()}),o.register(o._screenDprMonitor),o.register(n.onOptionChange(function(){return o._renderer.onOptionsChanged()})),o.register(s.onCharSizeChange(function(){return o.onCharSizeChanged()})),o.register(u.addDisposableDomListener(window,"resize",function(){return o.onDevicePixelRatioChange()})),"IntersectionObserver"in window){var l=new IntersectionObserver(function(e){return o._onIntersectionChange(e[e.length-1])},{threshold:0});l.observe(r),o.register({dispose:function(){return l.disconnect()}})}return o}return n(t,e),Object.defineProperty(t.prototype,"onDimensionsChange",{get:function(){return this._onDimensionsChange.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRender",{get:function(){return this._onRender.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onRefreshRequest",{get:function(){return this._onRefreshRequest.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dimensions",{get:function(){return this._renderer.dimensions},enumerable:!0,configurable:!0}),t.prototype._onIntersectionChange=function(e){this._isPaused=0===e.intersectionRatio,!this._isPaused&&this._needsFullRefresh&&(this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)},t.prototype.refreshRows=function(e,t){this._isPaused?this._needsFullRefresh=!0:this._renderDebouncer.refresh(e,t,this._rowCount)},t.prototype._renderRows=function(e,t){this._renderer.renderRows(e,t),this._onRender.fire({start:e,end:t})},t.prototype.resize=function(e,t){this._rowCount=t,this._fireOnCanvasResize()},t.prototype.changeOptions=function(){this._renderer.onOptionsChanged(),this._fireOnCanvasResize()},t.prototype._fireOnCanvasResize=function(){this._renderer.dimensions.canvasWidth===this._canvasWidth&&this._renderer.dimensions.canvasHeight===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.dimensions)},t.prototype.dispose=function(){this._renderer.dispose()},t.prototype.setRenderer=function(e){this._renderer.dispose(),this._renderer=e,this.refreshRows(0,this._rowCount-1)},t.prototype._fullRefresh=function(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)},t.prototype.setColors=function(e){this._renderer.setColors(e),this._fullRefresh()},t.prototype.onDevicePixelRatioChange=function(){this._renderer.onDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1)},t.prototype.onResize=function(e,t){this._renderer.onResize(e,t),this._fullRefresh()},t.prototype.onCharSizeChanged=function(){this._renderer.onCharSizeChanged()},t.prototype.onBlur=function(){this._renderer.onBlur()},t.prototype.onFocus=function(){this._renderer.onFocus()},t.prototype.onSelectionChanged=function(e,t,i){this._renderer.onSelectionChanged(e,t,i)},t.prototype.onCursorMove=function(){this._renderer.onCursorMove()},t.prototype.clear=function(){this._renderer.clear()},t.prototype.registerCharacterJoiner=function(e){return this._renderer.registerCharacterJoiner(e)},t.prototype.deregisterCharacterJoiner=function(e){return this._renderer.deregisterCharacterJoiner(e)},t=s([o(3,f.IOptionsService),o(4,_.ICharSizeService)],t)}(l.Disposable);t.RenderService=d},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(1),n=i(10),s=i(31);t.DEFAULT_BELL_SOUND="data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq",t.DEFAULT_OPTIONS=Object.freeze({cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",bellSound:t.DEFAULT_BELL_SOUND,bellStyle:"none",drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",lineHeight:1,letterSpacing:0,logLevel:"info",scrollback:1e3,scrollSensitivity:1,screenReaderMode:!1,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,disableStdin:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:n.isMac,rendererType:"canvas",windowsMode:!1,convertEol:!1,termName:"xterm",screenKeys:!1,cancelEvents:!1,useFlowControl:!1,wordSeparator:" ()[]{}',:;\""});var o=["cols","rows"],a=function(){function e(e){var i=this;this._onOptionChange=new r.EventEmitter,this.options=s.clone(t.DEFAULT_OPTIONS),Object.keys(e).forEach(function(t){if(t in i.options){var r=e[t];i.options[t]=r}})}return Object.defineProperty(e.prototype,"onOptionChange",{get:function(){return this._onOptionChange.event},enumerable:!0,configurable:!0}),e.prototype.setOption=function(e,i){if(!(e in t.DEFAULT_OPTIONS))throw new Error('No option with key "'+e+'"');if(-1!==o.indexOf(e))throw new Error('Option "'+e+'" can only be set in the constructor');this.options[e]!==i&&(i=this._sanitizeAndValidateOption(e,i),this.options[e]!==i&&(this.options[e]=i,this._onOptionChange.fire(e)))},e.prototype._sanitizeAndValidateOption=function(e,i){switch(e){case"bellStyle":case"cursorStyle":case"fontWeight":case"fontWeightBold":case"rendererType":case"wordSeparator":i||(i=t.DEFAULT_OPTIONS[e]);break;case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(e+" cannot be less than 1, value: "+i);break;case"scrollback":if((i=Math.min(i,4294967295))<0)throw new Error(e+" cannot be less than 0, value: "+i);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(e+" cannot be less than or equal to 0, value: "+i)}return i},e.prototype.getOption=function(e){if(!(e in t.DEFAULT_OPTIONS))throw new Error('No option with key "'+e+'"');return this.options[e]},e}();t.OptionsService=a},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(1),a=function(){function e(e,t,i){this.document=e,this.parentElement=t,this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=new o.EventEmitter,this._measureStrategy=new c(e,t,this._optionsService)}return Object.defineProperty(e.prototype,"hasValidSize",{get:function(){return this.width>0&&this.height>0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onCharSizeChange",{get:function(){return this._onCharSizeChange.event},enumerable:!0,configurable:!0}),e.prototype.measure=function(){var e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())},e=r([n(2,s.IOptionsService)],e)}();t.CharSizeService=a;var c=function(){function e(e,t,i){this._document=e,this._parentElement=t,this._optionsService=i,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W",this._measureElement.setAttribute("aria-hidden","true"),this._parentElement.appendChild(this._measureElement)}return e.prototype.measure=function(){this._measureElement.style.fontFamily=this._optionsService.options.fontFamily,this._measureElement.style.fontSize=this._optionsService.options.fontSize+"px";var e=this._measureElement.getBoundingClientRect();return 0!==e.width&&0!==e.height&&(this._result.width=e.width,this._result.height=Math.ceil(e.height)),this._result},e}()},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(63);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;var a=function(){function e(e){this._optionsService=e,this.cols=Math.max(e.options.cols,t.MINIMUM_COLS),this.rows=Math.max(e.options.rows,t.MINIMUM_ROWS),this.buffers=new o.BufferSet(e,this)}return Object.defineProperty(e.prototype,"buffer",{get:function(){return this.buffers.active},enumerable:!0,configurable:!0}),e.prototype.resize=function(e,t){this.cols=e,this.rows=t},e.prototype.reset=function(){this.buffers=new o.BufferSet(this._optionsService,this)},e=r([n(0,s.IOptionsService)],e)}();t.BufferService=a},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(64),n=i(1),s=function(){function e(e,t){this.optionsService=e,this.bufferService=t,this._onBufferActivate=new n.EventEmitter,this._normal=new r.Buffer(!0,e,t),this._normal.fillViewportRows(),this._alt=new r.Buffer(!1,e,t),this._activeBuffer=this._normal,this.setupTabStops()}return Object.defineProperty(e.prototype,"onBufferActivate",{get:function(){return this._onBufferActivate.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alt",{get:function(){return this._alt},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"active",{get:function(){return this._activeBuffer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"normal",{get:function(){return this._normal},enumerable:!0,configurable:!0}),e.prototype.activateNormalBuffer=function(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))},e.prototype.activateAltBuffer=function(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))},e.prototype.resize=function(e,t){this._normal.resize(e,t),this._alt.resize(e,t)},e.prototype.setupTabStops=function(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)},e}();t.BufferSet=s},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(65),n=i(15),s=i(4),o=i(3),a=i(66),c=i(67),l=i(17);t.MAX_BUFFER_SIZE=4294967295;var h=function(){function e(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.savedY=0,this.savedX=0,this.savedCurAttrData=n.DEFAULT_ATTR_DATA.clone(),this.savedCharset=l.DEFAULT_CHARSET,this.markers=[],this._nullCell=s.CellData.fromCharData([0,o.NULL_CELL_CHAR,o.NULL_CELL_WIDTH,o.NULL_CELL_CODE]),this._whitespaceCell=s.CellData.fromCharData([0,o.WHITESPACE_CELL_CHAR,o.WHITESPACE_CELL_WIDTH,o.WHITESPACE_CELL_CODE]),this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}return e.prototype.getNullCell=function(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg):(this._nullCell.fg=0,this._nullCell.bg=0),this._nullCell},e.prototype.getWhitespaceCell=function(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0),this._whitespaceCell},e.prototype.getBlankLine=function(e,t){return new n.BufferLine(this._bufferService.cols,this.getNullCell(e),t)},Object.defineProperty(e.prototype,"hasScrollback",{get:function(){return this._hasScrollback&&this.lines.maxLength>this._rows},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isCursorInViewport",{get:function(){var e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows},enumerable:!0,configurable:!0}),e.prototype._getCorrectBufferLength=function(e){if(!this._hasScrollback)return e;var i=e+this._optionsService.options.scrollback;return i>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:i},e.prototype.fillViewportRows=function(e){if(0===this.lines.length){void 0===e&&(e=n.DEFAULT_ATTR_DATA);for(var t=this._rows;t--;)this.lines.push(this.getBlankLine(e))}},e.prototype.clear=function(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()},e.prototype.resize=function(e,t){var i=this.getNullCell(n.DEFAULT_ATTR_DATA),r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(var s=0;s<this.lines.length;s++)this.lines.get(s).resize(e,i);var o=0;if(this._rows<t)for(var a=this._rows;a<t;a++)this.lines.length<t+this.ybase&&(this._optionsService.options.windowsMode?this.lines.push(new n.BufferLine(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new n.BufferLine(e,i)));else for(a=this._rows;a>t;a--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){var c=this.lines.length-r;c>0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(s=0;s<this.lines.length;s++)this.lines.get(s).resize(e,i);this._cols=e,this._rows=t},Object.defineProperty(e.prototype,"_isReflowEnabled",{get:function(){return this._hasScrollback&&!this._optionsService.options.windowsMode},enumerable:!0,configurable:!0}),e.prototype._reflow=function(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))},e.prototype._reflowLarger=function(e,t){var i=a.reflowLargerGetLinesToRemove(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(n.DEFAULT_ATTR_DATA));if(i.length>0){var r=a.reflowLargerCreateNewLayout(this.lines,i);a.reflowLargerApplyNewLayout(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}},e.prototype._reflowLargerAdjustViewport=function(e,t,i){for(var r=this.getNullCell(n.DEFAULT_ATTR_DATA),s=i;s-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new n.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)},e.prototype._reflowSmaller=function(e,t){for(var i=this.getNullCell(n.DEFAULT_ATTR_DATA),r=[],s=0,o=this.lines.length-1;o>=0;o--){var c=this.lines.get(o);if(!(!c||!c.isWrapped&&c.getTrimmedLength()<=e)){for(var l=[c];c.isWrapped&&o>0;)c=this.lines.get(--o),l.unshift(c);var h=this.ybase+this.y;if(!(h>=o&&h<o+l.length)){var u=l[l.length-1].getTrimmedLength(),f=a.reflowSmallerGetNewLineLengths(l,this._cols,e),_=f.length-l.length,d=void 0;d=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+_):Math.max(0,this.lines.length-this.lines.maxLength+_);for(var p=[],v=0;v<_;v++){var g=this.getBlankLine(n.DEFAULT_ATTR_DATA,!0);p.push(g)}p.length>0&&(r.push({start:o+l.length+s,newLines:p}),s+=p.length),l.push.apply(l,p);var y=f.length-1,m=f[y];0===m&&(m=f[--y]);for(var b=l.length-_-1,C=u;b>=0;){var S=Math.min(C,m);if(l[y].copyCellsFrom(l[b],C-S,m-S,S,!0),0===(m-=S)&&(m=f[--y]),0===(C-=S)){b--;var w=Math.max(b,0);C=a.getWrappedLineTrimmedLength(l,w,this._cols)}}for(v=0;v<l.length;v++)f[v]<e&&l[v].setCell(f[v],i);for(var E=_-d;E-- >0;)0===this.ybase?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+s)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+_,this.ybase+t-1)}}}if(r.length>0){var L=[],A=[];for(v=0;v<this.lines.length;v++)A.push(this.lines.get(v));var x=this.lines.length,k=x-1,D=0,T=r[D];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+s);var R=0;for(v=Math.min(this.lines.maxLength-1,x+s-1);v>=0;v--)if(T&&T.start>k+R){for(var M=T.newLines.length-1;M>=0;M--)this.lines.set(v--,T.newLines[M]);v++,L.push({index:k+1,amount:T.newLines.length}),R+=T.newLines.length,T=r[++D]}else this.lines.set(v,A[k--]);var O=0;for(v=L.length-1;v>=0;v--)L[v].index+=O,this.lines.onInsertEmitter.fire(L[v]),O+=L[v].amount;var P=Math.max(0,x+s-this.lines.maxLength);P>0&&this.lines.onTrimEmitter.fire(P)}},e.prototype.stringIndexToBufferIndex=function(e,t,i){for(void 0===i&&(i=!1);t;){var r=this.lines.get(e);if(!r)return[-1,-1];for(var n=i?r.getTrimmedLength():r.length,s=0;s<n;++s)if(r.get(s)[o.CHAR_DATA_WIDTH_INDEX]&&(t-=r.get(s)[o.CHAR_DATA_CHAR_INDEX].length||1),t<0)return[e,s];e++}return[e,0]},e.prototype.translateBufferLineToString=function(e,t,i,r){void 0===i&&(i=0);var n=this.lines.get(e);return n?n.translateToString(t,i,r):""},e.prototype.getWrappedRangeForLine=function(e){for(var t=e,i=e;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}},e.prototype.setupTabStops=function(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.options.tabStopWidth)this.tabs[e]=!0},e.prototype.prevStop=function(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e},e.prototype.nextStop=function(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e},e.prototype.addMarker=function(e){var t=this,i=new c.Marker(e);return this.markers.push(i),i.register(this.lines.onTrim(function(e){i.line-=e,i.line<0&&i.dispose()})),i.register(this.lines.onInsert(function(e){i.line>=e.index&&(i.line+=e.amount)})),i.register(this.lines.onDelete(function(e){i.line>=e.index&&i.line<e.index+e.amount&&i.dispose(),i.line>e.index&&(i.line-=e.amount)})),i.register(i.onDispose(function(){return t._removeMarker(i)})),i},e.prototype._removeMarker=function(e){this.markers.splice(this.markers.indexOf(e),1)},e.prototype.iterator=function(e,t,i,r,n){return new u(this,e,t,i,r,n)},e}();t.Buffer=h;var u=function(){function e(e,t,i,r,n,s){void 0===i&&(i=0),void 0===r&&(r=e.lines.length),void 0===n&&(n=0),void 0===s&&(s=0),this._buffer=e,this._trimRight=t,this._startIndex=i,this._endIndex=r,this._startOverscan=n,this._endOverscan=s,this._startIndex<0&&(this._startIndex=0),this._endIndex>this._buffer.lines.length&&(this._endIndex=this._buffer.lines.length),this._current=this._startIndex}return e.prototype.hasNext=function(){return this._current<this._endIndex},e.prototype.next=function(){var e=this._buffer.getWrappedRangeForLine(this._current);e.first<this._startIndex-this._startOverscan&&(e.first=this._startIndex-this._startOverscan),e.last>this._endIndex+this._endOverscan&&(e.last=this._endIndex+this._endOverscan),e.first=Math.max(e.first,0),e.last=Math.min(e.last,this._buffer.lines.length);for(var t="",i=e.first;i<=e.last;++i)t+=this._buffer.translateBufferLineToString(i,this._trimRight);return this._current=e.last+1,{range:e,content:t}},e}();t.BufferStringIterator=u},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=i(1),n=function(){function e(e){this._maxLength=e,this.onDeleteEmitter=new r.EventEmitter,this.onInsertEmitter=new r.EventEmitter,this.onTrimEmitter=new r.EventEmitter,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}return Object.defineProperty(e.prototype,"onDelete",{get:function(){return this.onDeleteEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onInsert",{get:function(){return this.onInsertEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTrim",{get:function(){return this.onTrimEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxLength",{get:function(){return this._maxLength},set:function(e){if(this._maxLength!==e){for(var t=new Array(e),i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return this._length},set:function(e){if(e>this._length)for(var t=this._length;t<e;t++)this._array[t]=void 0;this._length=e},enumerable:!0,configurable:!0}),e.prototype.get=function(e){return this._array[this._getCyclicIndex(e)]},e.prototype.set=function(e,t){this._array[this._getCyclicIndex(e)]=t},e.prototype.push=function(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++},e.prototype.recycle=function(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]},Object.defineProperty(e.prototype,"isFull",{get:function(){return this._length===this._maxLength},enumerable:!0,configurable:!0}),e.prototype.pop=function(){return this._array[this._getCyclicIndex(this._length---1)]},e.prototype.splice=function(e,t){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];if(t){for(var n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t}for(n=this._length-1;n>=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(n=0;n<i.length;n++)this._array[this._getCyclicIndex(e+n)]=i[n];if(this._length+i.length>this._maxLength){var s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length},e.prototype.trimStart=function(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)},e.prototype.shiftElements=function(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(var r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));var n=e+t+i-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(r=0;r<t;r++)this.set(e+r+i,this.get(e+r))}},e.prototype._getCyclicIndex=function(e){return(this._startIndex+e)%this._maxLength},e}();t.CircularList=n},function(e,t,i){"use strict";function r(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();var r=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),n=2===e[t+1].getWidth(0);return r&&n?i-1:i}Object.defineProperty(t,"__esModule",{value:!0}),t.reflowLargerGetLinesToRemove=function(e,t,i,n,s){for(var o=[],a=0;a<e.length-1;a++){var c=a,l=e.get(++c);if(l.isWrapped){for(var h=[e.get(a)];c<e.length&&l.isWrapped;)h.push(l),l=e.get(++c);if(n>=a&&n<c)a+=h.length-1;else{for(var u=0,f=r(h,u,t),_=1,d=0;_<h.length;){var p=r(h,_,t),v=p-d,g=i-f,y=Math.min(v,g);h[u].copyCellsFrom(h[_],d,f,y,!1),(f+=y)===i&&(u++,f=0),(d+=y)===p&&(_++,d=0),0===f&&0!==u&&2===h[u-1].getWidth(i-1)&&(h[u].copyCellsFrom(h[u-1],i-1,f++,1,!1),h[u-1].setCell(i-1,s))}h[u].replaceCells(f,i,s);for(var m=0,b=h.length-1;b>0&&(b>u||0===h[b].getTrimmedLength());b--)m++;m>0&&(o.push(a+h.length-m),o.push(m)),a+=h.length-1}}}return o},t.reflowLargerCreateNewLayout=function(e,t){for(var i=[],r=0,n=t[r],s=0,o=0;o<e.length;o++)if(n===o){var a=t[++r];e.onDeleteEmitter.fire({index:o-s,amount:a}),o+=a-1,s+=a,n=t[++r]}else i.push(o);return{layout:i,countRemoved:s}},t.reflowLargerApplyNewLayout=function(e,t){for(var i=[],r=0;r<t.length;r++)i.push(e.get(t[r]));for(r=0;r<i.length;r++)e.set(r,i[r]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,i){for(var n=[],s=e.map(function(i,n){return r(e,n,t)}).reduce(function(e,t){return e+t}),o=0,a=0,c=0;c<s;){if(s-c<i){n.push(s-c);break}o+=i;var l=r(e,a,t);o>l&&(o-=l,a++);var h=2===e[a].getWidth(o-1);h&&o--;var u=h?i-1:i;n.push(u),c+=u}return n},t.getWrappedLineTrimmedLength=r},function(e,t,i){"use strict";var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});Object.defineProperty(t,"__esModule",{value:!0});var s=i(1),o=function(e){function t(i){var r=e.call(this)||this;return r.line=i,r._id=t._nextId++,r.isDisposed=!1,r._onDispose=new s.EventEmitter,r}return n(t,e),Object.defineProperty(t.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{get:function(){return this._onDispose.event},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire())},t._nextId=1,t}(i(2).Disposable);t.Marker=o},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(5),o=i(28),a=function(){function e(e,t){this._renderService=e,this._charSizeService=t}return e.prototype.getCoords=function(e,t,i,r,n){return o.getCoords(e,t,i,r,this._charSizeService.hasValidSize,this._renderService.dimensions.actualCellWidth,this._renderService.dimensions.actualCellHeight,n)},e.prototype.getRawByteCoords=function(e,t,i,r){var n=this.getCoords(e,t,i,r);return o.getRawByteCoords(n)},e=r([n(0,s.IRenderService),n(1,s.ICharSizeService)],e)}();t.MouseService=a},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(1),a=i(31),c=Object.freeze({applicationCursorKeys:!1}),l=function(){function e(e,t,i,r){this._scrollToBottom=e,this._bufferService=t,this._logService=i,this._optionsService=r,this._onData=new o.EventEmitter,this._onUserInput=new o.EventEmitter,this.decPrivateModes=a.clone(c)}return Object.defineProperty(e.prototype,"onData",{get:function(){return this._onData.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onUserInput",{get:function(){return this._onUserInput.event},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this.decPrivateModes=a.clone(c)},e.prototype.triggerDataEvent=function(e,t){if(void 0===t&&(t=!1),!this._optionsService.options.disableStdin){var i=this._bufferService.buffer;i.ybase!==i.ydisp&&this._scrollToBottom(),t&&this._onUserInput.fire(),this._logService.debug('sending data "'+e+'"',function(){return e.split("").map(function(e){return e.charCodeAt(0)})}),this._onData.fire(e)}},e=r([n(1,s.IBufferService),n(2,s.ILogService),n(3,s.IOptionsService)],e)}();t.CoreService=l},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}},s=this&&this.__spreadArrays||function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var r=Array(e),n=0;for(t=0;t<i;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,n++)r[n]=s[o];return r};Object.defineProperty(t,"__esModule",{value:!0});var o,a=i(0);!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(o=t.LogLevel||(t.LogLevel={}));var c={debug:o.DEBUG,info:o.INFO,warn:o.WARN,error:o.ERROR,off:o.OFF},l=function(){function e(e){var t=this;this._optionsService=e,this._updateLogLevel(),this._optionsService.onOptionChange(function(e){"logLevel"===e&&t._updateLogLevel()})}return e.prototype._updateLogLevel=function(){this._logLevel=c[this._optionsService.options.logLevel]},e.prototype._evalLazyOptionalParams=function(e){for(var t=0;t<e.length;t++)"function"==typeof e[t]&&(e[t]=e[t]())},e.prototype._log=function(e,t,i){this._evalLazyOptionalParams(i),e.call.apply(e,s([console,"xterm.js: "+t],i))},e.prototype.debug=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.DEBUG&&this._log(console.log,e,t)},e.prototype.info=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.INFO&&this._log(console.info,e,t)},e.prototype.warn=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.WARN&&this._log(console.warn,e,t)},e.prototype.error=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this._logLevel<=o.ERROR&&this._log(console.error,e,t)},e=r([n(0,a.IOptionsService)],e)}();t.LogService=l},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=function(){function e(e){this._bufferService=e,this.clearRange()}return Object.defineProperty(e.prototype,"start",{get:function(){return this._start},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"end",{get:function(){return this._end},enumerable:!0,configurable:!0}),e.prototype.clearRange=function(){this._start=this._bufferService.buffer.y,this._end=this._bufferService.buffer.y},e.prototype.markDirty=function(e){e<this._start?this._start=e:e>this._end&&(this._end=e)},e.prototype.markRangeDirty=function(e,t){if(e>t){var i=e;e=t,t=i}e<this._start&&(this._start=e),t>this._end&&(this._end=t)},e.prototype.markAllDirty=function(){this.markRangeDirty(0,this._bufferService.rows-1)},e=r([n(0,s.IBufferService)],e)}();t.DirtyRowService=o},function(e,t,i){"use strict";var r=this&&this.__spreadArrays||function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var r=Array(e),n=0;for(t=0;t<i;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,n++)r[n]=s[o];return r};Object.defineProperty(t,"__esModule",{value:!0});var n=i(0),s=i(13),o=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._entries=new Map;for(var i=0,r=e;i<r.length;i++){var n=r[i],s=n[0],o=n[1];this.set(s,o)}}return e.prototype.set=function(e,t){var i=this._entries.get(e);return this._entries.set(e,t),i},e.prototype.forEach=function(e){this._entries.forEach(function(t,i){return e(i,t)})},e.prototype.has=function(e){return this._entries.has(e)},e.prototype.get=function(e){return this._entries.get(e)},e}();t.ServiceCollection=o;var a=function(){function e(){this._services=new o,this._services.set(n.IInstantiationService,this)}return e.prototype.setService=function(e,t){this._services.set(e,t)},e.prototype.createInstance=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=s.getServiceDependencies(e).sort(function(e,t){return e.index-t.index}),o=[],a=0,c=n;a<c.length;a++){var l=c[a],h=this._services.get(l.id);if(!h)throw new Error("[createInstance] "+e.name+" depends on UNKNOWN service "+l.id+".");o.push(h)}var u=n.length>0?n[0].index:t.length;if(t.length!==u)throw new Error("[createInstance] First service dependency of "+e.name+" at position "+(u+1)+" conflicts with "+t.length+" static arguments");return new(e.bind.apply(e,r([void 0],r(t,o))))},e}();t.InstantiationService=a},function(e,t,i){"use strict";var r=this&&this.__decorate||function(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},n=this&&this.__param||function(e,t){return function(i,r){t(i,r,e)}};Object.defineProperty(t,"__esModule",{value:!0});var s=i(0),o=i(1),a={NONE:{events:0,restrict:function(){return!1}},X10:{events:1,restrict:function(e){return 4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)}},VT200:{events:19,restrict:function(e){return 32!==e.action}},DRAG:{events:23,restrict:function(e){return 32!==e.action||3!==e.button}},ANY:{events:31,restrict:function(e){return!0}}};function c(e,t){var i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0!==e.action||t||(i|=3)),i}var l=String.fromCharCode,h={DEFAULT:function(e){var t=[c(e,!1)+32,e.col+32,e.row+32];return t=t.map(function(e){return e>127?127:e}),"\e[M"+l(t[0])+l(t[1])+l(t[2])},SGR:function(e){var t=0===e.action&&4!==e.button?"m":"M";return"\e[<"+c(e,!0)+";"+e.col+";"+e.row+t}},u=function(){function e(e,t){var i=this;this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._onProtocolChange=new o.EventEmitter,this._lastEvent=null,Object.keys(a).forEach(function(e){return i.addProtocol(e,a[e])}),Object.keys(h).forEach(function(e){return i.addEncoding(e,h[e])}),this.reset()}return e.prototype.addProtocol=function(e,t){this._protocols[e]=t},e.prototype.addEncoding=function(e,t){this._encodings[e]=t},Object.defineProperty(e.prototype,"activeProtocol",{get:function(){return this._activeProtocol},set:function(e){if(!this._protocols[e])throw new Error('unknown protocol "'+e+'"');this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activeEncoding",{get:function(){return this._activeEncoding},set:function(e){if(!this._encodings[e])throw new Error('unknown encoding "'+e+'"');this._activeEncoding=e},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null},Object.defineProperty(e.prototype,"onProtocolChange",{get:function(){return this._onProtocolChange.event},enumerable:!0,configurable:!0}),e.prototype.triggerMouseEvent=function(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows)return!1;if(4===e.button&&32===e.action)return!1;if(3===e.button&&32!==e.action)return!1;if(4!==e.button&&(2===e.action||3===e.action))return!1;if(e.col++,e.row++,32===e.action&&this._lastEvent&&this._compareEvents(this._lastEvent,e))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;var t=this._encodings[this._activeEncoding](e);return this._coreService.triggerDataEvent(t,!0),this._lastEvent=e,!0},e.prototype.explainEvents=function(e){return{DOWN:!!(1&e),UP:!!(2&e),DRAG:!!(4&e),MOVE:!!(8&e),WHEEL:!!(16&e)}},e.prototype._compareEvents=function(e,t){return e.col===t.col&&(e.row===t.row&&(e.button===t.button&&(e.action===t.action&&(e.ctrl===t.ctrl&&(e.alt===t.alt&&e.shift===t.shift)))))},e=r([n(0,s.IBufferService),n(1,s.ICoreService)],e)}();t.CoreMouseService=u},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e){this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0}return e.prototype.writeSync=function(e){if(this._writeBuffer.length){for(var t=this._bufferOffset;t<this._writeBuffer.length;++t){var i=this._writeBuffer[t],r=this._callbacks[t];this._action(i),r&&r()}this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=2147483647}this._action(e)},e.prototype.write=function(e,t){var i=this;if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");this._writeBuffer.length||(this._bufferOffset=0,setTimeout(function(){return i._innerWrite()})),this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)},e.prototype._innerWrite=function(){for(var e=this,t=Date.now();this._writeBuffer.length>this._bufferOffset;){var i=this._writeBuffer[this._bufferOffset],r=this._callbacks[this._bufferOffset];if(this._bufferOffset++,this._action(i),this._pendingData-=i.length,r&&r(),Date.now()-t>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(function(){return e._innerWrite()},0)):(this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0)},e}();t.WriteBuffer=r},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this._addons=[]}return e.prototype.dispose=function(){for(var e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()},e.prototype.loadAddon=function(e,t){var i=this,r={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(r),t.dispose=function(){return i._wrappedAddonDispose(r)},t.activate(e)},e.prototype._wrappedAddonDispose=function(e){if(!e.isDisposed){for(var t=-1,i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(-1===t)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},e}();t.AddonManager=r}])});
+//# sourceMappingURL=xterm.js.map
\ No newline at end of file
diff --git a/node_modules/xterm/lib/xterm.js.map b/node_modules/xterm/lib/xterm.js.map
new file mode 100644 (file)
index 0000000..9afd254
--- /dev/null
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap","webpack:///./src/common/services/Services.ts","webpack:///./src/common/EventEmitter.ts","webpack:///./src/common/Lifecycle.ts","webpack:///./src/common/buffer/Constants.ts","webpack:///./src/common/buffer/CellData.ts","webpack:///./src/browser/services/Services.ts","webpack:///./src/common/buffer/AttributeData.ts","webpack:///./src/browser/Lifecycle.ts","webpack:///./src/common/input/TextDecoder.ts","webpack:///./src/browser/renderer/atlas/Constants.ts","webpack:///./src/common/Platform.ts","webpack:///./src/common/data/EscapeSequences.ts","webpack:///./src/browser/renderer/BaseRenderLayer.ts","webpack:///./src/common/services/ServiceRegistry.ts","webpack:///./src/common/TypedArrayUtils.ts","webpack:///./src/common/buffer/BufferLine.ts","webpack:///./src/browser/LocalizableStrings.ts","webpack:///./src/common/data/Charsets.ts","webpack:///./src/common/CharWidth.ts","webpack:///./src/common/parser/Params.ts","webpack:///./src/common/parser/OscParser.ts","webpack:///./src/common/parser/Constants.ts","webpack:///./src/common/parser/DcsParser.ts","webpack:///./src/browser/renderer/atlas/CharAtlasCache.ts","webpack:///./src/browser/renderer/atlas/CharAtlasUtils.ts","webpack:///./src/browser/ColorManager.ts","webpack:///./src/browser/renderer/RendererUtils.ts","webpack:///./src/browser/renderer/CharacterJoinerRegistry.ts","webpack:///./src/browser/input/Mouse.ts","webpack:///./src/browser/RenderDebouncer.ts","webpack:///./src/browser/ScreenDprMonitor.ts","webpack:///./src/common/Clone.ts","webpack:///./src/public/Terminal.ts","webpack:///./src/Terminal.ts","webpack:///./src/browser/input/CompositionHelper.ts","webpack:///./src/browser/Viewport.ts","webpack:///./src/browser/Clipboard.ts","webpack:///./src/InputHandler.ts","webpack:///./src/common/parser/EscapeSequenceParser.ts","webpack:///./src/renderer/Renderer.ts","webpack:///./src/browser/renderer/TextRenderLayer.ts","webpack:///./src/browser/renderer/GridCache.ts","webpack:///./src/browser/renderer/atlas/DynamicCharAtlas.ts","webpack:///./src/browser/renderer/atlas/BaseCharAtlas.ts","webpack:///./src/browser/renderer/atlas/LRUMap.ts","webpack:///./src/browser/renderer/SelectionRenderLayer.ts","webpack:///./src/renderer/CursorRenderLayer.ts","webpack:///./src/browser/renderer/LinkRenderLayer.ts","webpack:///./src/browser/Linkifier.ts","webpack:///./src/browser/services/SelectionService.ts","webpack:///./src/browser/selection/SelectionModel.ts","webpack:///./src/browser/input/MoveToCell.ts","webpack:///./src/browser/services/SoundService.ts","webpack:///./src/browser/MouseZoneManager.ts","webpack:///./src/AccessibilityManager.ts","webpack:///./src/renderer/dom/DomRenderer.ts","webpack:///./src/browser/renderer/dom/DomRendererRowFactory.ts","webpack:///./src/common/input/Keyboard.ts","webpack:///./src/WindowsMode.ts","webpack:///./src/browser/services/RenderService.ts","webpack:///./src/common/services/OptionsService.ts","webpack:///./src/browser/services/CharSizeService.ts","webpack:///./src/common/services/BufferService.ts","webpack:///./src/common/buffer/BufferSet.ts","webpack:///./src/common/buffer/Buffer.ts","webpack:///./src/common/CircularList.ts","webpack:///./src/common/buffer/BufferReflow.ts","webpack:///./src/common/buffer/Marker.ts","webpack:///./src/browser/services/MouseService.ts","webpack:///./src/common/services/CoreService.ts","webpack:///./src/common/services/LogService.ts","webpack:///./src/common/services/DirtyRowService.ts","webpack:///./src/common/services/InstantiationService.ts","webpack:///./src/common/services/CoreMouseService.ts","webpack:///./src/common/input/WriteBuffer.ts","webpack:///./src/public/AddonManager.ts"],"names":["root","factory","exports","module","define","amd","a","i","window","installedModules","__webpack_require__","moduleId","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","IBufferService","createDecorator","ICoreMouseService","ICoreService","IDirtyRowService","IInstantiationService","ILogService","IOptionsService","_listeners","this","_event","listener","push","dispose","length","splice","fire","data","queue","undefined","EventEmitter","_disposables","_isDisposed","forEach","register","unregister","index","indexOf","Disposable","DEFAULT_COLOR","DEFAULT_ATTR","CHAR_DATA_ATTR_INDEX","CHAR_DATA_CHAR_INDEX","CHAR_DATA_WIDTH_INDEX","CHAR_DATA_CODE_INDEX","NULL_CELL_CHAR","NULL_CELL_WIDTH","NULL_CELL_CODE","WHITESPACE_CELL_CHAR","WHITESPACE_CELL_WIDTH","WHITESPACE_CELL_CODE","content","fg","bg","combinedData","fromCharData","obj","CellData","setFromCharData","isCombined","getWidth","getChars","stringFromCodePoint","getCode","charCodeAt","combined","code","second","getAsCharData","AttributeData","ICharSizeService","IMouseService","IRenderService","ISelectionService","ISoundService","toColorRGB","fromColorRGB","clone","newObj","isInverse","isBold","isUnderline","isBlink","isInvisible","isItalic","isDim","getFgColorMode","getBgColorMode","isFgRGB","isBgRGB","isFgPalette","isBgPalette","isFgDefault","isBgDefault","getFgColor","getBgColor","node","type","handler","useCapture","addEventListener","removeEventListener","codePoint","String","fromCharCode","start","end","result","codepoint","_interim","clear","decode","input","target","size","startPos","StringToUtf32","interim","Uint8Array","fill","byte1","byte2","byte3","byte4","discardInterim","cp","pos","tmp","missing","fourStop","Utf8ToUtf32","INVERTED_DEFAULT_COLOR","DIM_OPACITY","CHAR_ATLAS_CELL_SPACING","isNode","navigator","userAgent","platform","contains","arr","el","isFirefox","isSafari","test","isMac","isIpad","isIphone","isWindows","isLinux","C0","NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL","BS","HT","LF","VT","FF","CR","SO","SI","DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB","CAN","EM","SUB","ESC","FS","GS","RS","US","SP","DEL","C1","PAD","HOP","BPH","NBH","IND","NEL","SSA","ESA","HTS","HTJ","VTS","PLD","PLU","RI","SS2","SS3","DCS","PU1","PU2","STS","CCH","MW","SPA","EPA","SOS","SGCI","SCI","CSI","ST","OSC","PM","APC","_container","id","zIndex","_alpha","_colors","_rendererId","_bufferService","_optionsService","_scaledCharWidth","_scaledCharHeight","_scaledCellWidth","_scaledCellHeight","_scaledCharLeft","_scaledCharTop","_currentGlyphIdentifier","chars","bold","dim","italic","_canvas","document","createElement","classList","add","style","toString","_initCanvas","appendChild","removeChild","_charAtlas","_ctx","throwIfFalsy","getContext","alpha","_clearAll","onOptionsChanged","onBlur","onFocus","onCursorMove","onGridChanged","startRow","endRow","onSelectionChanged","columnSelectMode","setColors","colorSet","_refreshCharAtlas","_setTransparency","oldCanvas","cloneNode","replaceChild","rows","acquireCharAtlas","options","warmUp","resize","scaledCellWidth","scaledCellHeight","scaledCharWidth","scaledCharHeight","scaledCharLeft","scaledCharTop","width","scaledCanvasWidth","height","scaledCanvasHeight","canvasWidth","canvasHeight","_fillCells","x","y","fillRect","_fillBottomLineAtCells","devicePixelRatio","_fillLeftLineAtCell","_strokeRectAtCell","lineWidth","strokeRect","clearRect","fillStyle","background","css","_clearCells","_fillCharTrueColor","cell","font","_getFont","textBaseline","_clipRow","fillText","_drawChars","_drawUncachedChars","drawBoldTextInBrightColors","draw","save","join","ansi","foreground","globalAlpha","restore","beginPath","rect","cols","clip","fontWeightBold","fontWeight","fontSize","fontFamily","BaseRenderLayer","DI_TARGET","DI_DEPENDENCIES","storeServiceDependency","serviceRegistry","Map","ctor","has","decorator","arguments","Error","set","fillFallback","array","b","constructor","CELL_SIZE","DEFAULT_ATTR_DATA","freeze","fillCellData","isWrapped","_combined","_data","Uint32Array","setCell","hasWidth","getFg","getBg","hasContent","getCodePoint","getString","loadCell","startIndex","setCellFromCodePoint","addCodepointToCell","insertCells","deleteCells","replaceCells","subarray","keys","parseInt","copyFrom","line","newLine","BufferLine","getTrimmedLength","copyCellsFrom","src","srcCol","destCol","applyInReverse","srcData","srcCombinedKeys","translateToString","trimRight","startCol","endCol","Math","min","promptLabel","tooMuchOutput","CHARSETS","DEFAULT_CHARSET","wcwidth","opts","COMBINING_BMP","COMBINING_HIGH","control","table","nul","num","ucs","mid","max","bisearch","MAX_SUBPARAMS","maxLength","maxSubParamsLength","params","Int32Array","_subParams","_subParamsLength","_subParamsIdx","Uint16Array","_rejectDigits","_rejectSubDigits","_digitIsSub","fromArray","values","Params","Array","k","addSubParam","addParam","newParams","toArray","res","slice","reset","hasSubParams","idx","getSubParams","getSubParamsAll","addDigit","store","cur","_state","_id","_handlers","_handlerFb","addHandler","ident","handlerList","handlerIndex","setHandler","clearHandler","setHandlerFallback","_start","handlers","j","_put","put","utf32ToString","_end","success","OscParser","_handler","_hitLimit","PAYLOAD_LIMIT","ret","OscHandler","EMPTY_HANDLERS","_active","_ident","unhook","hook","DcsParser","_params","DcsHandler","charAtlasCache","rendererId","colors","newConfig","generateConfig","ownedByIndex","entry","ownedBy","configEquals","config","atlas","newEntry","DynamicCharAtlas","clonedColors","cursor","cursorAccent","selection","allowTransparency","rgba","colorCode","DEFAULT_FOREGROUND","fromHex","DEFAULT_BACKGROUND","DEFAULT_CURSOR","DEFAULT_CURSOR_ACCENT","DEFAULT_SELECTION","toPaddedHex","DEFAULT_ANSI_COLORS","v","g","ch","canvas","ctx","globalCompositeOperation","_litmusColor","createLinearGradient","setTheme","theme","_parseColor","black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite","fallback","console","warn","getImageData","ColorManager","firstCell","_width","JoinedCellData","_characterJoiners","_nextCharacterJoinerId","_workCell","registerCharacterJoiner","joiner","deregisterCharacterJoiner","joinerId","getJoinedCharacters","row","buffer","lines","ranges","lineStr","rangeStartColumn","currentStringIndex","rangeStartStringIndex","rangeAttrFG","rangeAttrBG","joinedRanges","_getJoinedRanges","endIndex","lineData","text","substring","joinerRanges","CharacterJoinerRegistry","_mergeRanges","_stringRangesToCellRanges","currentRangeIndex","currentRangeStarted","currentRange","newRange","inRange","range","getCoordsRelativeToElement","event","element","getBoundingClientRect","clientX","left","clientY","top","colCount","rowCount","hasValidCharSize","actualCellWidth","actualCellHeight","isSelection","coords","ceil","_renderCallback","_animationFrame","cancelAnimationFrame","refresh","rowStart","rowEnd","_rowCount","_rowStart","_rowEnd","requestAnimationFrame","_innerRefresh","RenderDebouncer","_currentDevicePixelRatio","setListener","_listener","clearListener","_outerListener","_updateDpr","_resolutionMediaMatchList","removeListener","matchMedia","addListener","ScreenDprMonitor","val","depth","clonedObject","isArray","_core","Terminal","_addonManager","AddonManager","onLineFeed","onSelectionChange","onData","onTitleChange","onScroll","onKey","onRender","onResize","_parser","ParserApi","textarea","BufferApiView","markers","blur","focus","columns","_verifyIntegers","open","parent","attachCustomKeyEventHandler","customKeyEventHandler","registerLinkMatcher","regex","deregisterLinkMatcher","matcherId","addMarker","cursorYOffset","hasSelection","select","column","getSelection","getSelectionPosition","clearSelection","selectAll","selectLines","scrollLines","amount","scrollPages","pageCount","scrollToTop","scrollToBottom","scrollToLine","write","callback","writeUtf8","writeln","paste","getOption","optionsService","setOption","loadAddon","addon","Strings","Infinity","isNaN","_buffer","ydisp","ybase","getLine","BufferLineApiView","_line","getCell","BufferCellApiView","startColumn","endColumn","_x","addCsiHandler","addDcsHandler","addEscHandler","addOscHandler","browser","Browser","mouseEvents","_keyDownHandled","_blankLine","_onCursorMove","_onData","_onKey","_onLineFeed","_onRender","_onResize","_onScroll","_onSelectionChange","_onTitleChange","_onFocus","_onBlur","onA11yCharEmitter","onA11yTabEmitter","_instantiationService","InstantiationService","OptionsService","setService","createInstance","BufferService","_logService","LogService","_coreService","CoreService","e","_coreMouseService","CoreMouseService","_dirtyRowService","DirtyRowService","_setupOptionsListeners","_setup","_writeBuffer","WriteBuffer","_inputHandler","parse","_windowsMode","_renderService","_customKeyEventHandler","parentNode","_parent","body","cursorState","cursorHidden","applicationKeypad","originMode","insertMode","wraparoundMode","bracketedPasteMode","charset","gcharset","glevel","charsets","curAttrData","_eraseAttrData","currentParam","_userScrolling","InputHandler","linkifier","Linkifier","windowsMode","applyWindowsMode","buffers","active","eraseAttrData","preventScroll","activeElement","hasFocus","onOptionChange","_charSizeService","measure","setRenderer","_createRenderer","viewport","syncScrollArea","screenReaderMode","_accessibilityManager","AccessibilityManager","setupTabStops","_setTheme","_onTextAreaFocus","ev","sendFocus","triggerDataEvent","updateCursorStyle","showCursor","_onTextAreaBlur","remove","_initGlobal","_bindKeys","addDisposableDomListener","copyHandler","_selectionService","pasteHandlerWrapper","handlePasteEvent","button","rightClickHandler","screenElement","rightClickSelectsWord","moveTextAreaUnderMouseCursor","_keyUp","_keyDown","_keyPress","_compositionHelper","compositionstart","compositionupdate","compositionend","updateCompositionElements","_queueLinkification","_document","ownerDocument","dir","setAttribute","fragment","createDocumentFragment","_viewportElement","_viewportScrollArea","_helperContainer","tabIndex","CharSizeService","_compositionView","CompositionHelper","_theme","_colorManager","renderer","RenderService","_soundService","SoundService","_mouseService","MouseService","Viewport","suppressEvent","onThemeChange","onDimensionsChange","SelectionService","onRedrawRequest","onLinuxMouseSelection","_mouseZoneManager","MouseZoneManager","clearAll","attachToDom","onMouseDown","disable","enable","bindMouse","rendererType","Renderer","DomRenderer","self","sendEvent","but","action","getRawByteCoords","overrideType","buttons","deltaY","triggerMouseEvent","col","ctrl","ctrlKey","alt","altKey","shift","shiftKey","requestedEvents","mouseup","wheel","mousedrag","mousemove","eventListeners","cancel","preventDefault","onProtocolChange","events","logLevel","debug","explainEvents","activeProtocol","shouldForceSelection","hasScrollback","getLinesScrolled","sequence","decPrivateModes","applicationCursorKeys","abs","onWheel","onTouchStart","onTouchMove","refreshRows","linkifyRows","shouldColumnSelect","scroll","eraseAttr","getBlankLine","topRow","scrollTop","bottomRow","scrollBottom","willBufferBeTrimmed","isFull","recycle","scrollRegionHeight","shiftElements","markRangeDirty","disp","suppressScrollEvent","oldYdisp","scrollAmount","normal","setSelection","selectionText","selectionStart","selectionEnd","keydown","evaluateKeyboardEvent","macOptionIsMeta","scrollCount","_isThirdLevelShift","domEvent","thirdLevelKey","metaKey","keyCode","setgLevel","setgCharset","wasModifierKeyOnlyEvent","charCode","which","bell","_soundBell","playBellSound","_visualBell","clearTimeout","_visualBellTimer","setTimeout","MINIMUM_COLS","MINIMUM_ROWS","hasValidSize","is","term","termName","handleTitle","title","inputHandler","userScrolling","force","cancelEvents","stopPropagation","bellStyle","writeSync","_textarea","_isComposing","_isSendingComposition","_compositionPosition","textContent","_finalizeComposition","_handleAnyTextareaChanges","waitForPropagation","_clearTextareaPosition","oldValue","diff","replace","dontRecurse","isCursorInViewport","cellHeight","lineHeight","cursorTop","cursorLeft","compositionViewBounds","FALLBACK_SCROLL_BAR_WIDTH","_scrollLines","_scrollArea","scrollBarWidth","_currentRowHeight","_lastRecordedBufferLength","_lastRecordedViewportHeight","_lastRecordedBufferHeight","_lastTouchY","_lastScrollTop","_wheelPartialScroll","_refreshAnimationFrame","_ignoreNextScrollEvent","offsetWidth","backgroundColor","_refresh","immediate","dimensions","offsetHeight","newBufferHeight","round","newScrollTop","offsetParent","_bubbleScroll","scrollPosFromTop","cancelable","_getPixelsScrolled","_applyScrollModifier","deltaMode","WheelEvent","DOM_DELTA_LINE","DOM_DELTA_PAGE","DOM_DELTA_PIXEL","floor","modifier","fastScrollModifier","fastScrollSensitivity","scrollSensitivity","touches","pageY","prepareTextForTerminal","bracketTextForPaste","coreService","position","selectionService","clipboardData","setData","getData","shouldSelectWord","isClickInSelection","selectWordAtCursor","GLEVEL","concat","pt","cursorStyle","cursorBlink","_terminal","EscapeSequenceParser","_parseBuffer","_stringDecoder","_utf8Decoder","setCsiHandlerFallback","identifier","identToString","setEscHandlerFallback","setExecuteHandlerFallback","setOscHandlerFallback","setDcsHandlerFallback","payload","setPrintHandler","print","setCsiHandler","final","insertChars","intermediates","scrollLeft","cursorUp","scrollRight","cursorDown","cursorForward","cursorBackward","cursorNextLine","cursorPrecedingLine","cursorCharAbsolute","cursorPosition","cursorForwardTab","eraseInDisplay","prefix","eraseInLine","insertLines","deleteLines","deleteChars","scrollUp","scrollDown","eraseChars","cursorBackwardTab","charPosAbsolute","hPositionRelative","repeatPrecedingCharacter","sendDeviceAttributesPrimary","sendDeviceAttributesSecondary","linePosAbsolute","vPositionRelative","hVPosition","tabClear","setMode","setModePrivate","resetMode","resetModePrivate","charAttributes","deviceStatus","deviceStatusPrivate","softReset","setCursorStyle","setScrollRegion","saveCursor","restoreCursor","insertColumns","deleteColumns","setExecuteHandler","lineFeed","carriageReturn","backspace","tab","shiftOut","shiftIn","nextLine","tabSet","setOscHandler","setTitle","setEscHandler","reverseIndex","keypadApplicationMode","keypadNumericMode","selectDefaultCharset","flag","selectCharset","screenAlignmentPattern","setErrorHandler","state","error","setDcsHandler","DECRQSS","cursorStartX","cursorStartY","len","chWidth","curAttr","bufferRow","markDirty","getNullCell","precedingCodepoint","convertEol","_restrictCursor","originalX","nextStop","_setCursor","_moveCursor","diffToTop","diffToBottom","param","tabs","prevStop","_eraseInBufferLine","clearWrap","_resetBufferLine","scrollBackSize","trimStart","scrollBottomRowsOffset","scrollBottomAbsolute","savedCols","activeEncoding","activateAltBuffer","activateNormalBuffer","_extractColor","attr","accu","cSpace","advance","subparams","isBlinking","bottom","savedX","savedY","savedCurAttrData","savedCharset","_savedCharset","collectAndFlag","level","yOffset","markAllDirty","setDefault","next","addMany","codes","TransitionTable","VT500_TRANSITION_TABLE","blueprint","apply","map","unused","PRINTABLES","EXECUTABLES","states","TRANSITIONS","initialState","currentState","_collect","_printHandlerFb","_executeHandlerFb","_csiHandlerFb","_escHandlerFb","_errorHandlerFb","_printHandler","_executeHandlers","_csiHandlers","_escHandlers","_oscParser","_dcsParser","_errorHandler","_identifier","finalRange","intermediate","finalCode","reverse","clearPrintHandler","clearEscHandler","clearExecuteHandler","clearCsiHandler","clearDcsHandler","clearOscHandler","clearErrorHandler","transition","osc","dcs","collect","abort","handlersEsc","jj","nextRendererId","bufferService","_characterJoinerRegistry","_renderLayers","TextRenderLayer","SelectionRenderLayer","LinkRenderLayer","CursorRenderLayer","_devicePixelRatio","_updateDimensions","removeTerminalFromCache","onDevicePixelRatioChange","onCharSizeChanged","_runOperation","operation","renderRows","letterSpacing","container","characterJoinerRegistry","_characterWidth","_characterFont","_characterOverlapCache","GridCache","terminalFont","_forEachCell","firstRow","lastRow","joinerRegistry","isJoined","lastCharX","_isOverlapping","_drawBackground","startX","startY","prevFillStyle","nextFillStyle","_drawForeground","cache","beginFrame","overlaps","measureText","TEXTURE_WIDTH","TEXTURE_HEIGHT","TRANSPARENT_COLOR","getGlyphCacheKey","glyph","_config","_drawToCacheCount","_glyphsWaitingOnBitmap","_bitmapCommitTimeout","_bitmap","_cacheCanvas","_cacheCtx","tmpCanvas","_tmpCtx","_height","capacity","_cacheMap","LRUMap","prealloc","_canCache","glyphKey","cacheValue","_drawFromCache","peek","_drawToCache","_toCoordinateX","_toCoordinateY","isEmpty","cacheX","cacheY","drawImage","inBitmap","_getColorFromAnsiIndex","_getBackgroundColor","_getForegroundColor","fontStyle","imageData","color","offset","clearColor","putImageData","_addGlyphToBitmap","_generateBitmap","glyphsMovingToBitmap","createImageBitmap","then","bitmap","BaseCharAtlas","NoneCharAtlas","_didWarmUp","_doWarmUp","_map","_head","_tail","_nodePool","_unlinkNode","prev","_appendNode","tail","count","nodePool","peekValue","head","pop","_clearState","_didStateChange","viewportStartRow","viewportEndRow","viewportCappedStartRow","viewportCappedEndRow","startRowEndCol","middleRowsCount","_areCoordinatesEqual","coord1","coord2","_cell","isFocused","_cursorRenderers","_renderBarCursor","_renderBlockCursor","_renderUnderlineCursor","_clearCursor","_cursorBlinkStateManager","pause","resume","CursorBlinkStateManager","_render","restartBlinkAnimation","isPaused","triggeredByAnimationFrame","cursorY","viewportRelativeCursorY","_renderBlurCursor","isCursorVisible","strokeStyle","_restartInterval","_blinkStartTimeout","_blinkInterval","clearInterval","_animationTimeRestarted","Date","now","timeToStart","time","setInterval","onLinkHover","_onLinkHover","onLinkLeave","_onLinkLeave","_clearCurrentLink","x1","y1","middleRowCount","y2","x2","is256Color","_linkMatchers","_nextLinkMatcherId","_onLinkTooltip","_rowsToLinkify","mouseZoneManager","_element","_rowsTimeoutId","_linkifyRows","_timeBeforeLatency","absoluteRowIndexStart","absoluteRowIndexEnd","overscanLineLimit","iterator","hasNext","_doLinkifyRow","first","matcher","matchIndex","validationCallback","hoverTooltipCallback","tooltipCallback","hoverLeaveCallback","leaveCallback","willLinkActivate","priority","_addLinkMatcherToList","rowIndex","match","rex","RegExp","source","flags","stringIndex","uri","lastIndex","bufferIndex","stringIndexToBufferIndex","isValid","_addLink","exec","getStringCellWidth","MouseZone","_createLinkHoverEvent","clickCallback","hoverCallback","NON_BREAKING_SPACE_CHAR","ALL_NON_BREAKING_SPACE_REGEX","_screenElement","_dragScrollAmount","_enabled","_mouseDownTimeStamp","_onLinuxMouseSelection","_onRedrawRequest","_mouseMoveListener","_onMouseMove","_mouseUpListener","_onMouseUp","onUserInput","_trimListener","onTrim","_onTrim","onBufferActivate","_onBufferActivate","_model","SelectionModel","_activeSelectionMode","_removeMouseDownListeners","finalSelectionStart","finalSelectionEnd","lineText","translateBufferLineToString","bufferLine","isLinuxMouseSelection","_getMouseBufferCoords","_areCoordsInSelection","_selectWordAt","isSelectAllActive","getCoords","_getMouseEventScrollAmount","terminalHeight","macOptionClickForcesSelection","timeStamp","_onIncrementalClick","detail","_onSingleClick","_onDoubleClick","_onTripleClick","_addMouseDownListeners","_dragScrollIntervalTimer","_dragScroll","selectionStartLength","_selectLineAt","stopImmediatePropagation","previousSelectionEnd","_selectToWordAt","timeElapsed","coordinates","moveToCellSequence","activeBuffer","_convertViewportColToCharacterIndex","charIndex","_getWordAt","allowWhitespaceOnlySelection","followWrappedLinesAbove","followWrappedLinesBelow","charOffset","leftWideCharCount","rightWideCharCount","leftLongCharOffset","rightLongCharOffset","charAt","_isCharWordSeparator","trim","previousBufferLine","previousLineWordPosition","nextBufferLine","nextLineWordPosition","wordPosition","areSelectionValuesReversed","wordSeparator","wrappedRange","getWrappedRangeForLine","last","startPlusLength","moveToRequestedRow","targetY","applicationCursor","wrappedRowsForRow","repeat","wrappedRows","direction","verticalDirection","wrappedRowsCount","currentRow","lineWraps","horizontalDirection","targetX","forward","currentCol","bufferStr","mod","str","rpt","moveHorizontallyOnly","resetStartingRow","moveToRequestedCol","_audioContext","audioContextCtor","AudioContext","webkitAudioContext","audioContext","bellAudioSource","createBufferSource","decodeAudioData","_base64ToArrayBuffer","_removeMimeType","bellSound","connect","destination","base64","binaryString","atob","bytes","dataURI","split","_zones","_areZonesActive","_lastHoverCoords","_initialSelectionLength","_onMouseDown","_mouseLeaveListener","_onMouseLeave","_clickListener","_onClick","_deactivate","zone","_activate","_currentZone","pageX","_onHover","_findZoneEventAt","_tooltipTimeout","_onTooltip","_getSelectionLength","currentSelectionLength","_liveRegionLineCount","_charsToConsume","_charsToAnnounce","_accessibilityTreeRoot","_rowContainer","_rowElements","_createAccessibilityTreeNode","_topBoundaryFocusListener","_onBoundaryFocus","_bottomBoundaryFocusListener","_refreshRowsDimensions","_renderRowsDebouncer","_renderRows","_refreshRows","_liveRegion","insertAdjacentElement","onA11yChar","char","_onChar","onA11yTab","spaceCount","_onTab","_clearLiveRegion","_screenDprMonitor","boundaryElement","beforeBoundaryElement","getAttribute","relatedTarget","topBoundaryElement","bottomBoundaryElement","newElement","unshift","children","_refreshRowDimensions","MAX_ROWS_TO_READ","keyChar","setSize","posInSet","innerHTML","_announceCharacters","TERMINAL_CLASS_PREFIX","ROW_CONTAINER_CLASS","SELECTION_CLASS","nextTerminalId","_terminalClass","_refreshRowElements","_selectionContainer","_injectCss","_rowFactory","DomRendererRowFactory","_themeStyleElement","_dimensionsStyleElement","overflow","styles","_terminalSelector","BOLD_CLASS","ITALIC_CLASS","CURSOR_CLASS","CURSOR_STYLE_BLOCK_CLASS","CURSOR_BLINK_CLASS","CURSOR_STYLE_BAR_CLASS","CURSOR_STYLE_UNDERLINE_CLASS","documentFragment","_createSelectionElement","colStart","colEnd","terminal","cursorAbsoluteY","cursorX","rowElement","createRow","_setCellUnderline","enabled","span","textDecoration","DIM_CLASS","UNDERLINE_CLASS","isCursorRow","cellWidth","lineLength","charElement","swapColor","KEYCODE_KEY_MAPPINGS","48","49","50","51","52","53","54","55","56","57","186","187","188","189","190","191","192","219","220","221","222","applicationCursorMode","modifiers","keyMapping","lastChar","_renderer","charSizeService","_isPaused","_needsFullRefresh","_canvasWidth","_canvasHeight","_onDimensionsChange","_onRefreshRequest","_renderDebouncer","onCharSizeChange","IntersectionObserver","_onIntersectionChange","threshold","observe","disconnect","intersectionRatio","_fireOnCanvasResize","changeOptions","_fullRefresh","DEFAULT_BELL_SOUND","DEFAULT_OPTIONS","scrollback","disableStdin","tabStopWidth","screenKeys","useFlowControl","CONSTRUCTOR_ONLY_OPTIONS","_onOptionChange","newValue","_sanitizeAndValidateOption","parentElement","_onCharSizeChange","_measureStrategy","DomMeasureStrategy","_parentElement","_result","_measureElement","geometry","BufferSet","_normal","Buffer","fillViewportRows","_alt","_activeBuffer","inactiveBuffer","fillAttr","newCols","newRows","MAX_BUFFER_SIZE","_hasScrollback","_nullCell","_whitespaceCell","_cols","_rows","CircularList","_getCorrectBufferLength","getWhitespaceCell","relativeY","correctBufferLength","nullCell","newMaxLength","addToY","amountToTrim","_isReflowEnabled","_reflow","_reflowLarger","_reflowSmaller","toRemove","reflowLargerGetLinesToRemove","newLayoutResult","reflowLargerCreateNewLayout","reflowLargerApplyNewLayout","layout","_reflowLargerAdjustViewport","countRemoved","viewportAdjustments","toInsert","countToInsert","wrappedLines","absoluteY","lastLineLength","destLineLengths","reflowSmallerGetNewLineLengths","linesToAdd","trimmedLines","newLines","destLineIndex","srcLineIndex","cellsToCopy","wrappedLinesIndex","getWrappedLineTrimmedLength","insertEvents","originalLines","originalLinesLength","originalLineIndex","nextToInsertIndex","nextToInsert","countInsertedSoFar","nextI","insertCountEmitted","onInsertEmitter","onTrimEmitter","lineIndex","marker","Marker","onInsert","onDelete","onDispose","_removeMarker","startOverscan","endOverscan","BufferStringIterator","_trimRight","_startIndex","_endIndex","_startOverscan","_endOverscan","_current","_maxLength","onDeleteEmitter","_array","_length","newArray","_getCyclicIndex","newLength","deleteCount","items","countToTrim","expandListBy","endsInNull","followingLineStartsWithWide","oldCols","bufferAbsoluteY","srcTrimmedTineLength","srcRemainingCells","destRemainingCells","countToRemove","nextToRemoveIndex","nextToRemoveStart","countRemovedSoFar","newLayout","newLayoutLines","newLineLengths","cellsNeeded","reduce","srcLine","cellsAvailable","oldTrimmedLength","endsWithWide","_nextId","isDisposed","_onDispose","DEFAULT_DEC_PRIVATE_MODES","_scrollToBottom","_onUserInput","wasUserInput","LogLevel","optionsKeyToLogLevel","DEBUG","info","INFO","WARN","ERROR","off","OFF","_updateLogLevel","_logLevel","_evalLazyOptionalParams","optionalParams","_log","message","log","clearRange","temp","_entries","entries","service","instance","ServiceCollection","_services","serviceDependencies","getServiceDependencies","sort","serviceArgs","dependency","firstServiceArgPos","args","DEFAULT_PROTOCOLS","NONE","restrict","X10","VT200","DRAG","ANY","eventCode","isSGR","S","DEFAULT_ENCODINGS","DEFAULT","SGR","_protocols","_encodings","_activeProtocol","_activeEncoding","_onProtocolChange","_lastEvent","addProtocol","addEncoding","protocol","encoding","_compareEvents","report","DOWN","UP","MOVE","WHEEL","e1","e2","_action","_callbacks","_pendingData","_bufferOffset","cb","_innerWrite","startTime","_addons","loadedAddon","_wrappedAddonDispose","activate"],"mappings":"CAAA,SAA2CA,EAAMC,GAChD,GAAsB,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,Q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,WACQiD,EAA4B,CAChCjD,SAAQ,EACRhwD,QAASgwD,EAAShwD,QAClBquD,YAAY,GAEdzuD,KAAKozD,QAAQjzD,KAAKkzD,GAClBjD,EAAShwD,QAAU,WAAM,SAAKkzD,qBAAqBD,IACnDjD,EAASmD,SAAc9Q,IAGjB,YAAA6Q,qBAAR,SAA6BD,GAC3B,IAAIA,EAAY5E,WAAhB,CAKA,IADA,IAAIxtD,GAAS,EACJ9D,EAAI,EAAGA,EAAI6C,KAAKozD,QAAQ/yD,OAAQlD,IACvC,GAAI6C,KAAKozD,QAAQj2D,KAAOk2D,EAAa,CACnCpyD,EAAQ9D,EACR,MAGJ,IAAe,IAAX8D,EACF,MAAM,IAAI2S,MAAM,uDAElBy/C,EAAY5E,YAAa,EACzB4E,EAAYjzD,QAAQomC,MAAM6sB,EAAYjD,UACtCpwD,KAAKozD,QAAQ9yD,OAAOW,EAAO,KAE/B,EA1CA,GAAa,EAAA2jB","file":"xterm.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 32);\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IEvent } from 'common/EventEmitter';\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IDecPrivateModes, ICoreMouseEvent, CoreMouseEncoding, ICoreMouseProtocol, CoreMouseEventType } from 'common/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\n\nexport const IBufferService = createDecorator<IBufferService>('BufferService');\nexport interface IBufferService {\n  serviceBrand: any;\n\n  readonly cols: number;\n  readonly rows: number;\n  readonly buffer: IBuffer;\n  readonly buffers: IBufferSet;\n\n  // TODO: Move resize event here\n\n  resize(cols: number, rows: number): void;\n  reset(): void;\n}\n\nexport const ICoreMouseService = createDecorator<ICoreMouseService>('CoreMouseService');\nexport interface ICoreMouseService {\n  activeProtocol: string;\n  activeEncoding: string;\n  addProtocol(name: string, protocol: ICoreMouseProtocol): void;\n  addEncoding(name: string, encoding: CoreMouseEncoding): void;\n  reset(): void;\n\n  /**\n   * Triggers a mouse event to be sent.\n   *\n   * Returns true if the event passed all protocol restrictions and a report\n   * was sent, otherwise false. The return value may be used to decide whether\n   * the default event action in the bowser component should be omitted.\n   *\n   * Note: The method will change values of the given event object\n   * to fullfill protocol and encoding restrictions.\n   */\n  triggerMouseEvent(event: ICoreMouseEvent): boolean;\n\n  /**\n   * Event to announce changes in mouse tracking.\n   */\n  onProtocolChange: IEvent<CoreMouseEventType>;\n\n  /**\n   * Human readable version of mouse events.\n   */\n  explainEvents(events: CoreMouseEventType): {[event: string]: boolean};\n}\n\nexport const ICoreService = createDecorator<ICoreService>('CoreService');\nexport interface ICoreService {\n  serviceBrand: any;\n\n  readonly decPrivateModes: IDecPrivateModes;\n\n  readonly onData: IEvent<string>;\n  readonly onUserInput: IEvent<void>;\n\n  reset(): void;\n\n  /**\n   * Triggers the onData event in the public API.\n   * @param data The data that is being emitted.\n   * @param wasFromUser Whether the data originated from the user (as opposed to\n   * resulting from parsing incoming data). When true this will also:\n   * - Scroll to the bottom of the buffer.s\n   * - Fire the `onUserInput` event (so selection can be cleared).\n    */\n  triggerDataEvent(data: string, wasUserInput?: boolean): void;\n}\n\nexport const IDirtyRowService = createDecorator<IDirtyRowService>('DirtyRowService');\nexport interface IDirtyRowService {\n  serviceBrand: any;\n\n  readonly start: number;\n  readonly end: number;\n\n  clearRange(): void;\n  markDirty(y: number): void;\n  markRangeDirty(y1: number, y2: number): void;\n  markAllDirty(): void;\n}\n\nexport interface IServiceIdentifier<T> {\n  (...args: any[]): void;\n  type: T;\n}\n\nexport interface IConstructorSignature0<T> {\n  new(...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature1<A1, T> {\n  new(first: A1, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature2<A1, A2, T> {\n  new(first: A1, second: A2, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature3<A1, A2, A3, T> {\n  new(first: A1, second: A2, third: A3, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature4<A1, A2, A3, A4, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {\n  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { serviceBrand: any; }[]): T;\n}\n\nexport const IInstantiationService = createDecorator<IInstantiationService>('InstantiationService');\nexport interface IInstantiationService {\n  setService<T>(id: IServiceIdentifier<T>, instance: T): void;\n\n  createInstance<T>(ctor: IConstructorSignature0<T>): T;\n  createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T;\n  createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T;\n  createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T;\n  createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T;\n  createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;\n  createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;\n  createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;\n  createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;\n}\n\nexport const ILogService = createDecorator<ILogService>('LogService');\nexport interface ILogService {\n  serviceBrand: any;\n\n  debug(message: any, ...optionalParams: any[]): void;\n  info(message: any, ...optionalParams: any[]): void;\n  warn(message: any, ...optionalParams: any[]): void;\n  error(message: any, ...optionalParams: any[]): void;\n}\n\nexport const IOptionsService = createDecorator<IOptionsService>('OptionsService');\nexport interface IOptionsService {\n  serviceBrand: any;\n\n  readonly options: ITerminalOptions;\n\n  readonly onOptionChange: IEvent<string>;\n\n  setOption<T>(key: string, value: T): void;\n  getOption<T>(key: string): T | undefined;\n}\n\nexport type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';\nexport type RendererType = 'dom' | 'canvas';\n\nexport interface IPartialTerminalOptions {\n  allowTransparency?: boolean;\n  bellSound?: string;\n  bellStyle?: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;\n  cols?: number;\n  cursorBlink?: boolean;\n  cursorStyle?: 'block' | 'underline' | 'bar';\n  disableStdin?: boolean;\n  drawBoldTextInBrightColors?: boolean;\n  fastScrollModifier?: 'alt' | 'ctrl' | 'shift';\n  fastScrollSensitivity?: number;\n  fontSize?: number;\n  fontFamily?: string;\n  fontWeight?: FontWeight;\n  fontWeightBold?: FontWeight;\n  letterSpacing?: number;\n  lineHeight?: number;\n  logLevel?: LogLevel;\n  macOptionIsMeta?: boolean;\n  macOptionClickForcesSelection?: boolean;\n  rendererType?: RendererType;\n  rightClickSelectsWord?: boolean;\n  rows?: number;\n  screenReaderMode?: boolean;\n  scrollback?: number;\n  scrollSensitivity?: number;\n  tabStopWidth?: number;\n  theme?: ITheme;\n  windowsMode?: boolean;\n  wordSeparator?: string;\n}\n\nexport interface ITerminalOptions {\n  allowTransparency: boolean;\n  bellSound: string;\n  bellStyle: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;\n  cols: number;\n  cursorBlink: boolean;\n  cursorStyle: 'block' | 'underline' | 'bar';\n  disableStdin: boolean;\n  drawBoldTextInBrightColors: boolean;\n  fastScrollModifier: 'alt' | 'ctrl' | 'shift' | undefined;\n  fastScrollSensitivity: number;\n  fontSize: number;\n  fontFamily: string;\n  fontWeight: FontWeight;\n  fontWeightBold: FontWeight;\n  letterSpacing: number;\n  lineHeight: number;\n  logLevel: LogLevel;\n  macOptionIsMeta: boolean;\n  macOptionClickForcesSelection: boolean;\n  rendererType: RendererType;\n  rightClickSelectsWord: boolean;\n  rows: number;\n  screenReaderMode: boolean;\n  scrollback: number;\n  scrollSensitivity: number;\n  tabStopWidth: number;\n  theme: ITheme;\n  windowsMode: boolean;\n  wordSeparator: string;\n\n  [key: string]: any;\n  cancelEvents: boolean;\n  convertEol: boolean;\n  screenKeys: boolean;\n  termName: string;\n  useFlowControl: boolean;\n}\n\nexport interface ITheme {\n  foreground?: string;\n  background?: string;\n  cursor?: string;\n  cursorAccent?: string;\n  selection?: string;\n  black?: string;\n  red?: string;\n  green?: string;\n  yellow?: string;\n  blue?: string;\n  magenta?: string;\n  cyan?: string;\n  white?: string;\n  brightBlack?: string;\n  brightRed?: string;\n  brightGreen?: string;\n  brightYellow?: string;\n  brightBlue?: string;\n  brightMagenta?: string;\n  brightCyan?: string;\n  brightWhite?: string;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\ninterface IListener<T> {\n  (e: T): void;\n}\n\nexport interface IEvent<T> {\n  (listener: (e: T) => any): IDisposable;\n}\n\nexport interface IEventEmitter<T> {\n  event: IEvent<T>;\n  fire(data: T): void;\n}\n\nexport class EventEmitter<T> implements IEventEmitter<T> {\n  private _listeners: IListener<T>[] = [];\n  private _event?: IEvent<T>;\n\n  public get event(): IEvent<T> {\n    if (!this._event) {\n      this._event = (listener: (e: T) => any) => {\n        this._listeners.push(listener);\n        const disposable = {\n          dispose: () => {\n            for (let i = 0; i < this._listeners.length; i++) {\n              if (this._listeners[i] === listener) {\n                this._listeners.splice(i, 1);\n                return;\n              }\n            }\n          }\n        };\n        return disposable;\n      };\n    }\n    return this._event;\n  }\n\n  public fire(data: T): void {\n    const queue: IListener<T>[] = [];\n    for (let i = 0; i < this._listeners.length; i++) {\n      queue.push(this._listeners[i]);\n    }\n    for (let i = 0; i < queue.length; i++) {\n      queue[i].call(undefined, data);\n    }\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\n/**\n * A base class that can be extended to provide convenience methods for managing the lifecycle of an\n * object and its components.\n */\nexport abstract class Disposable implements IDisposable {\n  protected _disposables: IDisposable[] = [];\n  protected _isDisposed: boolean = false;\n\n  constructor() {\n  }\n\n  /**\n   * Disposes the object, triggering the `dispose` method on all registered IDisposables.\n   */\n  public dispose(): void {\n    this._isDisposed = true;\n    this._disposables.forEach(d => d.dispose());\n    this._disposables.length = 0;\n  }\n\n  /**\n   * Registers a disposable object.\n   * @param d The disposable to register.\n   */\n  public register<T extends IDisposable>(d: T): void {\n    this._disposables.push(d);\n  }\n\n  /**\n   * Unregisters a disposable object if it has been registered, if not do\n   * nothing.\n   * @param d The disposable to unregister.\n   */\n  public unregister<T extends IDisposable>(d: T): void {\n    const index = this._disposables.indexOf(d);\n    if (index !== -1) {\n      this._disposables.splice(index, 1);\n    }\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const DEFAULT_COLOR = 256;\nexport const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0);\n\nexport const CHAR_DATA_ATTR_INDEX = 0;\nexport const CHAR_DATA_CHAR_INDEX = 1;\nexport const CHAR_DATA_WIDTH_INDEX = 2;\nexport const CHAR_DATA_CODE_INDEX = 3;\n\n/**\n * Null cell - a real empty cell (containing nothing).\n * Note that code should always be 0 for a null cell as\n * several test condition of the buffer line rely on this.\n */\nexport const NULL_CELL_CHAR = '';\nexport const NULL_CELL_WIDTH = 1;\nexport const NULL_CELL_CODE = 0;\n\n/**\n * Whitespace cell.\n * This is meant as a replacement for empty cells when needed\n * during rendering lines to preserve correct aligment.\n */\nexport const WHITESPACE_CELL_CHAR = ' ';\nexport const WHITESPACE_CELL_WIDTH = 1;\nexport const WHITESPACE_CELL_CODE = 32;\n\n/**\n * Bitmasks for accessing data in `content`.\n */\nexport const enum Content {\n  /**\n   * bit 1..21    codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken)\n   *              read:   `codepoint = content & Content.codepointMask;`\n   *              write:  `content |= codepoint & Content.codepointMask;`\n   *                      shortcut if precondition `codepoint <= 0x10FFFF` is met:\n   *                      `content |= codepoint;`\n   */\n  CODEPOINT_MASK = 0x1FFFFF,\n\n  /**\n   * bit 22       flag indication whether a cell contains combined content\n   *              read:   `isCombined = content & Content.isCombined;`\n   *              set:    `content |= Content.isCombined;`\n   *              clear:  `content &= ~Content.isCombined;`\n   */\n  IS_COMBINED_MASK = 0x200000,  // 1 << 21\n\n  /**\n   * bit 1..22    mask to check whether a cell contains any string data\n   *              we need to check for codepoint and isCombined bits to see\n   *              whether a cell contains anything\n   *              read:   `isEmpty = !(content & Content.hasContent)`\n   */\n  HAS_CONTENT_MASK = 0x3FFFFF,\n\n  /**\n   * bit 23..24   wcwidth value of cell, takes 2 bits (ranges from 0..2)\n   *              read:   `width = (content & Content.widthMask) >> Content.widthShift;`\n   *                      `hasWidth = content & Content.widthMask;`\n   *                      as long as wcwidth is highest value in `content`:\n   *                      `width = content >> Content.widthShift;`\n   *              write:  `content |= (width << Content.widthShift) & Content.widthMask;`\n   *                      shortcut if precondition `0 <= width <= 3` is met:\n   *                      `content |= width << Content.widthShift;`\n   */\n  WIDTH_MASK = 0xC00000,   // 3 << 22\n  WIDTH_SHIFT = 22\n}\n\nexport const enum Attributes {\n  /**\n   * bit 1..8     blue in RGB, color in P256 and P16\n   */\n  BLUE_MASK = 0xFF,\n  BLUE_SHIFT = 0,\n  PCOLOR_MASK = 0xFF,\n  PCOLOR_SHIFT = 0,\n\n  /**\n   * bit 9..16    green in RGB\n   */\n  GREEN_MASK = 0xFF00,\n  GREEN_SHIFT = 8,\n\n  /**\n   * bit 17..24   red in RGB\n   */\n  RED_MASK = 0xFF0000,\n  RED_SHIFT = 16,\n\n  /**\n   * bit 25..26   color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)\n   */\n  CM_MASK = 0x3000000,\n  CM_DEFAULT = 0,\n  CM_P16 = 0x1000000,\n  CM_P256 = 0x2000000,\n  CM_RGB = 0x3000000,\n\n  /**\n   * bit 1..24  RGB room\n   */\n  RGB_MASK = 0xFFFFFF\n}\n\nexport const enum FgFlags {\n  /**\n   * bit 27..31 (32th bit unused)\n   */\n  INVERSE = 0x4000000,\n  BOLD = 0x8000000,\n  UNDERLINE = 0x10000000,\n  BLINK = 0x20000000,\n  INVISIBLE = 0x40000000\n}\n\nexport const enum BgFlags {\n  /**\n   * bit 27..32 (upper 4 unused)\n   */\n  ITALIC = 0x4000000,\n  DIM = 0x8000000\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, ICellData } from 'common/Types';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\nimport { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants';\nimport { AttributeData } from 'common/buffer/AttributeData';\n\n/**\n * CellData - represents a single Cell in the terminal buffer.\n */\nexport class CellData extends AttributeData implements ICellData {\n  /** Helper to create CellData from CharData. */\n  public static fromCharData(value: CharData): CellData {\n    const obj = new CellData();\n    obj.setFromCharData(value);\n    return obj;\n  }\n  /** Primitives from terminal buffer. */\n  public content: number = 0;\n  public fg: number = 0;\n  public bg: number = 0;\n  public combinedData: string = '';\n  /** Whether cell contains a combined string. */\n  public isCombined(): number {\n    return this.content & Content.IS_COMBINED_MASK;\n  }\n  /** Width of the cell. */\n  public getWidth(): number {\n    return this.content >> Content.WIDTH_SHIFT;\n  }\n  /** JS string of the content. */\n  public getChars(): string {\n    if (this.content & Content.IS_COMBINED_MASK) {\n      return this.combinedData;\n    }\n    if (this.content & Content.CODEPOINT_MASK) {\n      return stringFromCodePoint(this.content & Content.CODEPOINT_MASK);\n    }\n    return '';\n  }\n  /**\n   * Codepoint of cell\n   * Note this returns the UTF32 codepoint of single chars,\n   * if content is a combined string it returns the codepoint\n   * of the last char in string to be in line with code in CharData.\n   * */\n  public getCode(): number {\n    return (this.isCombined())\n      ? this.combinedData.charCodeAt(this.combinedData.length - 1)\n      : this.content & Content.CODEPOINT_MASK;\n  }\n  /** Set data from CharData */\n  public setFromCharData(value: CharData): void {\n    this.fg = value[CHAR_DATA_ATTR_INDEX];\n    this.bg = 0;\n    let combined = false;\n    // surrogates and combined strings need special treatment\n    if (value[CHAR_DATA_CHAR_INDEX].length > 2) {\n      combined = true;\n    }\n    else if (value[CHAR_DATA_CHAR_INDEX].length === 2) {\n      const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0);\n      // if the 2-char string is a surrogate create single codepoint\n      // everything else is combined\n      if (0xD800 <= code && code <= 0xDBFF) {\n        const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1);\n        if (0xDC00 <= second && second <= 0xDFFF) {\n          this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n        }\n        else {\n          combined = true;\n        }\n      }\n      else {\n        combined = true;\n      }\n    }\n    else {\n      this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    }\n    if (combined) {\n      this.combinedData = value[CHAR_DATA_CHAR_INDEX];\n      this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    }\n  }\n  /** Get data as CharData. */\n  public getAsCharData(): CharData {\n    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IEvent } from 'common/EventEmitter';\nimport { IRenderDimensions, IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { IColorSet } from 'browser/Types';\nimport { ISelectionRedrawRequestEvent } from 'browser/selection/Types';\nimport { createDecorator } from 'common/services/ServiceRegistry';\nimport { IDisposable } from 'common/Types';\n\nexport const ICharSizeService = createDecorator<ICharSizeService>('CharSizeService');\nexport interface ICharSizeService {\n  serviceBrand: any;\n\n  readonly width: number;\n  readonly height: number;\n  readonly hasValidSize: boolean;\n\n  readonly onCharSizeChange: IEvent<void>;\n\n  measure(): void;\n}\n\nexport const IMouseService = createDecorator<IMouseService>('MouseService');\nexport interface IMouseService {\n  serviceBrand: any;\n\n  getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined;\n  getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined;\n}\n\nexport const IRenderService = createDecorator<IRenderService>('RenderService');\nexport interface IRenderService extends IDisposable {\n  serviceBrand: any;\n\n  onDimensionsChange: IEvent<IRenderDimensions>;\n  onRender: IEvent<{ start: number, end: number }>;\n  onRefreshRequest: IEvent<{ start: number, end: number }>;\n\n  dimensions: IRenderDimensions;\n\n  refreshRows(start: number, end: number): void;\n  resize(cols: number, rows: number): void;\n  changeOptions(): void;\n  setRenderer(renderer: IRenderer): void;\n  setColors(colors: IColorSet): void;\n  onDevicePixelRatioChange(): void;\n  onResize(cols: number, rows: number): void;\n  // TODO: Is this useful when we have onResize?\n  onCharSizeChanged(): void;\n  onBlur(): void;\n  onFocus(): void;\n  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;\n  onCursorMove(): void;\n  clear(): void;\n  registerCharacterJoiner(handler: CharacterJoinerHandler): number;\n  deregisterCharacterJoiner(joinerId: number): boolean;\n}\n\nexport const ISelectionService = createDecorator<ISelectionService>('SelectionService');\nexport interface ISelectionService {\n  serviceBrand: any;\n\n  readonly selectionText: string;\n  readonly hasSelection: boolean;\n  readonly selectionStart: [number, number] | undefined;\n  readonly selectionEnd: [number, number] | undefined;\n\n  readonly onLinuxMouseSelection: IEvent<string>;\n  readonly onRedrawRequest: IEvent<ISelectionRedrawRequestEvent>;\n  readonly onSelectionChange: IEvent<void>;\n\n  disable(): void;\n  enable(): void;\n  reset(): void;\n  setSelection(row: number, col: number, length: number): void;\n  selectAll(): void;\n  selectLines(start: number, end: number): void;\n  clearSelection(): void;\n  isClickInSelection(event: MouseEvent): boolean;\n  selectWordAtCursor(event: MouseEvent): void;\n  shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean;\n  shouldForceSelection(event: MouseEvent): boolean;\n  refresh(isLinuxMouseSelection?: boolean): void;\n  onMouseDown(event: MouseEvent): void;\n}\n\nexport const ISoundService = createDecorator<ISoundService>('SoundService');\nexport interface ISoundService {\n  serviceBrand: any;\n\n  playBellSound(): void;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAttributeData, IColorRGB } from 'common/Types';\nimport { Attributes, FgFlags, BgFlags } from 'common/buffer/Constants';\n\nexport class AttributeData implements IAttributeData {\n  static toColorRGB(value: number): IColorRGB {\n    return [\n      value >>> Attributes.RED_SHIFT & 255,\n      value >>> Attributes.GREEN_SHIFT & 255,\n      value & 255\n    ];\n  }\n  static fromColorRGB(value: IColorRGB): number {\n    return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255;\n  }\n\n  public clone(): IAttributeData {\n    const newObj = new AttributeData();\n    newObj.fg = this.fg;\n    newObj.bg = this.bg;\n    return newObj;\n  }\n\n  // data\n  public fg: number = 0;\n  public bg: number = 0;\n\n  // flags\n  public isInverse(): number   { return this.fg & FgFlags.INVERSE; }\n  public isBold(): number      { return this.fg & FgFlags.BOLD; }\n  public isUnderline(): number { return this.fg & FgFlags.UNDERLINE; }\n  public isBlink(): number     { return this.fg & FgFlags.BLINK; }\n  public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; }\n  public isItalic(): number    { return this.bg & BgFlags.ITALIC; }\n  public isDim(): number       { return this.bg & BgFlags.DIM; }\n\n  // color modes\n  public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; }\n  public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; }\n  public isFgRGB(): boolean       { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n  public isBgRGB(): boolean       { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; }\n  public isFgPalette(): boolean   { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; }\n  public isBgPalette(): boolean   { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; }\n  public isFgDefault(): boolean   { return (this.fg & Attributes.CM_MASK) === 0; }\n  public isBgDefault(): boolean   { return (this.bg & Attributes.CM_MASK) === 0; }\n\n  // colors\n  public getFgColor(): number {\n    switch (this.fg & Attributes.CM_MASK) {\n      case Attributes.CM_P16:\n      case Attributes.CM_P256:  return this.fg & Attributes.PCOLOR_MASK;\n      case Attributes.CM_RGB:   return this.fg & Attributes.RGB_MASK;\n      default:                  return -1;  // CM_DEFAULT defaults to -1\n    }\n  }\n  public getBgColor(): number {\n    switch (this.bg & Attributes.CM_MASK) {\n      case Attributes.CM_P16:\n      case Attributes.CM_P256:  return this.bg & Attributes.PCOLOR_MASK;\n      case Attributes.CM_RGB:   return this.bg & Attributes.RGB_MASK;\n      default:                  return -1;  // CM_DEFAULT defaults to -1\n    }\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\n/**\n * Adds a disposable listener to a node in the DOM, returning the disposable.\n * @param type The event type.\n * @param handler The handler for the listener.\n */\nexport function addDisposableDomListener(\n  node: Element | Window | Document,\n  type: string,\n  handler: (e: any) => void,\n  useCapture?: boolean\n): IDisposable {\n  node.addEventListener(type, handler, useCapture);\n  return {\n    dispose: () => {\n      if (!handler) {\n        // Already disposed\n        return;\n      }\n      node.removeEventListener(type, handler, useCapture);\n    }\n  };\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Polyfill - Convert UTF32 codepoint into JS string.\n * Note: The built-in String.fromCodePoint happens to be much slower\n *       due to additional sanity checks. We can avoid them since\n *       we always operate on legal UTF32 (granted by the input decoders)\n *       and use this faster version instead.\n */\nexport function stringFromCodePoint(codePoint: number): string {\n  if (codePoint > 0xFFFF) {\n    codePoint -= 0x10000;\n    return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00);\n  }\n  return String.fromCharCode(codePoint);\n}\n\n/**\n * Convert UTF32 char codes into JS string.\n * Basically the same as `stringFromCodePoint` but for multiple codepoints\n * in a loop (which is a lot faster).\n */\nexport function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string {\n  let result = '';\n  for (let i = start; i < end; ++i) {\n    let codepoint = data[i];\n    if (codepoint > 0xFFFF) {\n      // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate pair\n      // conversion rules:\n      //  - subtract 0x10000 from code point, leaving a 20 bit number\n      //  - add high 10 bits to 0xD800  --> first surrogate\n      //  - add low 10 bits to 0xDC00   --> second surrogate\n      codepoint -= 0x10000;\n      result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00);\n    } else {\n      result += String.fromCharCode(codepoint);\n    }\n  }\n  return result;\n}\n\n/**\n * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints.\n * To keep the decoder in line with JS strings it handles single surrogates as UCS2.\n */\nexport class StringToUtf32 {\n  private _interim: number = 0;\n\n  /**\n   * Clears interim and resets decoder to clean state.\n   */\n  public clear(): void {\n    this._interim = 0;\n  }\n\n  /**\n   * Decode JS string to UTF32 codepoints.\n   * The methods assumes stream input and will store partly transmitted\n   * surrogate pairs and decode them with the next data chunk.\n   * Note: The method does no bound checks for target, therefore make sure\n   * the provided input data does not exceed the size of `target`.\n   * Returns the number of written codepoints in `target`.\n   */\n  decode(input: string, target: Uint32Array): number {\n    const length = input.length;\n\n    if (!length) {\n      return 0;\n    }\n\n    let size = 0;\n    let startPos = 0;\n\n    // handle leftover surrogate high\n    if (this._interim) {\n      const second = input.charCodeAt(startPos++);\n      if (0xDC00 <= second && second <= 0xDFFF) {\n        target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n      } else {\n        // illegal codepoint (USC2 handling)\n        target[size++] = this._interim;\n        target[size++] = second;\n      }\n      this._interim = 0;\n    }\n\n    for (let i = startPos; i < length; ++i) {\n      const code = input.charCodeAt(i);\n      // surrogate pair first\n      if (0xD800 <= code && code <= 0xDBFF) {\n        if (++i >= length) {\n          this._interim = code;\n          return size;\n        }\n        const second = input.charCodeAt(i);\n        if (0xDC00 <= second && second <= 0xDFFF) {\n          target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n        } else {\n          // illegal codepoint (USC2 handling)\n          target[size++] = code;\n          target[size++] = second;\n        }\n        continue;\n      }\n      target[size++] = code;\n    }\n    return size;\n  }\n}\n\n/**\n * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints.\n */\nexport class Utf8ToUtf32 {\n  public interim: Uint8Array = new Uint8Array(3);\n\n  /**\n   * Clears interim bytes and resets decoder to clean state.\n   */\n  public clear(): void {\n    this.interim.fill(0);\n  }\n\n  /**\n   * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`.\n   * The methods assumes stream input and will store partly transmitted bytes\n   * and decode them with the next data chunk.\n   * Note: The method does no bound checks for target, therefore make sure\n   * the provided data chunk does not exceed the size of `target`.\n   * Returns the number of written codepoints in `target`.\n   */\n  decode(input: Uint8Array, target: Uint32Array): number {\n    const length = input.length;\n\n    if (!length) {\n      return 0;\n    }\n\n    let size = 0;\n    let byte1: number;\n    let byte2: number;\n    let byte3: number;\n    let byte4: number;\n    let codepoint = 0;\n    let startPos = 0;\n\n    // handle leftover bytes\n    if (this.interim[0]) {\n      let discardInterim = false;\n      let cp = this.interim[0];\n      cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);\n      let pos = 0;\n      let tmp: number;\n      while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {\n        cp <<= 6;\n        cp |= tmp;\n      }\n      // missing bytes - read ahead from input\n      const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;\n      const missing = type - pos;\n      while (startPos < missing) {\n        if (startPos >= length) {\n          return 0;\n        }\n        tmp = input[startPos++];\n        if ((tmp & 0xC0) !== 0x80) {\n          // wrong continuation, discard interim bytes completely\n          startPos--;\n          discardInterim = true;\n          break;\n        } else {\n          // need to save so we can continue short inputs in next call\n          this.interim[pos++] = tmp;\n          cp <<= 6;\n          cp |= tmp & 0x3F;\n        }\n      }\n      if (!discardInterim) {\n        // final test is type dependent\n        if (type === 2) {\n          if (cp < 0x80) {\n            // wrong starter byte\n            startPos--;\n          } else {\n            target[size++] = cp;\n          }\n        } else if (type === 3) {\n          if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF)) {\n            // illegal codepoint\n          } else {\n            target[size++] = cp;\n          }\n        } else {\n          if (cp < 0x010000 || cp > 0x10FFFF) {\n            // illegal codepoint\n          } else {\n            target[size++] = cp;\n          }\n        }\n      }\n      this.interim.fill(0);\n    }\n\n    // loop through input\n    const fourStop = length - 4;\n    let i = startPos;\n    while (i < length) {\n      /**\n       * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.\n       * This is a compromise between speed gain for ASCII\n       * and penalty for non ASCII:\n       * For best ASCII performance the char should be stored directly into target,\n       * but even a single attempt to write to target and compare afterwards\n       * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,\n       * which reduces ASCII performance by ~15%.\n       * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible\n       * compared to the gains.\n       * Note that this optimization only takes place for 4 consecutive ASCII chars,\n       * for any shorter it bails out. Worst case - all 4 bytes being read but\n       * thrown away due to the last being a non ASCII char (-10% performance).\n       */\n      while (i < fourStop\n        && !((byte1 = input[i]) & 0x80)\n        && !((byte2 = input[i + 1]) & 0x80)\n        && !((byte3 = input[i + 2]) & 0x80)\n        && !((byte4 = input[i + 3]) & 0x80))\n      {\n        target[size++] = byte1;\n        target[size++] = byte2;\n        target[size++] = byte3;\n        target[size++] = byte4;\n        i += 4;\n      }\n\n      // reread byte1\n      byte1 = input[i++];\n\n      // 1 byte\n      if (byte1 < 0x80) {\n        target[size++] = byte1;\n\n        // 2 bytes\n      } else if ((byte1 & 0xE0) === 0xC0) {\n        if (i >= length) {\n          this.interim[0] = byte1;\n          return size;\n        }\n        byte2 = input[i++];\n        if ((byte2 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);\n        if (codepoint < 0x80) {\n          // wrong starter byte\n          i--;\n          continue;\n        }\n        target[size++] = codepoint;\n\n        // 3 bytes\n      } else if ((byte1 & 0xF0) === 0xE0) {\n        if (i >= length) {\n          this.interim[0] = byte1;\n          return size;\n        }\n        byte2 = input[i++];\n        if ((byte2 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        if (i >= length) {\n          this.interim[0] = byte1;\n          this.interim[1] = byte2;\n          return size;\n        }\n        byte3 = input[i++];\n        if ((byte3 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);\n        if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {\n          // illegal codepoint, no i-- here\n          continue;\n        }\n        target[size++] = codepoint;\n\n        // 4 bytes\n      } else if ((byte1 & 0xF8) === 0xF0) {\n        if (i >= length) {\n          this.interim[0] = byte1;\n          return size;\n        }\n        byte2 = input[i++];\n        if ((byte2 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        if (i >= length) {\n          this.interim[0] = byte1;\n          this.interim[1] = byte2;\n          return size;\n        }\n        byte3 = input[i++];\n        if ((byte3 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        if (i >= length) {\n          this.interim[0] = byte1;\n          this.interim[1] = byte2;\n          this.interim[2] = byte3;\n          return size;\n        }\n        byte4 = input[i++];\n        if ((byte4 & 0xC0) !== 0x80) {\n          // wrong continuation\n          i--;\n          continue;\n        }\n        codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);\n        if (codepoint < 0x010000 || codepoint > 0x10FFFF) {\n          // illegal codepoint, no i-- here\n          continue;\n        }\n        target[size++] = codepoint;\n      } else {\n        // illegal byte, just skip\n      }\n    }\n    return size;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport const INVERTED_DEFAULT_COLOR = 257;\nexport const DIM_OPACITY = 0.5;\n\nexport const CHAR_ATLAS_CELL_SPACING = 1;\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ninterface INavigator {\n  userAgent: string;\n  language: string;\n  platform: string;\n}\n\n// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but\n// we want this module to live in common.\ndeclare const navigator: INavigator;\n\nconst isNode = (typeof navigator === 'undefined') ? true : false;\nconst userAgent = (isNode) ? 'node' : navigator.userAgent;\nconst platform = (isNode) ? 'node' : navigator.platform;\n\nexport const isFirefox = !!~userAgent.indexOf('Firefox');\nexport const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);\n\n// Find the users platform. We use this to interpret the meta key\n// and ISO third level shifts.\n// http://stackoverflow.com/q/19877924/577598\nexport const isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);\nexport const isIpad = platform === 'iPad';\nexport const isIphone = platform === 'iPhone';\nexport const isWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);\nexport const isLinux = platform.indexOf('Linux') >= 0;\n\n/**\n * Return if the given array contains the given element\n * @param arr The array to search for the given element.\n * @param el The element to look for into the array\n */\nfunction contains(arr: any[], el: any): boolean {\n  return arr.indexOf(el) >= 0;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * C0 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C0 {\n  /** Null (Caret = ^@, C = \\0) */\n  export const NUL = '\\x00';\n  /** Start of Heading (Caret = ^A) */\n  export const SOH = '\\x01';\n  /** Start of Text (Caret = ^B) */\n  export const STX = '\\x02';\n  /** End of Text (Caret = ^C) */\n  export const ETX = '\\x03';\n  /** End of Transmission (Caret = ^D) */\n  export const EOT = '\\x04';\n  /** Enquiry (Caret = ^E) */\n  export const ENQ = '\\x05';\n  /** Acknowledge (Caret = ^F) */\n  export const ACK = '\\x06';\n  /** Bell (Caret = ^G, C = \\a) */\n  export const BEL = '\\x07';\n  /** Backspace (Caret = ^H, C = \\b) */\n  export const BS  = '\\x08';\n  /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \\t) */\n  export const HT  = '\\x09';\n  /** Line Feed (Caret = ^J, C = \\n) */\n  export const LF  = '\\x0a';\n  /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \\v) */\n  export const VT  = '\\x0b';\n  /** Form Feed (Caret = ^L, C = \\f) */\n  export const FF  = '\\x0c';\n  /** Carriage Return (Caret = ^M, C = \\r) */\n  export const CR  = '\\x0d';\n  /** Shift Out (Caret = ^N) */\n  export const SO  = '\\x0e';\n  /** Shift In (Caret = ^O) */\n  export const SI  = '\\x0f';\n  /** Data Link Escape (Caret = ^P) */\n  export const DLE = '\\x10';\n  /** Device Control One (XON) (Caret = ^Q) */\n  export const DC1 = '\\x11';\n  /** Device Control Two (Caret = ^R) */\n  export const DC2 = '\\x12';\n  /** Device Control Three (XOFF) (Caret = ^S) */\n  export const DC3 = '\\x13';\n  /** Device Control Four (Caret = ^T) */\n  export const DC4 = '\\x14';\n  /** Negative Acknowledge (Caret = ^U) */\n  export const NAK = '\\x15';\n  /** Synchronous Idle (Caret = ^V) */\n  export const SYN = '\\x16';\n  /** End of Transmission Block (Caret = ^W) */\n  export const ETB = '\\x17';\n  /** Cancel (Caret = ^X) */\n  export const CAN = '\\x18';\n  /** End of Medium (Caret = ^Y) */\n  export const EM  = '\\x19';\n  /** Substitute (Caret = ^Z) */\n  export const SUB = '\\x1a';\n  /** Escape (Caret = ^[, C = \\e) */\n  export const ESC = '\\x1b';\n  /** File Separator (Caret = ^\\) */\n  export const FS  = '\\x1c';\n  /** Group Separator (Caret = ^]) */\n  export const GS  = '\\x1d';\n  /** Record Separator (Caret = ^^) */\n  export const RS  = '\\x1e';\n  /** Unit Separator (Caret = ^_) */\n  export const US  = '\\x1f';\n  /** Space */\n  export const SP  = '\\x20';\n  /** Delete (Caret = ^?) */\n  export const DEL = '\\x7f';\n}\n\n/**\n * C1 control codes\n * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes\n */\nexport namespace C1 {\n  /** padding character */\n  export const PAD = '\\x80';\n  /** High Octet Preset */\n  export const HOP = '\\x81';\n  /** Break Permitted Here */\n  export const BPH = '\\x82';\n  /** No Break Here */\n  export const NBH = '\\x83';\n  /** Index */\n  export const IND = '\\x84';\n  /** Next Line */\n  export const NEL = '\\x85';\n  /** Start of Selected Area */\n  export const SSA = '\\x86';\n  /** End of Selected Area */\n  export const ESA = '\\x87';\n  /** Horizontal Tabulation Set */\n  export const HTS = '\\x88';\n  /** Horizontal Tabulation With Justification */\n  export const HTJ = '\\x89';\n  /** Vertical Tabulation Set */\n  export const VTS = '\\x8a';\n  /** Partial Line Down */\n  export const PLD = '\\x8b';\n  /** Partial Line Up */\n  export const PLU = '\\x8c';\n  /** Reverse Index */\n  export const RI = '\\x8d';\n  /** Single-Shift 2 */\n  export const SS2 = '\\x8e';\n  /** Single-Shift 3 */\n  export const SS3 = '\\x8f';\n  /** Device Control String */\n  export const DCS = '\\x90';\n  /** Private Use 1 */\n  export const PU1 = '\\x91';\n  /** Private Use 2 */\n  export const PU2 = '\\x92';\n  /** Set Transmit State */\n  export const STS = '\\x93';\n  /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */\n  export const CCH = '\\x94';\n  /** Message Waiting */\n  export const MW = '\\x95';\n  /** Start of Protected Area */\n  export const SPA = '\\x96';\n  /** End of Protected Area */\n  export const EPA = '\\x97';\n  /** Start of String */\n  export const SOS = '\\x98';\n  /** Single Graphic Character Introducer */\n  export const SGCI = '\\x99';\n  /** Single Character Introducer */\n  export const SCI = '\\x9a';\n  /** Control Sequence Introducer */\n  export const CSI = '\\x9b';\n  /** String Terminator */\n  export const ST = '\\x9c';\n  /** Operating System Command */\n  export const OSC = '\\x9d';\n  /** Privacy Message */\n  export const PM = '\\x9e';\n  /** Application Program Command */\n  export const APC = '\\x9f';\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions, IRenderLayer } from 'browser/renderer/Types';\nimport { ICellData } from 'common/Types';\nimport { DEFAULT_COLOR, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';\nimport { IGlyphIdentifier } from 'browser/renderer/atlas/Types';\nimport { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';\nimport { acquireCharAtlas } from 'browser/renderer/atlas/CharAtlasCache';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { IColorSet } from 'browser/Types';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { throwIfFalsy } from 'browser/renderer/RendererUtils';\n\nexport abstract class BaseRenderLayer implements IRenderLayer {\n  private _canvas: HTMLCanvasElement;\n  protected _ctx!: CanvasRenderingContext2D;\n  private _scaledCharWidth: number = 0;\n  private _scaledCharHeight: number = 0;\n  private _scaledCellWidth: number = 0;\n  private _scaledCellHeight: number = 0;\n  private _scaledCharLeft: number = 0;\n  private _scaledCharTop: number = 0;\n\n  protected _charAtlas: BaseCharAtlas | undefined;\n\n  /**\n   * An object that's reused when drawing glyphs in order to reduce GC.\n   */\n  private _currentGlyphIdentifier: IGlyphIdentifier = {\n    chars: '',\n    code: 0,\n    bg: 0,\n    fg: 0,\n    bold: false,\n    dim: false,\n    italic: false\n  };\n\n  constructor(\n    private _container: HTMLElement,\n    id: string,\n    zIndex: number,\n    private _alpha: boolean,\n    protected _colors: IColorSet,\n    private _rendererId: number,\n    protected readonly _bufferService: IBufferService,\n    protected readonly _optionsService: IOptionsService\n  ) {\n    this._canvas = document.createElement('canvas');\n    this._canvas.classList.add(`xterm-${id}-layer`);\n    this._canvas.style.zIndex = zIndex.toString();\n    this._initCanvas();\n    this._container.appendChild(this._canvas);\n  }\n\n  public dispose(): void {\n    this._container.removeChild(this._canvas);\n    if (this._charAtlas) {\n      this._charAtlas.dispose();\n    }\n  }\n\n  private _initCanvas(): void {\n    this._ctx = throwIfFalsy(this._canvas.getContext('2d', {alpha: this._alpha}));\n    // Draw the background if this is an opaque layer\n    if (!this._alpha) {\n      this._clearAll();\n    }\n  }\n\n  public onOptionsChanged(): void {}\n  public onBlur(): void {}\n  public onFocus(): void {}\n  public onCursorMove(): void {}\n  public onGridChanged(startRow: number, endRow: number): void {}\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {}\n\n  public setColors(colorSet: IColorSet): void {\n    this._refreshCharAtlas(colorSet);\n  }\n\n  protected _setTransparency(alpha: boolean): void {\n    // Do nothing when alpha doesn't change\n    if (alpha === this._alpha) {\n      return;\n    }\n\n    // Create new canvas and replace old one\n    const oldCanvas = this._canvas;\n    this._alpha = alpha;\n    // Cloning preserves properties\n    this._canvas = <HTMLCanvasElement>this._canvas.cloneNode();\n    this._initCanvas();\n    this._container.replaceChild(this._canvas, oldCanvas);\n\n    // Regenerate char atlas and force a full redraw\n    this._refreshCharAtlas(this._colors);\n    this.onGridChanged(0, this._bufferService.rows - 1);\n  }\n\n  /**\n   * Refreshes the char atlas, aquiring a new one if necessary.\n   * @param colorSet The color set to use for the char atlas.\n   */\n  private _refreshCharAtlas(colorSet: IColorSet): void {\n    if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) {\n      return;\n    }\n    this._charAtlas = acquireCharAtlas(this._optionsService.options, this._rendererId, colorSet, this._scaledCharWidth, this._scaledCharHeight);\n    this._charAtlas.warmUp();\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    this._scaledCellWidth = dim.scaledCellWidth;\n    this._scaledCellHeight = dim.scaledCellHeight;\n    this._scaledCharWidth = dim.scaledCharWidth;\n    this._scaledCharHeight = dim.scaledCharHeight;\n    this._scaledCharLeft = dim.scaledCharLeft;\n    this._scaledCharTop = dim.scaledCharTop;\n    this._canvas.width = dim.scaledCanvasWidth;\n    this._canvas.height = dim.scaledCanvasHeight;\n    this._canvas.style.width = `${dim.canvasWidth}px`;\n    this._canvas.style.height = `${dim.canvasHeight}px`;\n\n    // Draw the background if this is an opaque layer\n    if (!this._alpha) {\n      this._clearAll();\n    }\n\n    this._refreshCharAtlas(this._colors);\n  }\n\n  public abstract reset(): void;\n\n  /**\n   * Fills 1+ cells completely. This uses the existing fillStyle on the context.\n   * @param x The column to start at.\n   * @param y The row to start at\n   * @param width The number of columns to fill.\n   * @param height The number of rows to fill.\n   */\n  protected _fillCells(x: number, y: number, width: number, height: number): void {\n    this._ctx.fillRect(\n        x * this._scaledCellWidth,\n        y * this._scaledCellHeight,\n        width * this._scaledCellWidth,\n        height * this._scaledCellHeight);\n  }\n\n  /**\n   * Fills a 1px line (2px on HDPI) at the bottom of the cell. This uses the\n   * existing fillStyle on the context.\n   * @param x The column to fill.\n   * @param y The row to fill.\n   */\n  protected _fillBottomLineAtCells(x: number, y: number, width: number = 1): void {\n    this._ctx.fillRect(\n        x * this._scaledCellWidth,\n        (y + 1) * this._scaledCellHeight - window.devicePixelRatio - 1 /* Ensure it's drawn within the cell */,\n        width * this._scaledCellWidth,\n        window.devicePixelRatio);\n  }\n\n  /**\n   * Fills a 1px line (2px on HDPI) at the left of the cell. This uses the\n   * existing fillStyle on the context.\n   * @param x The column to fill.\n   * @param y The row to fill.\n   */\n  protected _fillLeftLineAtCell(x: number, y: number): void {\n    this._ctx.fillRect(\n        x * this._scaledCellWidth,\n        y * this._scaledCellHeight,\n        window.devicePixelRatio,\n        this._scaledCellHeight);\n  }\n\n  /**\n   * Strokes a 1px rectangle (2px on HDPI) around a cell. This uses the existing\n   * strokeStyle on the context.\n   * @param x The column to fill.\n   * @param y The row to fill.\n   */\n  protected _strokeRectAtCell(x: number, y: number, width: number, height: number): void {\n    this._ctx.lineWidth = window.devicePixelRatio;\n    this._ctx.strokeRect(\n        x * this._scaledCellWidth + window.devicePixelRatio / 2,\n        y * this._scaledCellHeight + (window.devicePixelRatio / 2),\n        width * this._scaledCellWidth - window.devicePixelRatio,\n        (height * this._scaledCellHeight) - window.devicePixelRatio);\n  }\n\n  /**\n   * Clears the entire canvas.\n   */\n  protected _clearAll(): void {\n    if (this._alpha) {\n      this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);\n    } else {\n      this._ctx.fillStyle = this._colors.background.css;\n      this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);\n    }\n  }\n\n  /**\n   * Clears 1+ cells completely.\n   * @param x The column to start at.\n   * @param y The row to start at.\n   * @param width The number of columns to clear.\n   * @param height The number of rows to clear.\n   */\n  protected _clearCells(x: number, y: number, width: number, height: number): void {\n    if (this._alpha) {\n      this._ctx.clearRect(\n          x * this._scaledCellWidth,\n          y * this._scaledCellHeight,\n          width * this._scaledCellWidth,\n          height * this._scaledCellHeight);\n    } else {\n      this._ctx.fillStyle = this._colors.background.css;\n      this._ctx.fillRect(\n          x * this._scaledCellWidth,\n          y * this._scaledCellHeight,\n          width * this._scaledCellWidth,\n          height * this._scaledCellHeight);\n    }\n  }\n\n  /**\n   * Draws a truecolor character at the cell. The character will be clipped to\n   * ensure that it fits with the cell, including the cell to the right if it's\n   * a wide character. This uses the existing fillStyle on the context.\n   * @param cell The cell data for the character to draw.\n   * @param x The column to draw at.\n   * @param y The row to draw at.\n   * @param color The color of the character.\n   */\n  protected _fillCharTrueColor(cell: CellData, x: number, y: number): void {\n    this._ctx.font = this._getFont(false, false);\n    this._ctx.textBaseline = 'middle';\n    this._clipRow(y);\n    this._ctx.fillText(\n        cell.getChars(),\n        x * this._scaledCellWidth + this._scaledCharLeft,\n        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);\n  }\n\n  /**\n   * Draws one or more characters at a cell. If possible this will draw using\n   * the character atlas to reduce draw time.\n   * @param chars The character or characters.\n   * @param code The character code.\n   * @param width The width of the characters.\n   * @param x The column to draw at.\n   * @param y The row to draw at.\n   * @param fg The foreground color, in the format stored within the attributes.\n   * @param bg The background color, in the format stored within the attributes.\n   * This is used to validate whether a cached image can be used.\n   * @param bold Whether the text is bold.\n   */\n  protected _drawChars(cell: ICellData, x: number, y: number): void {\n\n    // skip cache right away if we draw in RGB\n    // Note: to avoid bad runtime JoinedCellData will be skipped\n    //       in the cache handler itself (atlasDidDraw == false) and\n    //       fall through to uncached later down below\n    if (cell.isFgRGB() || cell.isBgRGB()) {\n      this._drawUncachedChars(cell, x, y);\n      return;\n    }\n\n    let fg;\n    let bg;\n    if (cell.isInverse()) {\n      fg = (cell.isBgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getBgColor();\n      bg = (cell.isFgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getFgColor();\n    } else {\n      bg = (cell.isBgDefault()) ? DEFAULT_COLOR : cell.getBgColor();\n      fg = (cell.isFgDefault()) ? DEFAULT_COLOR : cell.getFgColor();\n    }\n\n    const drawInBrightColor = this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8 && fg !== INVERTED_DEFAULT_COLOR;\n\n    fg += drawInBrightColor ? 8 : 0;\n    this._currentGlyphIdentifier.chars = cell.getChars() || WHITESPACE_CELL_CHAR;\n    this._currentGlyphIdentifier.code = cell.getCode() || WHITESPACE_CELL_CODE;\n    this._currentGlyphIdentifier.bg = bg;\n    this._currentGlyphIdentifier.fg = fg;\n    this._currentGlyphIdentifier.bold = !!cell.isBold();\n    this._currentGlyphIdentifier.dim = !!cell.isDim();\n    this._currentGlyphIdentifier.italic = !!cell.isItalic();\n    const atlasDidDraw = this._charAtlas && this._charAtlas.draw(\n      this._ctx,\n      this._currentGlyphIdentifier,\n      x * this._scaledCellWidth + this._scaledCharLeft,\n      y * this._scaledCellHeight + this._scaledCharTop\n    );\n\n    if (!atlasDidDraw) {\n      this._drawUncachedChars(cell, x, y);\n    }\n  }\n\n  /**\n   * Draws one or more characters at one or more cells. The character(s) will be\n   * clipped to ensure that they fit with the cell(s), including the cell to the\n   * right if the last character is a wide character.\n   * @param chars The character.\n   * @param width The width of the character.\n   * @param fg The foreground color, in the format stored within the attributes.\n   * @param x The column to draw at.\n   * @param y The row to draw at.\n   */\n  private _drawUncachedChars(cell: ICellData, x: number, y: number): void {\n    this._ctx.save();\n    this._ctx.font = this._getFont(!!cell.isBold(), !!cell.isItalic());\n    this._ctx.textBaseline = 'middle';\n\n    if (cell.isInverse()) {\n      if (cell.isBgDefault()) {\n        this._ctx.fillStyle = this._colors.background.css;\n      } else if (cell.isBgRGB()) {\n        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;\n      } else {\n        this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;\n      }\n    } else {\n      if (cell.isFgDefault()) {\n        this._ctx.fillStyle = this._colors.foreground.css;\n      } else if (cell.isFgRGB()) {\n        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;\n      } else {\n        let fg = cell.getFgColor();\n        if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {\n          fg += 8;\n        }\n        this._ctx.fillStyle = this._colors.ansi[fg].css;\n      }\n    }\n\n    this._clipRow(y);\n\n    // Apply alpha to dim the character\n    if (cell.isDim()) {\n      this._ctx.globalAlpha = DIM_OPACITY;\n    }\n    // Draw the character\n    this._ctx.fillText(\n        cell.getChars(),\n        x * this._scaledCellWidth + this._scaledCharLeft,\n        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);\n    this._ctx.restore();\n  }\n\n  /**\n   * Clips a row to ensure no pixels will be drawn outside the cells in the row.\n   * @param y The row to clip.\n   */\n  private _clipRow(y: number): void {\n    this._ctx.beginPath();\n    this._ctx.rect(\n        0,\n        y * this._scaledCellHeight,\n        this._bufferService.cols * this._scaledCellWidth,\n        this._scaledCellHeight);\n    this._ctx.clip();\n  }\n\n  /**\n   * Gets the current font.\n   * @param isBold If we should use the bold fontWeight.\n   */\n  protected _getFont(isBold: boolean, isItalic: boolean): string {\n    const fontWeight = isBold ? this._optionsService.options.fontWeightBold : this._optionsService.options.fontWeight;\n    const fontStyle = isItalic ? 'italic' : '';\n\n    return `${fontStyle} ${fontWeight} ${this._optionsService.options.fontSize * window.devicePixelRatio}px ${this._optionsService.options.fontFamily}`;\n  }\n}\n\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IServiceIdentifier } from 'common/services/Services';\n\nconst DI_TARGET = 'di$target';\nconst DI_DEPENDENCIES = 'di$dependencies';\n\nexport const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map();\n\nexport function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] {\n  return ctor[DI_DEPENDENCIES] || [];\n}\n\nexport function createDecorator<T>(id: string): IServiceIdentifier<T> {\n  if (serviceRegistry.has(id)) {\n    return serviceRegistry.get(id)!;\n  }\n\n  const decorator = <any>function (target: Function, key: string, index: number): any {\n    if (arguments.length !== 3) {\n      throw new Error('@IServiceName-decorator can only be used to decorate a parameter');\n    }\n\n    storeServiceDependency(decorator, target, index);\n  };\n\n  decorator.toString = () => id;\n\n  serviceRegistry.set(id, decorator);\n  return decorator;\n}\n\nfunction storeServiceDependency(id: Function, target: Function, index: number): void {\n  if ((target as any)[DI_TARGET] === target) {\n    (target as any)[DI_DEPENDENCIES].push({ id, index });\n  } else {\n    (target as any)[DI_DEPENDENCIES] = [{ id, index }];\n    (target as any)[DI_TARGET] = target;\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport type TypedArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray\n  | Int8Array | Int16Array | Int32Array\n  | Float32Array | Float64Array;\n\n\n/**\n * polyfill for TypedArray.fill\n * This is needed to support .fill in all safari versions and IE 11.\n */\nexport function fill<T extends TypedArray>(array: T, value: number, start?: number, end?: number): T {\n  // all modern engines that support .fill\n  if (array.fill) {\n    return array.fill(value, start, end) as T;\n  }\n  return fillFallback(array, value, start, end);\n}\n\nexport function fillFallback<T extends TypedArray>(array: T, value: number, start: number = 0, end: number = array.length): T {\n  // safari and IE 11\n  // since IE 11 does not support Array.prototype.fill either\n  // we cannot use the suggested polyfill from MDN\n  // instead we simply fall back to looping\n  if (start >= array.length) {\n    return array;\n  }\n  start = (array.length + start) % array.length;\n  if (end >= array.length) {\n    end = array.length;\n  } else {\n    end = (array.length + end) % array.length;\n  }\n  for (let i = start; i < end; ++i) {\n    array[i] = value;\n  }\n  return array;\n}\n\n/**\n * Concat two typed arrays `a` and `b`.\n * Returns a new typed array.\n */\nexport function concat<T extends TypedArray>(a: T, b: T): T {\n  const result = new (a.constructor as any)(a.length + b.length);\n  result.set(a);\n  result.set(b, a.length);\n  return result;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CharData, IBufferLine, ICellData } from 'common/Types';\nimport { stringFromCodePoint } from 'common/input/TextDecoder';\nimport { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { AttributeData } from 'common/buffer/AttributeData';\n\n/**\n * buffer memory layout:\n *\n *   |             uint32_t             |        uint32_t         |        uint32_t         |\n *   |             `content`            |          `FG`           |          `BG`           |\n *   | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) |\n */\n\n\n/** typed array slots taken by one cell */\nconst CELL_SIZE = 3;\n\n/**\n * Cell member indices.\n *\n * Direct access:\n *    `content = data[column * CELL_SIZE + Cell.CONTENT];`\n *    `fg = data[column * CELL_SIZE + Cell.FG];`\n *    `bg = data[column * CELL_SIZE + Cell.BG];`\n */\nconst enum Cell {\n  CONTENT = 0,\n  FG = 1, // currently simply holds all known attrs\n  BG = 2  // currently unused\n}\n\nexport const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData());\n\n/**\n * Typed array based bufferline implementation.\n *\n * There are 2 ways to insert data into the cell buffer:\n * - `setCellFromCodepoint` + `addCodepointToCell`\n *   Use these for data that is already UTF32.\n *   Used during normal input in `InputHandler` for faster buffer access.\n * - `setCell`\n *   This method takes a CellData object and stores the data in the buffer.\n *   Use `CellData.fromCharData` to create the CellData object (e.g. from JS string).\n *\n * To retrieve data from the buffer use either one of the primitive methods\n * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop\n * memory allocs / GC pressure can be greatly reduced by reusing the CellData object.\n */\nexport class BufferLine implements IBufferLine {\n  protected _data: Uint32Array;\n  protected _combined: {[index: number]: string} = {};\n  public length: number;\n\n  constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) {\n    this._data = new Uint32Array(cols * CELL_SIZE);\n    const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n    for (let i = 0; i < cols; ++i) {\n      this.setCell(i, cell);\n    }\n    this.length = cols;\n  }\n\n  /**\n   * Get cell data CharData.\n   * @deprecated\n   */\n  public get(index: number): CharData {\n    const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    const cp = content & Content.CODEPOINT_MASK;\n    return [\n      this._data[index * CELL_SIZE + Cell.FG],\n      (content & Content.IS_COMBINED_MASK)\n        ? this._combined[index]\n        : (cp) ? stringFromCodePoint(cp) : '',\n      content >> Content.WIDTH_SHIFT,\n      (content & Content.IS_COMBINED_MASK)\n        ? this._combined[index].charCodeAt(this._combined[index].length - 1)\n        : cp\n    ];\n  }\n\n  /**\n   * Set cell data from CharData.\n   * @deprecated\n   */\n  public set(index: number, value: CharData): void {\n    this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX];\n    if (value[CHAR_DATA_CHAR_INDEX].length > 1) {\n      this._combined[index] = value[1];\n      this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    } else {\n      this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);\n    }\n  }\n\n  /**\n   * primitive getters\n   * use these when only one value is needed, otherwise use `loadCell`\n   */\n  public getWidth(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT;\n  }\n\n  /** Test whether content has width. */\n  public hasWidth(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK;\n  }\n\n  /** Get FG cell component. */\n  public getFg(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.FG];\n  }\n\n  /** Get BG cell component. */\n  public getBg(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.BG];\n  }\n\n  /**\n   * Test whether contains any chars.\n   * Basically an empty has no content, but other cells might differ in FG/BG\n   * from real empty cells.\n   * */\n  public hasContent(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK;\n  }\n\n  /**\n   * Get codepoint of the cell.\n   * To be in line with `code` in CharData this either returns\n   * a single UTF32 codepoint or the last codepoint of a combined string.\n   */\n  public getCodePoint(index: number): number {\n    const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    if (content & Content.IS_COMBINED_MASK) {\n      return this._combined[index].charCodeAt(this._combined[index].length - 1);\n    }\n    return content & Content.CODEPOINT_MASK;\n  }\n\n  /** Test whether the cell contains a combined string. */\n  public isCombined(index: number): number {\n    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK;\n  }\n\n  /** Returns the string content of the cell. */\n  public getString(index: number): string {\n    const content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    if (content & Content.IS_COMBINED_MASK) {\n      return this._combined[index];\n    }\n    if (content & Content.CODEPOINT_MASK) {\n      return stringFromCodePoint(content & Content.CODEPOINT_MASK);\n    }\n    // return empty string for empty cells\n    return '';\n  }\n\n  /**\n   * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly\n   * to GC as it significantly reduced the amount of new objects/references needed.\n   */\n  public loadCell(index: number, cell: ICellData): ICellData {\n    const startIndex = index * CELL_SIZE;\n    cell.content = this._data[startIndex + Cell.CONTENT];\n    cell.fg = this._data[startIndex + Cell.FG];\n    cell.bg = this._data[startIndex + Cell.BG];\n    if (cell.content & Content.IS_COMBINED_MASK) {\n      cell.combinedData = this._combined[index];\n    }\n    return cell;\n  }\n\n  /**\n   * Set data at `index` to `cell`.\n   */\n  public setCell(index: number, cell: ICellData): void {\n    if (cell.content & Content.IS_COMBINED_MASK) {\n      this._combined[index] = cell.combinedData;\n    }\n    this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content;\n    this._data[index * CELL_SIZE + Cell.FG] = cell.fg;\n    this._data[index * CELL_SIZE + Cell.BG] = cell.bg;\n  }\n\n  /**\n   * Set cell data from input handler.\n   * Since the input handler see the incoming chars as UTF32 codepoints,\n   * it gets an optimized access method.\n   */\n  public setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number): void {\n    this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);\n    this._data[index * CELL_SIZE + Cell.FG] = fg;\n    this._data[index * CELL_SIZE + Cell.BG] = bg;\n  }\n\n  /**\n   * Add a codepoint to a cell from input handler.\n   * During input stage combining chars with a width of 0 follow and stack\n   * onto a leading char. Since we already set the attrs\n   * by the previous `setDataFromCodePoint` call, we can omit it here.\n   */\n  public addCodepointToCell(index: number, codePoint: number): void {\n    let content = this._data[index * CELL_SIZE + Cell.CONTENT];\n    if (content & Content.IS_COMBINED_MASK) {\n      // we already have a combined string, simply add\n      this._combined[index] += stringFromCodePoint(codePoint);\n    } else {\n      if (content & Content.CODEPOINT_MASK) {\n        // normal case for combining chars:\n        //  - move current leading char + new one into combined string\n        //  - set combined flag\n        this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint);\n        content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0\n        content |= Content.IS_COMBINED_MASK;\n      } else {\n        // should not happen - we actually have no data in the cell yet\n        // simply set the data in the cell buffer with a width of 1\n        content = codePoint | (1 << Content.WIDTH_SHIFT);\n      }\n      this._data[index * CELL_SIZE + Cell.CONTENT] = content;\n    }\n  }\n\n  public insertCells(pos: number, n: number, fillCellData: ICellData): void {\n    pos %= this.length;\n    if (n < this.length - pos) {\n      const cell = new CellData();\n      for (let i = this.length - pos - n - 1; i >= 0; --i) {\n        this.setCell(pos + n + i, this.loadCell(pos + i, cell));\n      }\n      for (let i = 0; i < n; ++i) {\n        this.setCell(pos + i, fillCellData);\n      }\n    } else {\n      for (let i = pos; i < this.length; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    }\n  }\n\n  public deleteCells(pos: number, n: number, fillCellData: ICellData): void {\n    pos %= this.length;\n    if (n < this.length - pos) {\n      const cell = new CellData();\n      for (let i = 0; i < this.length - pos - n; ++i) {\n        this.setCell(pos + i, this.loadCell(pos + n + i, cell));\n      }\n      for (let i = this.length - n; i < this.length; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    } else {\n      for (let i = pos; i < this.length; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    }\n  }\n\n  public replaceCells(start: number, end: number, fillCellData: ICellData): void {\n    while (start < end  && start < this.length) {\n      this.setCell(start++, fillCellData);\n    }\n  }\n\n  public resize(cols: number, fillCellData: ICellData): void {\n    if (cols === this.length) {\n      return;\n    }\n    if (cols > this.length) {\n      const data = new Uint32Array(cols * CELL_SIZE);\n      if (this.length) {\n        if (cols * CELL_SIZE < this._data.length) {\n          data.set(this._data.subarray(0, cols * CELL_SIZE));\n        } else {\n          data.set(this._data);\n        }\n      }\n      this._data = data;\n      for (let i = this.length; i < cols; ++i) {\n        this.setCell(i, fillCellData);\n      }\n    } else {\n      if (cols) {\n        const data = new Uint32Array(cols * CELL_SIZE);\n        data.set(this._data.subarray(0, cols * CELL_SIZE));\n        this._data = data;\n        // Remove any cut off combined data\n        const keys = Object.keys(this._combined);\n        for (let i = 0; i < keys.length; i++) {\n          const key = parseInt(keys[i], 10);\n          if (key >= cols) {\n            delete this._combined[key];\n          }\n        }\n      } else {\n        this._data = new Uint32Array(0);\n        this._combined = {};\n      }\n    }\n    this.length = cols;\n  }\n\n  /** fill a line with fillCharData */\n  public fill(fillCellData: ICellData): void {\n    this._combined = {};\n    for (let i = 0; i < this.length; ++i) {\n      this.setCell(i, fillCellData);\n    }\n  }\n\n  /** alter to a full copy of line  */\n  public copyFrom(line: BufferLine): void {\n    if (this.length !== line.length) {\n      this._data = new Uint32Array(line._data);\n    } else {\n      // use high speed copy if lengths are equal\n      this._data.set(line._data);\n    }\n    this.length = line.length;\n    this._combined = {};\n    for (const el in line._combined) {\n      this._combined[el] = line._combined[el];\n    }\n    this.isWrapped = line.isWrapped;\n  }\n\n  /** create a new clone */\n  public clone(): IBufferLine {\n    const newLine = new BufferLine(0);\n    newLine._data = new Uint32Array(this._data);\n    newLine.length = this.length;\n    for (const el in this._combined) {\n      newLine._combined[el] = this._combined[el];\n    }\n    newLine.isWrapped = this.isWrapped;\n    return newLine;\n  }\n\n  public getTrimmedLength(): number {\n    for (let i = this.length - 1; i >= 0; --i) {\n      if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) {\n        return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);\n      }\n    }\n    return 0;\n  }\n\n  public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void {\n    const srcData = src._data;\n    if (applyInReverse) {\n      for (let cell = length - 1; cell >= 0; cell--) {\n        for (let i = 0; i < CELL_SIZE; i++) {\n          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n        }\n      }\n    } else {\n      for (let cell = 0; cell < length; cell++) {\n        for (let i = 0; i < CELL_SIZE; i++) {\n          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];\n        }\n      }\n    }\n\n    // Move any combined data over as needed\n    const srcCombinedKeys = Object.keys(src._combined);\n    for (let i = 0; i < srcCombinedKeys.length; i++) {\n      const key = parseInt(srcCombinedKeys[i], 10);\n      if (key >= srcCol) {\n        this._combined[key - srcCol + destCol] = src._combined[key];\n      }\n    }\n  }\n\n  public translateToString(trimRight: boolean = false, startCol: number = 0, endCol: number = this.length): string {\n    if (trimRight) {\n      endCol = Math.min(endCol, this.getTrimmedLength());\n    }\n    let result = '';\n    while (startCol < endCol) {\n      const content = this._data[startCol * CELL_SIZE + Cell.CONTENT];\n      const cp = content & Content.CODEPOINT_MASK;\n      result += (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;\n      startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by 1\n    }\n    return result;\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport let promptLabel = 'Terminal input';\nexport let tooMuchOutput = 'Too much output to announce, navigate to rows manually to read';\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharset } from 'common/Types';\n\n/**\n * The character sets supported by the terminal. These enable several languages\n * to be represented within the terminal with only 8-bit encoding. See ISO 2022\n * for a discussion on character sets. Only VT100 character sets are supported.\n */\nexport const CHARSETS: { [key: string]: ICharset | null } = {};\n\n/**\n * The default character set, US.\n */\nexport const DEFAULT_CHARSET: ICharset | null = CHARSETS['B'];\n\n/**\n * DEC Special Character and Line Drawing Set.\n * Reference: http://vt100.net/docs/vt102-ug/table5-13.html\n * A lot of curses apps use this if they see TERM=xterm.\n * testing: echo -e '\\e(0a\\e(B'\n * The xterm output sometimes seems to conflict with the\n * reference above. xterm seems in line with the reference\n * when running vttest however.\n * The table below now uses xterm's output from vttest.\n */\nCHARSETS['0'] = {\n  '`': '\\u25c6', // '◆'\n  'a': '\\u2592', // '▒'\n  'b': '\\u0009', // '\\t'\n  'c': '\\u000c', // '\\f'\n  'd': '\\u000d', // '\\r'\n  'e': '\\u000a', // '\\n'\n  'f': '\\u00b0', // '°'\n  'g': '\\u00b1', // '±'\n  'h': '\\u2424', // '\\u2424' (NL)\n  'i': '\\u000b', // '\\v'\n  'j': '\\u2518', // '┘'\n  'k': '\\u2510', // '┐'\n  'l': '\\u250c', // '┌'\n  'm': '\\u2514', // '└'\n  'n': '\\u253c', // '┼'\n  'o': '\\u23ba', // '⎺'\n  'p': '\\u23bb', // '⎻'\n  'q': '\\u2500', // '─'\n  'r': '\\u23bc', // '⎼'\n  's': '\\u23bd', // '⎽'\n  't': '\\u251c', // '├'\n  'u': '\\u2524', // '┤'\n  'v': '\\u2534', // '┴'\n  'w': '\\u252c', // '┬'\n  'x': '\\u2502', // '│'\n  'y': '\\u2264', // '≤'\n  'z': '\\u2265', // '≥'\n  '{': '\\u03c0', // 'π'\n  '|': '\\u2260', // '≠'\n  '}': '\\u00a3', // '£'\n  '~': '\\u00b7'  // '·'\n};\n\n/**\n * British character set\n * ESC (A\n * Reference: http://vt100.net/docs/vt220-rm/table2-5.html\n */\nCHARSETS['A'] = {\n  '#': '£'\n};\n\n/**\n * United States character set\n * ESC (B\n */\nCHARSETS['B'] = null;\n\n/**\n * Dutch character set\n * ESC (4\n * Reference: http://vt100.net/docs/vt220-rm/table2-6.html\n */\nCHARSETS['4'] = {\n  '#': '£',\n  '@': '¾',\n  '[': 'ij',\n  '\\\\': '½',\n  ']': '|',\n  '{': '¨',\n  '|': 'f',\n  '}': '¼',\n  '~': '´'\n};\n\n/**\n * Finnish character set\n * ESC (C or ESC (5\n * Reference: http://vt100.net/docs/vt220-rm/table2-7.html\n */\nCHARSETS['C'] =\nCHARSETS['5'] = {\n  '[': 'Ä',\n  '\\\\': 'Ö',\n  ']': 'Å',\n  '^': 'Ü',\n  '`': 'é',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'å',\n  '~': 'ü'\n};\n\n/**\n * French character set\n * ESC (R\n * Reference: http://vt100.net/docs/vt220-rm/table2-8.html\n */\nCHARSETS['R'] = {\n  '#': '£',\n  '@': 'à',\n  '[': '°',\n  '\\\\': 'ç',\n  ']': '§',\n  '{': 'é',\n  '|': 'ù',\n  '}': 'è',\n  '~': '¨'\n};\n\n/**\n * French Canadian character set\n * ESC (Q\n * Reference: http://vt100.net/docs/vt220-rm/table2-9.html\n */\nCHARSETS['Q'] = {\n  '@': 'à',\n  '[': 'â',\n  '\\\\': 'ç',\n  ']': 'ê',\n  '^': 'î',\n  '`': 'ô',\n  '{': 'é',\n  '|': 'ù',\n  '}': 'è',\n  '~': 'û'\n};\n\n/**\n * German character set\n * ESC (K\n * Reference: http://vt100.net/docs/vt220-rm/table2-10.html\n */\nCHARSETS['K'] = {\n  '@': '§',\n  '[': 'Ä',\n  '\\\\': 'Ö',\n  ']': 'Ü',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'ü',\n  '~': 'ß'\n};\n\n/**\n * Italian character set\n * ESC (Y\n * Reference: http://vt100.net/docs/vt220-rm/table2-11.html\n */\nCHARSETS['Y'] = {\n  '#': '£',\n  '@': '§',\n  '[': '°',\n  '\\\\': 'ç',\n  ']': 'é',\n  '`': 'ù',\n  '{': 'à',\n  '|': 'ò',\n  '}': 'è',\n  '~': 'ì'\n};\n\n/**\n * Norwegian/Danish character set\n * ESC (E or ESC (6\n * Reference: http://vt100.net/docs/vt220-rm/table2-12.html\n */\nCHARSETS['E'] =\nCHARSETS['6'] = {\n  '@': 'Ä',\n  '[': 'Æ',\n  '\\\\': 'Ø',\n  ']': 'Å',\n  '^': 'Ü',\n  '`': 'ä',\n  '{': 'æ',\n  '|': 'ø',\n  '}': 'å',\n  '~': 'ü'\n};\n\n/**\n * Spanish character set\n * ESC (Z\n * Reference: http://vt100.net/docs/vt220-rm/table2-13.html\n */\nCHARSETS['Z'] = {\n  '#': '£',\n  '@': '§',\n  '[': '¡',\n  '\\\\': 'Ñ',\n  ']': '¿',\n  '{': '°',\n  '|': 'ñ',\n  '}': 'ç'\n};\n\n/**\n * Swedish character set\n * ESC (H or ESC (7\n * Reference: http://vt100.net/docs/vt220-rm/table2-14.html\n */\nCHARSETS['H'] =\nCHARSETS['7'] = {\n  '@': 'É',\n  '[': 'Ä',\n  '\\\\': 'Ö',\n  ']': 'Å',\n  '^': 'Ü',\n  '`': 'é',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'å',\n  '~': 'ü'\n};\n\n/**\n * Swiss character set\n * ESC (=\n * Reference: http://vt100.net/docs/vt220-rm/table2-15.html\n */\nCHARSETS['='] = {\n  '#': 'ù',\n  '@': 'à',\n  '[': 'é',\n  '\\\\': 'ç',\n  ']': 'ê',\n  '^': 'î',\n  '_': 'è',\n  '`': 'ô',\n  '{': 'ä',\n  '|': 'ö',\n  '}': 'ü',\n  '~': 'û'\n};\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { fill } from 'common/TypedArrayUtils';\n\nexport const wcwidth = (function(opts: {nul: number, control: number}): (ucs: number) => number {\n  // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c\n  // combining characters\n  const COMBINING_BMP = [\n    [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],\n    [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],\n    [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],\n    [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],\n    [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],\n    [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],\n    [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],\n    [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],\n    [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],\n    [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],\n    [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],\n    [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],\n    [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],\n    [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],\n    [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],\n    [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],\n    [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],\n    [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],\n    [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],\n    [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],\n    [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],\n    [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],\n    [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],\n    [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],\n    [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],\n    [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],\n    [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],\n    [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],\n    [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],\n    [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],\n    [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],\n    [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],\n    [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],\n    [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],\n    [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],\n    [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],\n    [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],\n    [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],\n    [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],\n    [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],\n    [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],\n    [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],\n    [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]\n  ];\n  const COMBINING_HIGH = [\n    [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],\n    [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],\n    [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],\n    [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],\n    [0xE0100, 0xE01EF]\n  ];\n  // binary search\n  function bisearch(ucs: number, data: number[][]): boolean {\n    let min = 0;\n    let max = data.length - 1;\n    let mid;\n    if (ucs < data[0][0] || ucs > data[max][1]) {\n      return false;\n    }\n    while (max >= min) {\n      mid = (min + max) >> 1;\n      if (ucs > data[mid][1]) {\n        min = mid + 1;\n      } else if (ucs < data[mid][0]) {\n        max = mid - 1;\n      } else {\n        return true;\n      }\n    }\n    return false;\n  }\n  function wcwidthHigh(ucs: number): 0 | 1 | 2 {\n    if (bisearch(ucs, COMBINING_HIGH)) {\n      return 0;\n    }\n    if ((ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd)) {\n      return 2;\n    }\n    return 1;\n  }\n  const control = opts.control | 0;\n\n  // create lookup table for BMP plane\n  const table = new Uint8Array(65536);\n  fill(table, 1);\n  table[0] = opts.nul;\n  // control chars\n  fill(table, opts.control, 1, 32);\n  fill(table, opts.control, 0x7f, 0xa0);\n\n  // apply wide char rules first\n  // wide chars\n  fill(table, 2, 0x1100, 0x1160);\n  table[0x2329] = 2;\n  table[0x232a] = 2;\n  fill(table, 2, 0x2e80, 0xa4d0);\n  table[0x303f] = 1;  // wrongly in last line\n\n  fill(table, 2, 0xac00, 0xd7a4);\n  fill(table, 2, 0xf900, 0xfb00);\n  fill(table, 2, 0xfe10, 0xfe1a);\n  fill(table, 2, 0xfe30, 0xfe70);\n  fill(table, 2, 0xff00, 0xff61);\n  fill(table, 2, 0xffe0, 0xffe7);\n\n  // apply combining last to ensure we overwrite\n  // wrongly wide set chars:\n  //    the original algo evals combining first and falls\n  //    through to wide check so we simply do here the opposite\n  // combining 0\n  for (let r = 0; r < COMBINING_BMP.length; ++r) {\n    fill(table, 0, COMBINING_BMP[r][0], COMBINING_BMP[r][1] + 1);\n  }\n\n  return function (num: number): number {\n    if (num < 32) {\n      return control | 0;\n    }\n    if (num < 127) {\n      return 1;\n    }\n    if (num < 65536) {\n      return table[num];\n    }\n    // do a full search for high codepoints\n    return wcwidthHigh(num);\n  };\n})({nul: 0, control: 0});  // configurable options\n\n/**\n * Get the terminal cell width for a string.\n */\nexport function getStringCellWidth(s: string): number {\n  let result = 0;\n  const length = s.length;\n  for (let i = 0; i < length; ++i) {\n    let code = s.charCodeAt(i);\n    // surrogate pair first\n    if (0xD800 <= code && code <= 0xDBFF) {\n      if (++i >= length) {\n        // this should not happen with strings retrieved from\n        // Buffer.translateToString as it converts from UTF-32\n        // and therefore always should contain the second part\n        // for any other string we still have to handle it somehow:\n        // simply treat the lonely surrogate first as a single char (UCS-2 behavior)\n        return result + wcwidth(code);\n      }\n      const second = s.charCodeAt(i);\n      // convert surrogate pair to high codepoint only for valid second part (UTF-16)\n      // otherwise treat them independently (UCS-2 behavior)\n      if (0xDC00 <= second && second <= 0xDFFF) {\n        code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n      } else {\n        result += wcwidth(second);\n      }\n    }\n    result += wcwidth(code);\n  }\n  return result;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IParams, ParamsArray } from 'common/parser/Types';\n\n// max value supported for a single param/subparam (clamped to positive int32 range)\nconst MAX_VALUE = 0x7FFFFFFF;\n// max allowed subparams for a single sequence (hardcoded limitation)\nconst MAX_SUBPARAMS = 256;\n\n/**\n * Params storage class.\n * This type is used by the parser to accumulate sequence parameters and sub parameters\n * and transmit them to the input handler actions.\n *\n * NOTES:\n *  - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy\n *  - never read beyond `params.length - 1` (likely to contain arbitrary data)\n *  - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params\n *  - hardcoded limitations:\n *    - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that)\n *    - max. 256 sub params possible\n *    - negative values are not allowed beside -1 (placeholder for default value)\n *\n * About ZDM (Zero Default Mode):\n * ZDM is not orchestrated by this class. If the parser is in ZDM,\n * it should add 0 for empty params, otherwise -1. This does not apply\n * to subparams, empty subparams should always be added with -1.\n */\nexport class Params implements IParams {\n  // params store and length\n  public params: Int32Array;\n  public length: number;\n\n  // sub params store and length\n  protected _subParams: Int32Array;\n  protected _subParamsLength: number;\n\n  // sub params offsets from param: param idx --> [start, end] offset\n  private _subParamsIdx: Uint16Array;\n  private _rejectDigits: boolean;\n  private _rejectSubDigits: boolean;\n  private _digitIsSub: boolean;\n\n  /**\n   * Create a `Params` type from JS array representation.\n   */\n  public static fromArray(values: ParamsArray): Params {\n    const params = new Params();\n    if (!values.length) {\n      return params;\n    }\n    // skip leading sub params\n    for (let i = (values[0] instanceof Array) ? 1 : 0; i < values.length; ++i) {\n      const value = values[i];\n      if (value instanceof Array) {\n        for (let k = 0; k < value.length; ++k) {\n          params.addSubParam(value[k]);\n        }\n      } else {\n        params.addParam(value);\n      }\n    }\n    return params;\n  }\n\n  /**\n   * @param maxLength max length of storable parameters\n   * @param maxSubParamsLength max length of storable sub parameters\n   */\n  constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) {\n    if (maxSubParamsLength > MAX_SUBPARAMS) {\n      throw new Error('maxSubParamsLength must not be greater than 256');\n    }\n    this.params = new Int32Array(maxLength);\n    this.length = 0;\n    this._subParams = new Int32Array(maxSubParamsLength);\n    this._subParamsLength = 0;\n    this._subParamsIdx = new Uint16Array(maxLength);\n    this._rejectDigits = false;\n    this._rejectSubDigits = false;\n    this._digitIsSub = false;\n  }\n\n  /**\n   * Clone object.\n   */\n  public clone(): Params {\n    const newParams = new Params(this.maxLength, this.maxSubParamsLength);\n    newParams.params.set(this.params);\n    newParams.length = this.length;\n    newParams._subParams.set(this._subParams);\n    newParams._subParamsLength = this._subParamsLength;\n    newParams._subParamsIdx.set(this._subParamsIdx);\n    newParams._rejectDigits = this._rejectDigits;\n    newParams._rejectSubDigits = this._rejectSubDigits;\n    newParams._digitIsSub = this._digitIsSub;\n    return newParams;\n  }\n\n  /**\n   * Get a JS array representation of the current parameters and sub parameters.\n   * The array is structured as follows:\n   *    sequence: \"1;2:3:4;5::6\"\n   *    array   : [1, 2, [3, 4], 5, [-1, 6]]\n   */\n  public toArray(): ParamsArray {\n    const res: ParamsArray = [];\n    for (let i = 0; i < this.length; ++i) {\n      res.push(this.params[i]);\n      const start = this._subParamsIdx[i] >> 8;\n      const end = this._subParamsIdx[i] & 0xFF;\n      if (end - start > 0) {\n        res.push(Array.prototype.slice.call(this._subParams, start, end));\n      }\n    }\n    return res;\n  }\n\n  /**\n   * Reset to initial empty state.\n   */\n  public reset(): void {\n    this.length = 0;\n    this._subParamsLength = 0;\n    this._rejectDigits = false;\n    this._rejectSubDigits = false;\n    this._digitIsSub = false;\n  }\n\n  /**\n   * Add a parameter value.\n   * `Params` only stores up to `maxLength` parameters, any later\n   * parameter will be ignored.\n   * Note: VT devices only stored up to 16 values, xterm seems to\n   * store up to 30.\n   */\n  public addParam(value: number): void {\n    this._digitIsSub = false;\n    if (this.length >= this.maxLength) {\n      this._rejectDigits = true;\n      return;\n    }\n    if (value < -1) {\n      throw new Error('values lesser than -1 are not allowed');\n    }\n    this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength;\n    this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value;\n  }\n\n  /**\n   * Add a sub parameter value.\n   * The sub parameter is automatically associated with the last parameter value.\n   * Thus it is not possible to add a subparameter without any parameter added yet.\n   * `Params` only stores up to `subParamsLength` sub parameters, any later\n   * sub parameter will be ignored.\n   */\n  public addSubParam(value: number): void {\n    this._digitIsSub = true;\n    if (!this.length) {\n      return;\n    }\n    if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) {\n      this._rejectSubDigits = true;\n      return;\n    }\n    if (value < -1) {\n      throw new Error('values lesser than -1 are not allowed');\n    }\n    this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value;\n    this._subParamsIdx[this.length - 1]++;\n  }\n\n  /**\n   * Whether parameter at index `idx` has sub parameters.\n   */\n  public hasSubParams(idx: number): boolean {\n    return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);\n  }\n\n  /**\n   * Return sub parameters for parameter at index `idx`.\n   * Note: The values are borrowed, thus you need to copy\n   * the values if you need to hold them in nonlocal scope.\n   */\n  public getSubParams(idx: number): Int32Array | null {\n    const start = this._subParamsIdx[idx] >> 8;\n    const end = this._subParamsIdx[idx] & 0xFF;\n    if (end - start > 0) {\n      return this._subParams.subarray(start, end);\n    }\n    return null;\n  }\n\n  /**\n   * Return all sub parameters as {idx: subparams} mapping.\n   * Note: The values are not borrowed.\n   */\n  public getSubParamsAll(): {[idx: number]: Int32Array} {\n    const result: {[idx: number]: Int32Array} = {};\n    for (let i = 0; i < this.length; ++i) {\n      const start = this._subParamsIdx[i] >> 8;\n      const end = this._subParamsIdx[i] & 0xFF;\n      if (end - start > 0) {\n        result[i] = this._subParams.slice(start, end);\n      }\n    }\n    return result;\n  }\n\n  /**\n   * Add a single digit value to current parameter.\n   * This is used by the parser to account digits on a char by char basis.\n   */\n  public addDigit(value: number): void {\n    let length;\n    if (this._rejectDigits\n      || !(length = this._digitIsSub ? this._subParamsLength : this.length)\n      || (this._digitIsSub && this._rejectSubDigits)\n    ) {\n      return;\n    }\n\n    const store = this._digitIsSub ? this._subParams : this.params;\n    const cur = store[length - 1];\n    store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value;\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser } from 'common/parser/Types';\nimport { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { IDisposable } from 'common/Types';\n\n\nexport class OscParser implements IOscParser {\n  private _state = OscState.START;\n  private _id = -1;\n  private _handlers: IHandlerCollection<IOscHandler> = Object.create(null);\n  private _handlerFb: OscFallbackHandlerType = () => { };\n\n  public addHandler(ident: number, handler: IOscHandler): IDisposable {\n    if (this._handlers[ident] === undefined) {\n      this._handlers[ident] = [];\n    }\n    const handlerList = this._handlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n  public setHandler(ident: number, handler: IOscHandler): void {\n    this._handlers[ident] = [handler];\n  }\n  public clearHandler(ident: number): void {\n    if (this._handlers[ident]) delete this._handlers[ident];\n  }\n  public setHandlerFallback(handler: OscFallbackHandlerType): void {\n    this._handlerFb = handler;\n  }\n\n  public dispose(): void {\n    this._handlers = Object.create(null);\n    this._handlerFb = () => {};\n  }\n\n  public reset(): void {\n    // cleanup handlers if payload was already sent\n    if (this._state === OscState.PAYLOAD) {\n      this.end(false);\n    }\n    this._id = -1;\n    this._state = OscState.START;\n  }\n\n  private _start(): void {\n    const handlers = this._handlers[this._id];\n    if (!handlers) {\n      this._handlerFb(this._id, 'START');\n    } else {\n      for (let j = handlers.length - 1; j >= 0; j--) {\n        handlers[j].start();\n      }\n    }\n  }\n\n  private _put(data: Uint32Array, start: number, end: number): void {\n    const handlers = this._handlers[this._id];\n    if (!handlers) {\n      this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end));\n    } else {\n      for (let j = handlers.length - 1; j >= 0; j--) {\n        handlers[j].put(data, start, end);\n      }\n    }\n  }\n\n  private _end(success: boolean): void {\n    // other than the old code we always have to call .end\n    // to keep the bubbling we use `success` to indicate\n    // whether a handler should execute\n    const handlers = this._handlers[this._id];\n    if (!handlers) {\n      this._handlerFb(this._id, 'END', success);\n    } else {\n      let j = handlers.length - 1;\n      for (; j >= 0; j--) {\n        if (handlers[j].end(success) !== false) {\n          break;\n        }\n      }\n      j--;\n      // cleanup left over handlers\n      for (; j >= 0; j--) {\n        handlers[j].end(false);\n      }\n    }\n  }\n\n  public start(): void {\n    // always reset leftover handlers\n    this.reset();\n    this._id = -1;\n    this._state = OscState.ID;\n  }\n\n  /**\n   * Put data to current OSC command.\n   * Expects the identifier of the OSC command in the form\n   * OSC id ; payload ST/BEL\n   * Payload chunks are not further processed and get\n   * directly passed to the handlers.\n   */\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (this._state === OscState.ABORT) {\n      return;\n    }\n    if (this._state === OscState.ID) {\n      while (start < end) {\n        const code = data[start++];\n        if (code === 0x3b) {\n          this._state = OscState.PAYLOAD;\n          this._start();\n          break;\n        }\n        if (code < 0x30 || 0x39 < code) {\n          this._state = OscState.ABORT;\n          return;\n        }\n        if (this._id === -1) {\n          this._id = 0;\n        }\n        this._id = this._id * 10 + code - 48;\n      }\n    }\n    if (this._state === OscState.PAYLOAD && end - start > 0) {\n      this._put(data, start, end);\n    }\n  }\n\n  /**\n   * Indicates end of an OSC command.\n   * Whether the OSC got aborted or finished normally\n   * is indicated by `success`.\n   */\n  public end(success: boolean): void {\n    if (this._state === OscState.START) {\n      return;\n    }\n    // do nothing if command was faulty\n    if (this._state !== OscState.ABORT) {\n      // if we are still in ID state and get an early end\n      // means that the command has no payload thus we still have\n      // to announce START and send END right after\n      if (this._state === OscState.ID) {\n        this._start();\n      }\n      this._end(success);\n    }\n    this._id = -1;\n    this._state = OscState.START;\n  }\n}\n\n/**\n * Convenient class to allow attaching string based handler functions\n * as OSC handlers.\n */\nexport class OscHandler implements IOscHandler {\n  private _data = '';\n  private _hitLimit: boolean = false;\n\n  constructor(private _handler: (data: string) => any) {}\n\n  public start(): void {\n    this._data = '';\n    this._hitLimit = false;\n  }\n\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (this._hitLimit) {\n      return;\n    }\n    this._data += utf32ToString(data, start, end);\n    if (this._data.length > PAYLOAD_LIMIT) {\n      this._data = '';\n      this._hitLimit = true;\n    }\n  }\n\n  public end(success: boolean): any {\n    let ret;\n    if (this._hitLimit) {\n      ret = false;\n    } else if (success) {\n      ret = this._handler(this._data);\n    }\n    this._data = '';\n    this._hitLimit = false;\n    return ret;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/**\n * Internal states of EscapeSequenceParser.\n */\nexport const enum ParserState {\n  GROUND = 0,\n  ESCAPE = 1,\n  ESCAPE_INTERMEDIATE = 2,\n  CSI_ENTRY = 3,\n  CSI_PARAM = 4,\n  CSI_INTERMEDIATE = 5,\n  CSI_IGNORE = 6,\n  SOS_PM_APC_STRING = 7,\n  OSC_STRING = 8,\n  DCS_ENTRY = 9,\n  DCS_PARAM = 10,\n  DCS_IGNORE = 11,\n  DCS_INTERMEDIATE = 12,\n  DCS_PASSTHROUGH = 13\n}\n\n/**\n* Internal actions of EscapeSequenceParser.\n*/\nexport const enum ParserAction {\n  IGNORE = 0,\n  ERROR = 1,\n  PRINT = 2,\n  EXECUTE = 3,\n  OSC_START = 4,\n  OSC_PUT = 5,\n  OSC_END = 6,\n  CSI_DISPATCH = 7,\n  PARAM = 8,\n  COLLECT = 9,\n  ESC_DISPATCH = 10,\n  CLEAR = 11,\n  DCS_HOOK = 12,\n  DCS_PUT = 13,\n  DCS_UNHOOK = 14\n}\n\n/**\n * Internal states of OscParser.\n */\nexport const enum OscState {\n  START = 0,\n  ID = 1,\n  PAYLOAD = 2,\n  ABORT = 3\n}\n\n// payload limit for OSC and DCS\nexport const PAYLOAD_LIMIT = 10000000;\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\nimport { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType } from 'common/parser/Types';\nimport { utf32ToString } from 'common/input/TextDecoder';\nimport { Params } from 'common/parser/Params';\nimport { PAYLOAD_LIMIT } from 'common/parser/Constants';\n\nconst EMPTY_HANDLERS: IDcsHandler[] = [];\n\nexport class DcsParser implements IDcsParser {\n  private _handlers: IHandlerCollection<IDcsHandler> = Object.create(null);\n  private _active: IDcsHandler[] = EMPTY_HANDLERS;\n  private _ident: number = 0;\n  private _handlerFb: DcsFallbackHandlerType = () => {};\n\n  public dispose(): void {\n    this._handlers = Object.create(null);\n    this._handlerFb = () => {};\n  }\n\n  public addHandler(ident: number, handler: IDcsHandler): IDisposable {\n    if (this._handlers[ident] === undefined) {\n      this._handlers[ident] = [];\n    }\n    const handlerList = this._handlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n\n  public setHandler(ident: number, handler: IDcsHandler): void {\n    this._handlers[ident] = [handler];\n  }\n\n  public clearHandler(ident: number): void {\n    if (this._handlers[ident]) delete this._handlers[ident];\n  }\n\n  public setHandlerFallback(handler: DcsFallbackHandlerType): void {\n    this._handlerFb = handler;\n  }\n\n  public reset(): void {\n    if (this._active.length) {\n      this.unhook(false);\n    }\n    this._active = EMPTY_HANDLERS;\n    this._ident = 0;\n  }\n\n  public hook(ident: number, params: IParams): void {\n    // always reset leftover handlers\n    this.reset();\n    this._ident = ident;\n    this._active = this._handlers[ident] || EMPTY_HANDLERS;\n    if (!this._active.length) {\n      this._handlerFb(this._ident, 'HOOK', params);\n    } else {\n      for (let j = this._active.length - 1; j >= 0; j--) {\n        this._active[j].hook(params);\n      }\n    }\n  }\n\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (!this._active.length) {\n      this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end));\n    } else {\n      for (let j = this._active.length - 1; j >= 0; j--) {\n        this._active[j].put(data, start, end);\n      }\n    }\n  }\n\n  public unhook(success: boolean): void {\n    if (!this._active.length) {\n      this._handlerFb(this._ident, 'UNHOOK', success);\n    } else {\n      let j = this._active.length - 1;\n      for (; j >= 0; j--) {\n        if (this._active[j].unhook(success) !== false) {\n          break;\n        }\n      }\n      j--;\n      // cleanup left over handlers\n      for (; j >= 0; j--) {\n        this._active[j].unhook(false);\n      }\n    }\n    this._active = EMPTY_HANDLERS;\n    this._ident = 0;\n  }\n}\n\n/**\n * Convenient class to create a DCS handler from a single callback function.\n * Note: The payload is currently limited to 50 MB (hardcoded).\n */\nexport class DcsHandler implements IDcsHandler {\n  private _data = '';\n  private _params: IParams | undefined;\n  private _hitLimit: boolean = false;\n\n  constructor(private _handler: (data: string, params: IParams) => any) {}\n\n  public hook(params: IParams): void {\n    this._params = params.clone();\n    this._data = '';\n    this._hitLimit = false;\n  }\n\n  public put(data: Uint32Array, start: number, end: number): void {\n    if (this._hitLimit) {\n      return;\n    }\n    this._data += utf32ToString(data, start, end);\n    if (this._data.length > PAYLOAD_LIMIT) {\n      this._data = '';\n      this._hitLimit = true;\n    }\n  }\n\n  public unhook(success: boolean): any {\n    let ret;\n    if (this._hitLimit) {\n      ret = false;\n    } else if (success) {\n      ret = this._handler(this._data, this._params ? this._params : new Params());\n    }\n    this._params = undefined;\n    this._data = '';\n    this._hitLimit = false;\n    return ret;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { generateConfig, configEquals } from 'browser/renderer/atlas/CharAtlasUtils';\nimport { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';\nimport { DynamicCharAtlas } from 'browser/renderer/atlas/DynamicCharAtlas';\nimport { ICharAtlasConfig } from 'browser/renderer/atlas/Types';\nimport { IColorSet } from 'browser/Types';\nimport { ITerminalOptions } from 'common/services/Services';\n\ninterface ICharAtlasCacheEntry {\n  atlas: BaseCharAtlas;\n  config: ICharAtlasConfig;\n  // N.B. This implementation potentially holds onto copies of the terminal forever, so\n  // this may cause memory leaks.\n  ownedBy: number[];\n}\n\nconst charAtlasCache: ICharAtlasCacheEntry[] = [];\n\n/**\n * Acquires a char atlas, either generating a new one or returning an existing\n * one that is in use by another terminal.\n */\nexport function acquireCharAtlas(\n  options: ITerminalOptions,\n  rendererId: number,\n  colors: IColorSet,\n  scaledCharWidth: number,\n  scaledCharHeight: number\n): BaseCharAtlas {\n  const newConfig = generateConfig(scaledCharWidth, scaledCharHeight, options, colors);\n\n  // Check to see if the renderer already owns this config\n  for (let i = 0; i < charAtlasCache.length; i++) {\n    const entry = charAtlasCache[i];\n    const ownedByIndex = entry.ownedBy.indexOf(rendererId);\n    if (ownedByIndex >= 0) {\n      if (configEquals(entry.config, newConfig)) {\n        return entry.atlas;\n      }\n      // The configs differ, release the renderer from the entry\n      if (entry.ownedBy.length === 1) {\n        entry.atlas.dispose();\n        charAtlasCache.splice(i, 1);\n      } else {\n        entry.ownedBy.splice(ownedByIndex, 1);\n      }\n      break;\n    }\n  }\n\n  // Try match a char atlas from the cache\n  for (let i = 0; i < charAtlasCache.length; i++) {\n    const entry = charAtlasCache[i];\n    if (configEquals(entry.config, newConfig)) {\n      // Add the renderer to the cache entry and return\n      entry.ownedBy.push(rendererId);\n      return entry.atlas;\n    }\n  }\n\n  const newEntry: ICharAtlasCacheEntry = {\n    atlas: new DynamicCharAtlas(\n      document,\n      newConfig\n    ),\n    config: newConfig,\n    ownedBy: [rendererId]\n  };\n  charAtlasCache.push(newEntry);\n  return newEntry.atlas;\n}\n\n/**\n * Removes a terminal reference from the cache, allowing its memory to be freed.\n */\nexport function removeTerminalFromCache(rendererId: number): void {\n  for (let i = 0; i < charAtlasCache.length; i++) {\n    const index = charAtlasCache[i].ownedBy.indexOf(rendererId);\n    if (index !== -1) {\n      if (charAtlasCache[i].ownedBy.length === 1) {\n        // Remove the cache entry if it's the only renderer\n        charAtlasCache[i].atlas.dispose();\n        charAtlasCache.splice(i, 1);\n      } else {\n        // Remove the reference from the cache entry\n        charAtlasCache[i].ownedBy.splice(index, 1);\n      }\n      break;\n    }\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharAtlasConfig } from 'browser/renderer/atlas/Types';\nimport { DEFAULT_COLOR } from 'common/buffer/Constants';\nimport { IColorSet, IPartialColorSet } from 'browser/Types';\nimport { ITerminalOptions } from 'common/services/Services';\n\nexport function generateConfig(scaledCharWidth: number, scaledCharHeight: number, options: ITerminalOptions, colors: IColorSet): ICharAtlasConfig {\n  // null out some fields that don't matter\n  const clonedColors = <IPartialColorSet>{\n    foreground: colors.foreground,\n    background: colors.background,\n    cursor: undefined,\n    cursorAccent: undefined,\n    selection: undefined,\n    // For the static char atlas, we only use the first 16 colors, but we need all 256 for the\n    // dynamic character atlas.\n    ansi: colors.ansi.slice(0, 16)\n  };\n  return {\n    devicePixelRatio: window.devicePixelRatio,\n    scaledCharWidth,\n    scaledCharHeight,\n    fontFamily: options.fontFamily,\n    fontSize: options.fontSize,\n    fontWeight: options.fontWeight,\n    fontWeightBold: options.fontWeightBold,\n    allowTransparency: options.allowTransparency,\n    colors: clonedColors\n  };\n}\n\nexport function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean {\n  for (let i = 0; i < a.colors.ansi.length; i++) {\n    if (a.colors.ansi[i].rgba !== b.colors.ansi[i].rgba) {\n      return false;\n    }\n  }\n  return a.devicePixelRatio === b.devicePixelRatio &&\n      a.fontFamily === b.fontFamily &&\n      a.fontSize === b.fontSize &&\n      a.fontWeight === b.fontWeight &&\n      a.fontWeightBold === b.fontWeightBold &&\n      a.allowTransparency === b.allowTransparency &&\n      a.scaledCharWidth === b.scaledCharWidth &&\n      a.scaledCharHeight === b.scaledCharHeight &&\n      a.colors.foreground === b.colors.foreground &&\n      a.colors.background === b.colors.background;\n}\n\nexport function is256Color(colorCode: number): boolean {\n  return colorCode < DEFAULT_COLOR;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IColorManager, IColor, IColorSet } from 'browser/Types';\nimport { ITheme } from 'common/services/Services';\n\nconst DEFAULT_FOREGROUND = fromHex('#ffffff');\nconst DEFAULT_BACKGROUND = fromHex('#000000');\nconst DEFAULT_CURSOR = fromHex('#ffffff');\nconst DEFAULT_CURSOR_ACCENT = fromHex('#000000');\nconst DEFAULT_SELECTION = {\n  css: 'rgba(255, 255, 255, 0.3)',\n  rgba: 0xFFFFFF77\n};\n\n// An IIFE to generate DEFAULT_ANSI_COLORS. Do not mutate DEFAULT_ANSI_COLORS, instead make a copy\n// and mutate that.\nexport const DEFAULT_ANSI_COLORS = (() => {\n  const colors = [\n    // dark:\n    fromHex('#2e3436'),\n    fromHex('#cc0000'),\n    fromHex('#4e9a06'),\n    fromHex('#c4a000'),\n    fromHex('#3465a4'),\n    fromHex('#75507b'),\n    fromHex('#06989a'),\n    fromHex('#d3d7cf'),\n    // bright:\n    fromHex('#555753'),\n    fromHex('#ef2929'),\n    fromHex('#8ae234'),\n    fromHex('#fce94f'),\n    fromHex('#729fcf'),\n    fromHex('#ad7fa8'),\n    fromHex('#34e2e2'),\n    fromHex('#eeeeec')\n  ];\n\n  // Fill in the remaining 240 ANSI colors.\n  // Generate colors (16-231)\n  const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];\n  for (let i = 0; i < 216; i++) {\n    const r = v[(i / 36) % 6 | 0];\n    const g = v[(i / 6) % 6 | 0];\n    const b = v[i % 6];\n    colors.push({\n      css: `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`,\n      // Use >>> 0 to force a conversion to an unsigned int\n      rgba: ((r << 24) | (g << 16) | (b << 8) | 0xFF) >>> 0\n    });\n  }\n\n  // Generate greys (232-255)\n  for (let i = 0; i < 24; i++) {\n    const c = 8 + i * 10;\n    const ch = toPaddedHex(c);\n    colors.push({\n      css: `#${ch}${ch}${ch}`,\n      rgba: ((c << 24) | (c << 16) | (c << 8) | 0xFF) >>> 0\n    });\n  }\n\n  return colors;\n})();\n\nfunction fromHex(css: string): IColor {\n  return {\n    css,\n    rgba: parseInt(css.slice(1), 16) << 8 | 0xFF\n  };\n}\n\nfunction toPaddedHex(c: number): string {\n  const s = c.toString(16);\n  return s.length < 2 ? '0' + s : s;\n}\n\n/**\n * Manages the source of truth for a terminal's colors.\n */\nexport class ColorManager implements IColorManager {\n  public colors: IColorSet;\n  private _ctx: CanvasRenderingContext2D;\n  private _litmusColor: CanvasGradient;\n\n  constructor(document: Document, public allowTransparency: boolean) {\n    const canvas = document.createElement('canvas');\n    canvas.width = 1;\n    canvas.height = 1;\n    const ctx = canvas.getContext('2d');\n    if (!ctx) {\n      throw new Error('Could not get rendering context');\n    }\n    this._ctx = ctx;\n    this._ctx.globalCompositeOperation = 'copy';\n    this._litmusColor = this._ctx.createLinearGradient(0, 0, 1, 1);\n    this.colors = {\n      foreground: DEFAULT_FOREGROUND,\n      background: DEFAULT_BACKGROUND,\n      cursor: DEFAULT_CURSOR,\n      cursorAccent: DEFAULT_CURSOR_ACCENT,\n      selection: DEFAULT_SELECTION,\n      ansi: DEFAULT_ANSI_COLORS.slice()\n    };\n  }\n\n  /**\n   * Sets the terminal's theme.\n   * @param theme The  theme to use. If a partial theme is provided then default\n   * colors will be used where colors are not defined.\n   */\n  public setTheme(theme: ITheme = {}): void {\n    this.colors.foreground = this._parseColor(theme.foreground, DEFAULT_FOREGROUND);\n    this.colors.background = this._parseColor(theme.background, DEFAULT_BACKGROUND);\n    this.colors.cursor = this._parseColor(theme.cursor, DEFAULT_CURSOR, true);\n    this.colors.cursorAccent = this._parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT, true);\n    this.colors.selection = this._parseColor(theme.selection, DEFAULT_SELECTION, true);\n    this.colors.ansi[0] = this._parseColor(theme.black, DEFAULT_ANSI_COLORS[0]);\n    this.colors.ansi[1] = this._parseColor(theme.red, DEFAULT_ANSI_COLORS[1]);\n    this.colors.ansi[2] = this._parseColor(theme.green, DEFAULT_ANSI_COLORS[2]);\n    this.colors.ansi[3] = this._parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]);\n    this.colors.ansi[4] = this._parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]);\n    this.colors.ansi[5] = this._parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]);\n    this.colors.ansi[6] = this._parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]);\n    this.colors.ansi[7] = this._parseColor(theme.white, DEFAULT_ANSI_COLORS[7]);\n    this.colors.ansi[8] = this._parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]);\n    this.colors.ansi[9] = this._parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]);\n    this.colors.ansi[10] = this._parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]);\n    this.colors.ansi[11] = this._parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]);\n    this.colors.ansi[12] = this._parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]);\n    this.colors.ansi[13] = this._parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]);\n    this.colors.ansi[14] = this._parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]);\n    this.colors.ansi[15] = this._parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]);\n  }\n\n  private _parseColor(\n    css: string | undefined,\n    fallback: IColor,\n    allowTransparency: boolean = this.allowTransparency\n  ): IColor {\n    if (css === undefined) {\n      return fallback;\n    }\n\n    // If parsing the value results in failure, then it must be ignored, and the attribute must\n    // retain its previous value.\n    // -- https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles\n    this._ctx.fillStyle = this._litmusColor;\n    this._ctx.fillStyle = css;\n    if (typeof this._ctx.fillStyle !== 'string') {\n      console.warn(`Color: ${css} is invalid using fallback ${fallback.css}`);\n      return fallback;\n    }\n\n    this._ctx.fillRect(0, 0, 1, 1);\n    const data = this._ctx.getImageData(0, 0, 1, 1).data;\n\n    if (!allowTransparency && data[3] !== 0xFF) {\n      // Ideally we'd just ignore the alpha channel, but...\n      //\n      // Browsers may not give back exactly the same RGB values we put in, because most/all\n      // convert the color to a pre-multiplied representation. getImageData converts that back to\n      // a un-premultipled representation, but the precision loss may make the RGB channels unuable\n      // on their own.\n      //\n      // E.g. In Chrome #12345610 turns into #10305010, and in the extreme case, 0xFFFFFF00 turns\n      // into 0x00000000.\n      //\n      // \"Note: Due to the lossy nature of converting to and from premultiplied alpha color values,\n      // pixels that have just been set using putImageData() might be returned to an equivalent\n      // getImageData() as different values.\"\n      // -- https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation\n      //\n      // So let's just use the fallback color in this case instead.\n      console.warn(\n        `Color: ${css} is using transparency, but allowTransparency is false. ` +\n        `Using fallback ${fallback.css}.`\n      );\n      return fallback;\n    }\n\n    return {\n      css,\n      rgba: (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0\n    };\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport function throwIfFalsy<T>(value: T | undefined | null): T {\n  if (!value) {\n    throw new Error('value must not be falsy');\n  }\n  return value;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine, ICellData, CharData } from 'common/Types';\nimport { ICharacterJoinerRegistry, ICharacterJoiner } from 'browser/renderer/Types';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { IBufferService } from 'common/services/Services';\n\nexport class JoinedCellData extends AttributeData implements ICellData {\n  private _width: number;\n  // .content carries no meaning for joined CellData, simply nullify it\n  // thus we have to overload all other .content accessors\n  public content: number = 0;\n  public fg: number;\n  public bg: number;\n  public combinedData: string = '';\n\n  constructor(firstCell: ICellData, chars: string, width: number) {\n    super();\n    this.fg = firstCell.fg;\n    this.bg = firstCell.bg;\n    this.combinedData = chars;\n    this._width = width;\n  }\n\n  public isCombined(): number {\n    // always mark joined cell data as combined\n    return Content.IS_COMBINED_MASK;\n  }\n\n  public getWidth(): number {\n    return this._width;\n  }\n\n  public getChars(): string {\n    return this.combinedData;\n  }\n\n  public getCode(): number {\n    // code always gets the highest possible fake codepoint (read as -1)\n    // this is needed as code is used by caches as identifier\n    return 0x1FFFFF;\n  }\n\n  public setFromCharData(value: CharData): void {\n    throw new Error('not implemented');\n  }\n\n  public getAsCharData(): CharData {\n    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];\n  }\n}\n\nexport class CharacterJoinerRegistry implements ICharacterJoinerRegistry {\n\n  private _characterJoiners: ICharacterJoiner[] = [];\n  private _nextCharacterJoinerId: number = 0;\n  private _workCell: CellData = new CellData();\n\n  constructor(private _bufferService: IBufferService) { }\n\n  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {\n    const joiner: ICharacterJoiner = {\n      id: this._nextCharacterJoinerId++,\n      handler\n    };\n\n    this._characterJoiners.push(joiner);\n    return joiner.id;\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): boolean {\n    for (let i = 0; i < this._characterJoiners.length; i++) {\n      if (this._characterJoiners[i].id === joinerId) {\n        this._characterJoiners.splice(i, 1);\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  public getJoinedCharacters(row: number): [number, number][] {\n    if (this._characterJoiners.length === 0) {\n      return [];\n    }\n\n    const line = this._bufferService.buffer.lines.get(row);\n    if (!line || line.length === 0) {\n      return [];\n    }\n\n    const ranges: [number, number][] = [];\n    const lineStr = line.translateToString(true);\n\n    // Because some cells can be represented by multiple javascript characters,\n    // we track the cell and the string indexes separately. This allows us to\n    // translate the string ranges we get from the joiners back into cell ranges\n    // for use when rendering\n    let rangeStartColumn = 0;\n    let currentStringIndex = 0;\n    let rangeStartStringIndex = 0;\n    let rangeAttrFG = line.getFg(0);\n    let rangeAttrBG = line.getBg(0);\n\n    for (let x = 0; x < line.getTrimmedLength(); x++) {\n      line.loadCell(x, this._workCell);\n\n      if (this._workCell.getWidth() === 0) {\n        // If this character is of width 0, skip it.\n        continue;\n      }\n\n      // End of range\n      if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {\n        // If we ended up with a sequence of more than one character,\n        // look for ranges to join.\n        if (x - rangeStartColumn > 1) {\n          const joinedRanges = this._getJoinedRanges(\n            lineStr,\n            rangeStartStringIndex,\n            currentStringIndex,\n            line,\n            rangeStartColumn\n          );\n          for (let i = 0; i < joinedRanges.length; i++) {\n            ranges.push(joinedRanges[i]);\n          }\n        }\n\n        // Reset our markers for a new range.\n        rangeStartColumn = x;\n        rangeStartStringIndex = currentStringIndex;\n        rangeAttrFG = this._workCell.fg;\n        rangeAttrBG = this._workCell.bg;\n      }\n\n      currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;\n    }\n\n    // Process any trailing ranges.\n    if (this._bufferService.cols - rangeStartColumn > 1) {\n      const joinedRanges = this._getJoinedRanges(\n        lineStr,\n        rangeStartStringIndex,\n        currentStringIndex,\n        line,\n        rangeStartColumn\n      );\n      for (let i = 0; i < joinedRanges.length; i++) {\n        ranges.push(joinedRanges[i]);\n      }\n    }\n\n    return ranges;\n  }\n\n  /**\n   * Given a segment of a line of text, find all ranges of text that should be\n   * joined in a single rendering unit. Ranges are internally converted to\n   * column ranges, rather than string ranges.\n   * @param line String representation of the full line of text\n   * @param startIndex Start position of the range to search in the string (inclusive)\n   * @param endIndex End position of the range to search in the string (exclusive)\n   */\n  private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {\n    const text = line.substring(startIndex, endIndex);\n    // At this point we already know that there is at least one joiner so\n    // we can just pull its value and assign it directly rather than\n    // merging it into an empty array, which incurs unnecessary writes.\n    const joinedRanges: [number, number][] = this._characterJoiners[0].handler(text);\n    for (let i = 1; i < this._characterJoiners.length; i++) {\n      // We merge any overlapping ranges across the different joiners\n      const joinerRanges = this._characterJoiners[i].handler(text);\n      for (let j = 0; j < joinerRanges.length; j++) {\n        CharacterJoinerRegistry._mergeRanges(joinedRanges, joinerRanges[j]);\n      }\n    }\n    this._stringRangesToCellRanges(joinedRanges, lineData, startCol);\n    return joinedRanges;\n  }\n\n  /**\n   * Modifies the provided ranges in-place to adjust for variations between\n   * string length and cell width so that the range represents a cell range,\n   * rather than the string range the joiner provides.\n   * @param ranges String ranges containing start (inclusive) and end (exclusive) index\n   * @param line Cell data for the relevant line in the terminal\n   * @param startCol Offset within the line to start from\n   */\n  private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {\n    let currentRangeIndex = 0;\n    let currentRangeStarted = false;\n    let currentStringIndex = 0;\n    let currentRange = ranges[currentRangeIndex];\n\n    // If we got through all of the ranges, stop searching\n    if (!currentRange) {\n      return;\n    }\n\n    for (let x = startCol; x < this._bufferService.cols; x++) {\n      const width = line.getWidth(x);\n      const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;\n\n      // We skip zero-width characters when creating the string to join the text\n      // so we do the same here\n      if (width === 0) {\n        continue;\n      }\n\n      // Adjust the start of the range\n      if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {\n        currentRange[0] = x;\n        currentRangeStarted = true;\n      }\n\n      // Adjust the end of the range\n      if (currentRange[1] <= currentStringIndex) {\n        currentRange[1] = x;\n\n        // We're finished with this range, so we move to the next one\n        currentRange = ranges[++currentRangeIndex];\n\n        // If there are no more ranges left, stop searching\n        if (!currentRange) {\n          break;\n        }\n\n        // Ranges can be on adjacent characters. Because the end index of the\n        // ranges are exclusive, this means that the index for the start of a\n        // range can be the same as the end index of the previous range. To\n        // account for the start of the next range, we check here just in case.\n        if (currentRange[0] <= currentStringIndex) {\n          currentRange[0] = x;\n          currentRangeStarted = true;\n        } else {\n          currentRangeStarted = false;\n        }\n      }\n\n      // Adjust the string index based on the character length to line up with\n      // the column adjustment\n      currentStringIndex += length;\n    }\n\n    // If there is still a range left at the end, it must extend all the way to\n    // the end of the line.\n    if (currentRange) {\n      currentRange[1] = this._bufferService.cols;\n    }\n  }\n\n  /**\n   * Merges the range defined by the provided start and end into the list of\n   * existing ranges. The merge is done in place on the existing range for\n   * performance and is also returned.\n   * @param ranges Existing range list\n   * @param newRange Tuple of two numbers representing the new range to merge in.\n   * @returns The ranges input with the new range merged in place\n   */\n  private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {\n    let inRange = false;\n    for (let i = 0; i < ranges.length; i++) {\n      const range = ranges[i];\n      if (!inRange) {\n        if (newRange[1] <= range[0]) {\n          // Case 1: New range is before the search range\n          ranges.splice(i, 0, newRange);\n          return ranges;\n        }\n\n        if (newRange[1] <= range[1]) {\n          // Case 2: New range is either wholly contained within the\n          // search range or overlaps with the front of it\n          range[0] = Math.min(newRange[0], range[0]);\n          return ranges;\n        }\n\n        if (newRange[0] < range[1]) {\n          // Case 3: New range either wholly contains the search range\n          // or overlaps with the end of it\n          range[0] = Math.min(newRange[0], range[0]);\n          inRange = true;\n        }\n\n        // Case 4: New range starts after the search range\n        continue;\n      } else {\n        if (newRange[1] <= range[0]) {\n          // Case 5: New range extends from previous range but doesn't\n          // reach the current one\n          ranges[i - 1][1] = newRange[1];\n          return ranges;\n        }\n\n        if (newRange[1] <= range[1]) {\n          // Case 6: New range extends from prvious range into the\n          // current range\n          ranges[i - 1][1] = Math.max(newRange[1], range[1]);\n          ranges.splice(i, 1);\n          return ranges;\n        }\n\n        // Case 7: New range extends from previous range past the\n        // end of the current range\n        ranges.splice(i, 1);\n        i--;\n      }\n    }\n\n    if (inRange) {\n      // Case 8: New range extends past the last existing range\n      ranges[ranges.length - 1][1] = newRange[1];\n    } else {\n      // Case 9: New range starts after the last existing range\n      ranges.push(newRange);\n    }\n\n    return ranges;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport function getCoordsRelativeToElement(event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {\n  const rect = element.getBoundingClientRect();\n  return [event.clientX - rect.left, event.clientY - rect.top];\n}\n\n/**\n * Gets coordinates within the terminal for a particular mouse event. The result\n * is returned as an array in the form [x, y] instead of an object as it's a\n * little faster and this function is used in some low level code.\n * @param event The mouse event.\n * @param element The terminal's container element.\n * @param colCount The number of columns in the terminal.\n * @param rowCount The number of rows n the terminal.\n * @param isSelection Whether the request is for the selection or not. This will\n * apply an offset to the x value such that the left half of the cell will\n * select that cell and the right half will select the next cell.\n */\nexport function getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, actualCellWidth: number, actualCellHeight: number, isSelection?: boolean): [number, number] | undefined {\n  // Coordinates cannot be measured if there are no valid\n  if (!hasValidCharSize) {\n    return undefined;\n  }\n\n  const coords = getCoordsRelativeToElement(event, element);\n  if (!coords) {\n    return undefined;\n  }\n\n  coords[0] = Math.ceil((coords[0] + (isSelection ? actualCellWidth / 2 : 0)) / actualCellWidth);\n  coords[1] = Math.ceil(coords[1] / actualCellHeight);\n\n  // Ensure coordinates are within the terminal viewport. Note that selections\n  // need an addition point of precision to cover the end point (as characters\n  // cover half of one char and half of the next).\n  coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));\n  coords[1] = Math.min(Math.max(coords[1], 1), rowCount);\n\n  return coords;\n}\n\n/**\n * Gets coordinates within the terminal for a particular mouse event, wrapping\n * them to the bounds of the terminal and adding 32 to both the x and y values\n * as expected by xterm.\n */\nexport function getRawByteCoords(coords: [number, number] | undefined): { x: number, y: number } | undefined {\n  if (!coords) {\n    return undefined;\n  }\n\n  // xterm sends raw bytes and starts at 32 (SP) for each.\n  return { x: coords[0] + 32, y: coords[1] + 32 };\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'common/Types';\n\n/**\n * Debounces calls to render terminal rows using animation frames.\n */\nexport class RenderDebouncer implements IDisposable {\n  private _rowStart: number | undefined;\n  private _rowEnd: number | undefined;\n  private _rowCount: number | undefined;\n  private _animationFrame: number | undefined;\n\n  constructor(\n    private _renderCallback: (start: number, end: number) => void\n  ) {\n  }\n\n  public dispose(): void {\n    if (this._animationFrame) {\n      window.cancelAnimationFrame(this._animationFrame);\n      this._animationFrame = undefined;\n    }\n  }\n\n  public refresh(rowStart: number, rowEnd: number, rowCount: number): void {\n    this._rowCount = rowCount;\n    // Get the min/max row start/end for the arg values\n    rowStart = rowStart !== undefined ? rowStart : 0;\n    rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;\n    // Set the properties to the updated values\n    this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;\n    this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;\n\n    if (this._animationFrame) {\n      return;\n    }\n\n    this._animationFrame = window.requestAnimationFrame(() => this._innerRefresh());\n  }\n\n  private _innerRefresh(): void {\n    // Make sure values are set\n    if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {\n      return;\n    }\n\n    // Clamp values\n    this._rowStart = Math.max(this._rowStart, 0);\n    this._rowEnd = Math.min(this._rowEnd, this._rowCount - 1);\n\n    // Run render callback\n    this._renderCallback(this._rowStart, this._rowEnd);\n\n    // Reset debouncer\n    this._rowStart = undefined;\n    this._rowEnd = undefined;\n    this._animationFrame = undefined;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'common/Lifecycle';\n\nexport type ScreenDprListener = (newDevicePixelRatio?: number, oldDevicePixelRatio?: number) => void;\n\n/**\n * The screen device pixel ratio monitor allows listening for when the\n * window.devicePixelRatio value changes. This is done not with polling but with\n * the use of window.matchMedia to watch media queries. When the event fires,\n * the listener will be reattached using a different media query to ensure that\n * any further changes will register.\n *\n * The listener should fire on both window zoom changes and switching to a\n * monitor with a different DPI.\n */\nexport class ScreenDprMonitor extends Disposable {\n  private _currentDevicePixelRatio: number = window.devicePixelRatio;\n  private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined;\n  private _listener: ScreenDprListener | undefined;\n  private _resolutionMediaMatchList: MediaQueryList | undefined;\n\n  public setListener(listener: ScreenDprListener): void {\n    if (this._listener) {\n      this.clearListener();\n    }\n    this._listener = listener;\n    this._outerListener = () => {\n      if (!this._listener) {\n        return;\n      }\n      this._listener(window.devicePixelRatio, this._currentDevicePixelRatio);\n      this._updateDpr();\n    };\n    this._updateDpr();\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this.clearListener();\n  }\n\n  private _updateDpr(): void {\n    if (!this._resolutionMediaMatchList || !this._outerListener) {\n      return;\n    }\n\n    // Clear listeners for old DPR\n    this._resolutionMediaMatchList.removeListener(this._outerListener);\n\n    // Add listeners for new DPR\n    this._currentDevicePixelRatio = window.devicePixelRatio;\n    this._resolutionMediaMatchList = window.matchMedia(`screen and (resolution: ${window.devicePixelRatio}dppx)`);\n    this._resolutionMediaMatchList.addListener(this._outerListener);\n  }\n\n  public clearListener(): void {\n    if (!this._resolutionMediaMatchList || !this._listener || !this._outerListener) {\n      return;\n    }\n    this._resolutionMediaMatchList.removeListener(this._outerListener);\n    this._resolutionMediaMatchList = undefined;\n    this._listener = undefined;\n    this._outerListener = undefined;\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n/*\n * A simple utility for cloning values\n */\nexport function clone<T>(val: T, depth: number = 5): T {\n  if (typeof val !== 'object') {\n    return val;\n  }\n\n  // If we're cloning an array, use an array as the base, otherwise use an object\n  const clonedObject: any = Array.isArray(val) ? [] : {};\n\n  for (const key in val) {\n    // Recursively clone eack item unless we're at the maximum depth\n    clonedObject[key] = depth <= 1 ? val[key] : (val[key] ? clone(val[key], depth - 1) : val[key]);\n  }\n\n  return clonedObject as T;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Terminal as ITerminalApi, ITerminalOptions, IMarker, IDisposable, ILinkMatcherOptions, ITheme, ILocalizableStrings, ITerminalAddon, ISelectionPosition, IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi, IParser, IFunctionIdentifier } from 'xterm';\nimport { ITerminal } from '../Types';\nimport { IBufferLine } from 'common/Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { Terminal as TerminalCore } from '../Terminal';\nimport * as Strings from '../browser/LocalizableStrings';\nimport { IEvent } from 'common/EventEmitter';\nimport { AddonManager } from './AddonManager';\nimport { IParams } from 'common/parser/Types';\n\nexport class Terminal implements ITerminalApi {\n  private _core: ITerminal;\n  private _addonManager: AddonManager;\n  private _parser: IParser;\n\n  constructor(options?: ITerminalOptions) {\n    this._core = new TerminalCore(options);\n    this._addonManager = new AddonManager();\n  }\n\n  public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }\n  public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }\n  public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }\n  public get onData(): IEvent<string> { return this._core.onData; }\n  public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }\n  public get onScroll(): IEvent<number> { return this._core.onScroll; }\n  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }\n  public get onRender(): IEvent<{ start: number, end: number }> { return this._core.onRender; }\n  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }\n\n  public get element(): HTMLElement | undefined { return this._core.element; }\n  public get parser(): IParser {\n    if (!this._parser) {\n      this._parser = new ParserApi(this._core);\n    }\n    return this._parser;\n  }\n  public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; }\n  public get rows(): number { return this._core.rows; }\n  public get cols(): number { return this._core.cols; }\n  public get buffer(): IBufferApi { return new BufferApiView(this._core.buffer); }\n  public get markers(): ReadonlyArray<IMarker> { return this._core.markers; }\n  public blur(): void {\n    this._core.blur();\n  }\n  public focus(): void {\n    this._core.focus();\n  }\n  public resize(columns: number, rows: number): void {\n    this._verifyIntegers(columns, rows);\n    this._core.resize(columns, rows);\n  }\n  public open(parent: HTMLElement): void {\n    this._core.open(parent);\n  }\n  public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void {\n    this._core.attachCustomKeyEventHandler(customKeyEventHandler);\n  }\n  public registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number {\n    return this._core.registerLinkMatcher(regex, handler, options);\n  }\n  public deregisterLinkMatcher(matcherId: number): void {\n    this._core.deregisterLinkMatcher(matcherId);\n  }\n  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {\n    return this._core.registerCharacterJoiner(handler);\n  }\n  public deregisterCharacterJoiner(joinerId: number): void {\n    this._core.deregisterCharacterJoiner(joinerId);\n  }\n  public addMarker(cursorYOffset: number): IMarker {\n    this._verifyIntegers(cursorYOffset);\n    return this._core.addMarker(cursorYOffset);\n  }\n  public hasSelection(): boolean {\n    return this._core.hasSelection();\n  }\n  public select(column: number, row: number, length: number): void {\n    this._verifyIntegers(column, row, length);\n    this._core.select(column, row, length);\n  }\n  public getSelection(): string {\n    return this._core.getSelection();\n  }\n  public getSelectionPosition(): ISelectionPosition | undefined {\n    return this._core.getSelectionPosition();\n  }\n  public clearSelection(): void {\n    this._core.clearSelection();\n  }\n  public selectAll(): void {\n    this._core.selectAll();\n  }\n  public selectLines(start: number, end: number): void {\n    this._verifyIntegers(start, end);\n    this._core.selectLines(start, end);\n  }\n  public dispose(): void {\n    this._addonManager.dispose();\n    this._core.dispose();\n  }\n  public scrollLines(amount: number): void {\n    this._verifyIntegers(amount);\n    this._core.scrollLines(amount);\n  }\n  public scrollPages(pageCount: number): void {\n    this._verifyIntegers(pageCount);\n    this._core.scrollPages(pageCount);\n  }\n  public scrollToTop(): void {\n    this._core.scrollToTop();\n  }\n  public scrollToBottom(): void {\n    this._core.scrollToBottom();\n  }\n  public scrollToLine(line: number): void {\n    this._verifyIntegers(line);\n    this._core.scrollToLine(line);\n  }\n  public clear(): void {\n    this._core.clear();\n  }\n  public write(data: string | Uint8Array, callback?: () => void): void {\n    this._core.write(data, callback);\n  }\n  public writeUtf8(data: Uint8Array, callback?: () => void): void {\n    this._core.write(data, callback);\n  }\n  public writeln(data: string | Uint8Array, callback?: () => void): void {\n    this._core.write(data);\n    this._core.write('\\r\\n', callback);\n  }\n  public paste(data: string): void {\n    this._core.paste(data);\n  }\n  public getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;\n  public getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell'): boolean;\n  public getOption(key: 'colors'): string[];\n  public getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;\n  public getOption(key: 'handler'): (data: string) => void;\n  public getOption(key: string): any;\n  public getOption(key: any): any {\n    return this._core.optionsService.getOption(key);\n  }\n  public setOption(key: 'bellSound' | 'fontFamily' | 'termName' | 'wordSeparator', value: string): void;\n  public setOption(key: 'fontWeight' | 'fontWeightBold', value: 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'): void;\n  public setOption(key: 'logLevel', value: 'debug' | 'info' | 'warn' | 'error' | 'off'): void;\n  public setOption(key: 'bellStyle', value: 'none' | 'visual' | 'sound' | 'both'): void;\n  public setOption(key: 'cursorStyle', value: 'block' | 'underline' | 'bar'): void;\n  public setOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell', value: boolean): void;\n  public setOption(key: 'colors', value: string[]): void;\n  public setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;\n  public setOption(key: 'handler', value: (data: string) => void): void;\n  public setOption(key: 'theme', value: ITheme): void;\n  public setOption(key: 'cols' | 'rows', value: number): void;\n  public setOption(key: string, value: any): void;\n  public setOption(key: any, value: any): void {\n    this._core.optionsService.setOption(key, value);\n  }\n  public refresh(start: number, end: number): void {\n    this._verifyIntegers(start, end);\n    this._core.refresh(start, end);\n  }\n  public reset(): void {\n    this._core.reset();\n  }\n  public loadAddon(addon: ITerminalAddon): void {\n    return this._addonManager.loadAddon(this, addon);\n  }\n  public static get strings(): ILocalizableStrings {\n    return Strings;\n  }\n\n  private _verifyIntegers(...values: number[]): void {\n    values.forEach(value => {\n      if (value === Infinity || isNaN(value) || value % 1 !== 0) {\n        throw new Error('This API only accepts integers');\n      }\n    });\n  }\n}\n\nclass BufferApiView implements IBufferApi {\n  constructor(private _buffer: IBuffer) {}\n\n  public get cursorY(): number { return this._buffer.y; }\n  public get cursorX(): number { return this._buffer.x; }\n  public get viewportY(): number { return this._buffer.ydisp; }\n  public get baseY(): number { return this._buffer.ybase; }\n  public get length(): number { return this._buffer.lines.length; }\n  public getLine(y: number): IBufferLineApi | undefined {\n    const line = this._buffer.lines.get(y);\n    if (!line) {\n      return undefined;\n    }\n    return new BufferLineApiView(line);\n  }\n}\n\nclass BufferLineApiView implements IBufferLineApi {\n  constructor(private _line: IBufferLine) {}\n\n  public get isWrapped(): boolean { return this._line.isWrapped; }\n  public getCell(x: number): IBufferCellApi | undefined {\n    if (x < 0 || x >= this._line.length) {\n      return undefined;\n    }\n    return new BufferCellApiView(this._line, x);\n  }\n  public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string {\n    return this._line.translateToString(trimRight, startColumn, endColumn);\n  }\n}\n\nclass BufferCellApiView implements IBufferCellApi {\n  constructor(private _line: IBufferLine, private _x: number) {}\n  public get char(): string { return this._line.getString(this._x); }\n  public get width(): number { return this._line.getWidth(this._x); }\n}\n\nclass ParserApi implements IParser {\n  constructor(private _core: ITerminal) {}\n\n  public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable {\n    return this._core.addCsiHandler(id, (params: IParams) => callback(params.toArray()));\n  }\n  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable {\n    return this._core.addDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray()));\n  }\n  public addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable {\n    return this._core.addEscHandler(id, handler);\n  }\n  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {\n    return this._core.addOscHandler(ident, callback);\n  }\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n *\n * Originally forked from (with the author's permission):\n *   Fabrice Bellard's javascript vt100 for jslinux:\n *   http://bellard.org/jslinux/\n *   Copyright (c) 2011 Fabrice Bellard\n *   The original design remains. The terminal itself\n *   has been extended to include xterm CSI codes, among\n *   other features.\n *\n * Terminal Emulation References:\n *   http://vt100.net/\n *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt\n *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.html\n *   http://invisible-island.net/vttest/\n *   http://www.inwap.com/pdp10/ansicode.txt\n *   http://linux.die.net/man/4/console_codes\n *   http://linux.die.net/man/7/urxvt\n */\n\nimport { IInputHandlingTerminal, ICompositionHelper, ITerminalOptions, ITerminal, IBrowser, CustomKeyEventHandler } from './Types';\nimport { IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { CompositionHelper } from 'browser/input/CompositionHelper';\nimport { Viewport } from 'browser/Viewport';\nimport { rightClickHandler, moveTextAreaUnderMouseCursor, handlePasteEvent, copyHandler, paste } from 'browser/Clipboard';\nimport { C0 } from 'common/data/EscapeSequences';\nimport { InputHandler } from './InputHandler';\nimport { Renderer } from './renderer/Renderer';\nimport { Linkifier } from 'browser/Linkifier';\nimport { SelectionService } from 'browser/services/SelectionService';\nimport * as Browser from 'common/Platform';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport * as Strings from 'browser/LocalizableStrings';\nimport { SoundService } from 'browser/services/SoundService';\nimport { MouseZoneManager } from 'browser/MouseZoneManager';\nimport { AccessibilityManager } from './AccessibilityManager';\nimport { ITheme, IMarker, IDisposable, ISelectionPosition } from 'xterm';\nimport { DomRenderer } from './renderer/dom/DomRenderer';\nimport { IKeyboardEvent, KeyboardResultType, ICharset, IBufferLine, IAttributeData, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';\nimport { evaluateKeyboardEvent } from 'common/input/Keyboard';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { applyWindowsMode } from './WindowsMode';\nimport { ColorManager } from 'browser/ColorManager';\nimport { RenderService } from 'browser/services/RenderService';\nimport { IOptionsService, IBufferService, ICoreMouseService, ICoreService, ILogService, IDirtyRowService, IInstantiationService } from 'common/services/Services';\nimport { OptionsService } from 'common/services/OptionsService';\nimport { ICharSizeService, IRenderService, IMouseService, ISelectionService, ISoundService } from 'browser/services/Services';\nimport { CharSizeService } from 'browser/services/CharSizeService';\nimport { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService';\nimport { Disposable } from 'common/Lifecycle';\nimport { IBufferSet, IBuffer } from 'common/buffer/Types';\nimport { Attributes } from 'common/buffer/Constants';\nimport { MouseService } from 'browser/services/MouseService';\nimport { IParams, IFunctionIdentifier } from 'common/parser/Types';\nimport { CoreService } from 'common/services/CoreService';\nimport { LogService } from 'common/services/LogService';\nimport { ILinkifier, IMouseZoneManager, LinkMatcherHandler, ILinkMatcherOptions, IViewport } from 'browser/Types';\nimport { DirtyRowService } from 'common/services/DirtyRowService';\nimport { InstantiationService } from 'common/services/InstantiationService';\nimport { CoreMouseService } from 'common/services/CoreMouseService';\nimport { WriteBuffer } from 'common/input/WriteBuffer';\n\n// Let it work inside Node.js for automated testing purposes.\nconst document = (typeof window !== 'undefined') ? window.document : null;\n\n\nexport class Terminal extends Disposable implements ITerminal, IDisposable, IInputHandlingTerminal {\n  public textarea: HTMLTextAreaElement;\n  public element: HTMLElement;\n  public screenElement: HTMLElement;\n\n  /**\n   * The HTMLElement that the terminal is created in, set by Terminal.open.\n   */\n  private _parent: HTMLElement | null;\n  private _document: Document;\n  private _viewportScrollArea: HTMLElement;\n  private _viewportElement: HTMLElement;\n  private _helperContainer: HTMLElement;\n  private _compositionView: HTMLElement;\n\n  private _visualBellTimer: number;\n\n  public browser: IBrowser = <any>Browser;\n\n  // TODO: We should remove options once components adopt optionsService\n  public get options(): ITerminalOptions { return this.optionsService.options; }\n\n  // TODO: This can be changed to an enum or boolean, 0 and 1 seem to be the only options\n  public cursorState: number;\n  public cursorHidden: boolean;\n\n  private _customKeyEventHandler: CustomKeyEventHandler;\n\n  // common services\n  private _bufferService: IBufferService;\n  private _coreService: ICoreService;\n  private _coreMouseService: ICoreMouseService;\n  private _dirtyRowService: IDirtyRowService;\n  private _instantiationService: IInstantiationService;\n  private _logService: ILogService;\n  public optionsService: IOptionsService;\n\n  // browser services\n  private _charSizeService: ICharSizeService;\n  private _mouseService: IMouseService;\n  private _renderService: IRenderService;\n  private _selectionService: ISelectionService;\n  private _soundService: ISoundService;\n\n  // modes\n  public applicationKeypad: boolean;\n  public originMode: boolean;\n  public insertMode: boolean;\n  public wraparoundMode: boolean; // defaults: xterm - true, vt100 - false\n  public bracketedPasteMode: boolean;\n\n  // charset\n  // The current charset\n  public charset: ICharset;\n  public gcharset: number;\n  public glevel: number;\n  public charsets: ICharset[];\n\n  // mouse properties\n  public mouseEvents: CoreMouseEventType = CoreMouseEventType.NONE;\n  public sendFocus: boolean;\n\n  // misc\n  public savedCols: number;\n\n  public curAttrData: IAttributeData;\n  private _eraseAttrData: IAttributeData;\n\n  public params: (string | number)[];\n  public currentParam: string | number;\n\n  // write buffer\n  private _writeBuffer: WriteBuffer;\n\n  // Store if user went browsing history in scrollback\n  private _userScrolling: boolean;\n\n  /**\n   * Records whether the keydown event has already been handled and triggered a data event, if so\n   * the keypress event should not trigger a data event but should still print to the textarea so\n   * screen readers will announce it.\n   */\n  private _keyDownHandled: boolean = false;\n\n  private _inputHandler: InputHandler;\n  public linkifier: ILinkifier;\n  public viewport: IViewport;\n  private _compositionHelper: ICompositionHelper;\n  private _mouseZoneManager: IMouseZoneManager;\n  private _accessibilityManager: AccessibilityManager;\n  private _colorManager: ColorManager;\n  private _theme: ITheme;\n  private _windowsMode: IDisposable | undefined;\n\n  // bufferline to clone/copy from for new blank lines\n  private _blankLine: IBufferLine = null;\n\n  public get cols(): number { return this._bufferService.cols; }\n  public get rows(): number { return this._bufferService.rows; }\n\n  private _onCursorMove = new EventEmitter<void>();\n  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }\n  private _onData = new EventEmitter<string>();\n  public get onData(): IEvent<string> { return this._onData.event; }\n  private _onKey = new EventEmitter<{ key: string, domEvent: KeyboardEvent }>();\n  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._onKey.event; }\n  private _onLineFeed = new EventEmitter<void>();\n  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }\n  private _onRender = new EventEmitter<{ start: number, end: number }>();\n  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }\n  private _onResize = new EventEmitter<{ cols: number, rows: number }>();\n  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._onResize.event; }\n  private _onScroll = new EventEmitter<number>();\n  public get onScroll(): IEvent<number> { return this._onScroll.event; }\n  private _onSelectionChange = new EventEmitter<void>();\n  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }\n  private _onTitleChange = new EventEmitter<string>();\n  public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; }\n\n  private _onFocus = new EventEmitter<void>();\n  public get onFocus(): IEvent<void> { return this._onFocus.event; }\n  private _onBlur = new EventEmitter<void>();\n  public get onBlur(): IEvent<void> { return this._onBlur.event; }\n  public onA11yCharEmitter = new EventEmitter<string>();\n  public get onA11yChar(): IEvent<string> { return this.onA11yCharEmitter.event; }\n  public onA11yTabEmitter = new EventEmitter<number>();\n  public get onA11yTab(): IEvent<number> { return this.onA11yTabEmitter.event; }\n\n  /**\n   * Creates a new `Terminal` object.\n   *\n   * @param options An object containing a set of options, the available options are:\n   *   - `cursorBlink` (boolean): Whether the terminal cursor blinks\n   *   - `cols` (number): The number of columns of the terminal (horizontal size)\n   *   - `rows` (number): The number of rows of the terminal (vertical size)\n   *\n   * @public\n   * @class Xterm Xterm\n   * @alias module:xterm/src/xterm\n   */\n  constructor(\n    options: ITerminalOptions = {}\n  ) {\n    super();\n\n    // Setup and initialize common services\n    this._instantiationService = new InstantiationService();\n    this.optionsService = new OptionsService(options);\n    this._instantiationService.setService(IOptionsService, this.optionsService);\n    this._bufferService = this._instantiationService.createInstance(BufferService);\n    this._instantiationService.setService(IBufferService, this._bufferService);\n    this._logService = this._instantiationService.createInstance(LogService);\n    this._instantiationService.setService(ILogService, this._logService);\n    this._coreService = this._instantiationService.createInstance(CoreService, () => this.scrollToBottom());\n    this._instantiationService.setService(ICoreService, this._coreService);\n    this._coreService.onData(e => this._onData.fire(e));\n    this._coreMouseService = this._instantiationService.createInstance(CoreMouseService);\n    this._instantiationService.setService(ICoreMouseService, this._coreMouseService);\n    this._dirtyRowService = this._instantiationService.createInstance(DirtyRowService);\n    this._instantiationService.setService(IDirtyRowService, this._dirtyRowService);\n\n    this._setupOptionsListeners();\n    this._setup();\n\n    this._writeBuffer = new WriteBuffer(data => this._inputHandler.parse(data));\n  }\n\n  public dispose(): void {\n    if (this._isDisposed) {\n      return;\n    }\n    super.dispose();\n    if (this._windowsMode) {\n      this._windowsMode.dispose();\n      this._windowsMode = undefined;\n    }\n    if (this._renderService) {\n      this._renderService.dispose();\n    }\n    this._customKeyEventHandler = null;\n    this.write = () => {};\n    if (this.element && this.element.parentNode) {\n      this.element.parentNode.removeChild(this.element);\n    }\n  }\n\n  private _setup(): void {\n    this._parent = document ? document.body : null;\n\n    this.cursorState = 0;\n    this.cursorHidden = false;\n    this._customKeyEventHandler = null;\n\n    // modes\n    this.applicationKeypad = false;\n    this.originMode = false;\n    this.insertMode = false;\n    this.wraparoundMode = true; // defaults: xterm - true, vt100 - false\n    this.bracketedPasteMode = false;\n\n    // charset\n    this.charset = null;\n    this.gcharset = null;\n    this.glevel = 0;\n    // TODO: Can this be just []?\n    this.charsets = [null];\n\n    this.curAttrData = DEFAULT_ATTR_DATA.clone();\n    this._eraseAttrData = DEFAULT_ATTR_DATA.clone();\n\n    this.params = [];\n    this.currentParam = 0;\n\n    this._userScrolling = false;\n\n    // Register input handler and refire/handle events\n    this._inputHandler = new InputHandler(this, this._bufferService, this._coreService, this._dirtyRowService, this._logService, this.optionsService, this._coreMouseService);\n    this._inputHandler.onCursorMove(() => this._onCursorMove.fire());\n    this._inputHandler.onLineFeed(() => this._onLineFeed.fire());\n    this.register(this._inputHandler);\n\n    this.linkifier = this.linkifier || new Linkifier(this._bufferService, this._logService);\n\n    if (this.options.windowsMode) {\n      this._windowsMode = applyWindowsMode(this);\n    }\n  }\n\n  /**\n   * Convenience property to active buffer.\n   */\n  public get buffer(): IBuffer {\n    return this.buffers.active;\n  }\n\n  public get buffers(): IBufferSet {\n    return this._bufferService.buffers;\n  }\n\n  /**\n   * back_color_erase feature for xterm.\n   */\n  public eraseAttrData(): IAttributeData {\n    this._eraseAttrData.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);\n    this._eraseAttrData.bg |= this.curAttrData.bg & ~0xFC000000;\n    return this._eraseAttrData;\n  }\n\n  /**\n   * Focus the terminal. Delegates focus handling to the terminal's DOM element.\n   */\n  public focus(): void {\n    if (this.textarea) {\n      this.textarea.focus({ preventScroll: true });\n    }\n  }\n\n  public get isFocused(): boolean {\n    return document.activeElement === this.textarea && document.hasFocus();\n  }\n\n  private _setupOptionsListeners(): void {\n    // TODO: These listeners should be owned by individual components\n    this.optionsService.onOptionChange(key => {\n      switch (key) {\n        case 'fontFamily':\n        case 'fontSize':\n          // When the font changes the size of the cells may change which requires a renderer clear\n          if (this._renderService) {\n            this._renderService.clear();\n          }\n          if (this._charSizeService) {\n            this._charSizeService.measure();\n          }\n          break;\n        case 'drawBoldTextInBrightColors':\n        case 'letterSpacing':\n        case 'lineHeight':\n        case 'fontWeight':\n        case 'fontWeightBold':\n          // When the font changes the size of the cells may change which requires a renderer clear\n          if (this._renderService) {\n            this._renderService.clear();\n            this._renderService.onResize(this.cols, this.rows);\n            this.refresh(0, this.rows - 1);\n          }\n          break;\n        case 'rendererType':\n          if (this._renderService) {\n            this._renderService.setRenderer(this._createRenderer());\n            this._renderService.onResize(this.cols, this.rows);\n          }\n          break;\n        case 'scrollback':\n          this.buffers.resize(this.cols, this.rows);\n          if (this.viewport) {\n            this.viewport.syncScrollArea();\n          }\n          break;\n        case 'screenReaderMode':\n          if (this.optionsService.options.screenReaderMode) {\n            if (!this._accessibilityManager && this._renderService) {\n              this._accessibilityManager = new AccessibilityManager(this, this._renderService);\n            }\n          } else {\n            if (this._accessibilityManager) {\n              this._accessibilityManager.dispose();\n              this._accessibilityManager = null;\n            }\n          }\n          break;\n        case 'tabStopWidth': this.buffers.setupTabStops(); break;\n        case 'theme':\n          this._setTheme(this.optionsService.options.theme);\n          break;\n        case 'windowsMode':\n          if (this.optionsService.options.windowsMode) {\n            if (!this._windowsMode) {\n              this._windowsMode = applyWindowsMode(this);\n            }\n          } else {\n            if (this._windowsMode) {\n              this._windowsMode.dispose();\n              this._windowsMode = undefined;\n            }\n          }\n          break;\n      }\n    });\n  }\n\n  /**\n   * Binds the desired focus behavior on a given terminal object.\n   */\n  private _onTextAreaFocus(ev: KeyboardEvent): void {\n    if (this.sendFocus) {\n      this._coreService.triggerDataEvent(C0.ESC + '[I');\n    }\n    this.updateCursorStyle(ev);\n    this.element.classList.add('focus');\n    this.showCursor();\n    this._onFocus.fire();\n  }\n\n  /**\n   * Blur the terminal, calling the blur function on the terminal's underlying\n   * textarea.\n   */\n  public blur(): void {\n    return this.textarea.blur();\n  }\n\n  /**\n   * Binds the desired blur behavior on a given terminal object.\n   */\n  private _onTextAreaBlur(): void {\n    // Text can safely be removed on blur. Doing it earlier could interfere with\n    // screen readers reading it out.\n    this.textarea.value = '';\n    this.refresh(this.buffer.y, this.buffer.y);\n    if (this.sendFocus) {\n      this._coreService.triggerDataEvent(C0.ESC + '[O');\n    }\n    this.element.classList.remove('focus');\n    this._onBlur.fire();\n  }\n\n  /**\n   * Initialize default behavior\n   */\n  private _initGlobal(): void {\n    this._bindKeys();\n\n    // Bind clipboard functionality\n    this.register(addDisposableDomListener(this.element, 'copy', (event: ClipboardEvent) => {\n      // If mouse events are active it means the selection manager is disabled and\n      // copy should be handled by the host program.\n      if (!this.hasSelection()) {\n        return;\n      }\n      copyHandler(event, this._selectionService);\n    }));\n    const pasteHandlerWrapper = (event: ClipboardEvent) => handlePasteEvent(event, this.textarea, this.bracketedPasteMode, this._coreService);\n    this.register(addDisposableDomListener(this.textarea, 'paste', pasteHandlerWrapper));\n    this.register(addDisposableDomListener(this.element, 'paste', pasteHandlerWrapper));\n\n    // Handle right click context menus\n    if (Browser.isFirefox) {\n      // Firefox doesn't appear to fire the contextmenu event on right click\n      this.register(addDisposableDomListener(this.element, 'mousedown', (event: MouseEvent) => {\n        if (event.button === 2) {\n          rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);\n        }\n      }));\n    } else {\n      this.register(addDisposableDomListener(this.element, 'contextmenu', (event: MouseEvent) => {\n        rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);\n      }));\n    }\n\n    // Move the textarea under the cursor when middle clicking on Linux to ensure\n    // middle click to paste selection works. This only appears to work in Chrome\n    // at the time is writing.\n    if (Browser.isLinux) {\n      // Use auxclick event over mousedown the latter doesn't seem to work. Note\n      // that the regular click event doesn't fire for the middle mouse button.\n      this.register(addDisposableDomListener(this.element, 'auxclick', (event: MouseEvent) => {\n        if (event.button === 1) {\n          moveTextAreaUnderMouseCursor(event, this.textarea, this.screenElement);\n        }\n      }));\n    }\n  }\n\n  /**\n   * Apply key handling to the terminal\n   */\n  private _bindKeys(): void {\n    this.register(addDisposableDomListener(this.textarea, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));\n    this.register(addDisposableDomListener(this.textarea, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));\n    this.register(addDisposableDomListener(this.textarea, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));\n    this.register(addDisposableDomListener(this.textarea, 'compositionstart', () => this._compositionHelper.compositionstart()));\n    this.register(addDisposableDomListener(this.textarea, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper.compositionupdate(e)));\n    this.register(addDisposableDomListener(this.textarea, 'compositionend', () => this._compositionHelper.compositionend()));\n    this.register(this.onRender(() => this._compositionHelper.updateCompositionElements()));\n    this.register(this.onRender(e => this._queueLinkification(e.start, e.end)));\n  }\n\n  /**\n   * Opens the terminal within an element.\n   *\n   * @param parent The element to create the terminal within.\n   */\n  public open(parent: HTMLElement): void {\n    this._parent = parent || this._parent;\n\n    if (!this._parent) {\n      throw new Error('Terminal requires a parent element.');\n    }\n\n    if (!document.body.contains(parent)) {\n      this._logService.warn('Terminal.open was called on an element that was not attached to the DOM');\n    }\n\n    this._document = this._parent.ownerDocument;\n\n    // Create main element container\n    this.element = this._document.createElement('div');\n    this.element.dir = 'ltr';   // xterm.css assumes LTR\n    this.element.classList.add('terminal');\n    this.element.classList.add('xterm');\n    this.element.setAttribute('tabindex', '0');\n    this._parent.appendChild(this.element);\n\n    // Performance: Use a document fragment to build the terminal\n    // viewport and helper elements detached from the DOM\n    const fragment = document.createDocumentFragment();\n    this._viewportElement = document.createElement('div');\n    this._viewportElement.classList.add('xterm-viewport');\n    fragment.appendChild(this._viewportElement);\n    this._viewportScrollArea = document.createElement('div');\n    this._viewportScrollArea.classList.add('xterm-scroll-area');\n    this._viewportElement.appendChild(this._viewportScrollArea);\n\n    this.screenElement = document.createElement('div');\n    this.screenElement.classList.add('xterm-screen');\n    // Create the container that will hold helpers like the textarea for\n    // capturing DOM Events. Then produce the helpers.\n    this._helperContainer = document.createElement('div');\n    this._helperContainer.classList.add('xterm-helpers');\n    this.screenElement.appendChild(this._helperContainer);\n    fragment.appendChild(this.screenElement);\n\n    this.textarea = document.createElement('textarea');\n    this.textarea.classList.add('xterm-helper-textarea');\n    this.textarea.setAttribute('aria-label', Strings.promptLabel);\n    this.textarea.setAttribute('aria-multiline', 'false');\n    this.textarea.setAttribute('autocorrect', 'off');\n    this.textarea.setAttribute('autocapitalize', 'off');\n    this.textarea.setAttribute('spellcheck', 'false');\n    this.textarea.tabIndex = 0;\n    this.register(addDisposableDomListener(this.textarea, 'focus', (ev: KeyboardEvent) => this._onTextAreaFocus(ev)));\n    this.register(addDisposableDomListener(this.textarea, 'blur', () => this._onTextAreaBlur()));\n    this._helperContainer.appendChild(this.textarea);\n\n    this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);\n    this._instantiationService.setService(ICharSizeService, this._charSizeService);\n\n    this._compositionView = document.createElement('div');\n    this._compositionView.classList.add('composition-view');\n    this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);\n    this._helperContainer.appendChild(this._compositionView);\n\n    // Performance: Add viewport and helper elements from the fragment\n    this.element.appendChild(fragment);\n\n    this._theme = this.options.theme || this._theme;\n    this.options.theme = undefined;\n    this._colorManager = new ColorManager(document, this.options.allowTransparency);\n    this._colorManager.setTheme(this._theme);\n\n    const renderer = this._createRenderer();\n    this._renderService = this._instantiationService.createInstance(RenderService, renderer, this.rows, this.screenElement);\n    this._instantiationService.setService(IRenderService, this._renderService);\n    this._renderService.onRender(e => this._onRender.fire(e));\n    this.onResize(e => this._renderService.resize(e.cols, e.rows));\n\n    this._soundService = this._instantiationService.createInstance(SoundService);\n    this._instantiationService.setService(ISoundService, this._soundService);\n    this._mouseService = this._instantiationService.createInstance(MouseService);\n    this._instantiationService.setService(IMouseService, this._mouseService);\n\n    this.viewport = this._instantiationService.createInstance(Viewport,\n      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),\n      this._viewportElement,\n      this._viewportScrollArea\n    );\n    this.viewport.onThemeChange(this._colorManager.colors);\n    this.register(this.viewport);\n\n    this.register(this.onCursorMove(() => this._renderService.onCursorMove()));\n    this.register(this.onResize(() => this._renderService.onResize(this.cols, this.rows)));\n    this.register(this.onBlur(() => this._renderService.onBlur()));\n    this.register(this.onFocus(() => this._renderService.onFocus()));\n    this.register(this._renderService.onDimensionsChange(() => this.viewport.syncScrollArea()));\n\n    this._selectionService = this._instantiationService.createInstance(SelectionService,\n      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),\n      this.element,\n      this.screenElement);\n    this._instantiationService.setService(ISelectionService, this._selectionService);\n    this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));\n    this.register(this._selectionService.onRedrawRequest(e => this._renderService.onSelectionChanged(e.start, e.end, e.columnSelectMode)));\n    this.register(this._selectionService.onLinuxMouseSelection(text => {\n      // If there's a new selection, put it into the textarea, focus and select it\n      // in order to register it as a selection on the OS. This event is fired\n      // only on Linux to enable middle click to paste selection.\n      this.textarea.value = text;\n      this.textarea.focus();\n      this.textarea.select();\n    }));\n    this.register(this.onScroll(() => {\n      this.viewport.syncScrollArea();\n      this._selectionService.refresh();\n    }));\n    this.register(addDisposableDomListener(this._viewportElement, 'scroll', () => this._selectionService.refresh()));\n\n    this._mouseZoneManager = this._instantiationService.createInstance(MouseZoneManager, this.element, this.screenElement);\n    this.register(this._mouseZoneManager);\n    this.register(this.onScroll(() => this._mouseZoneManager.clearAll()));\n    this.linkifier.attachToDom(this.element, this._mouseZoneManager);\n\n    // This event listener must be registered aftre MouseZoneManager is created\n    this.register(addDisposableDomListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService.onMouseDown(e)));\n\n    // apply mouse event classes set by escape codes before terminal was attached\n    if (this.mouseEvents) {\n      this._selectionService.disable();\n      this.element.classList.add('enable-mouse-events');\n    } else {\n      this._selectionService.enable();\n    }\n\n    if (this.options.screenReaderMode) {\n      // Note that this must be done *after* the renderer is created in order to\n      // ensure the correct order of the dprchange event\n      this._accessibilityManager = new AccessibilityManager(this, this._renderService);\n    }\n\n    // Measure the character size\n    this._charSizeService.measure();\n\n    // Setup loop that draws to screen\n    this.refresh(0, this.rows - 1);\n\n    // Initialize global actions that need to be taken on the document.\n    this._initGlobal();\n\n    // Listen for mouse events and translate\n    // them into terminal mouse protocols.\n    this.bindMouse();\n  }\n\n  private _createRenderer(): IRenderer {\n    switch (this.options.rendererType) {\n      case 'canvas': return new Renderer(this._colorManager.colors, this, this._bufferService, this._charSizeService, this.optionsService);\n      case 'dom': return new DomRenderer(this, this._colorManager.colors, this._charSizeService, this.optionsService);\n      default: throw new Error(`Unrecognized rendererType \"${this.options.rendererType}\"`);\n    }\n  }\n\n  /**\n   * Sets the theme on the renderer. The renderer must have been initialized.\n   * @param theme The theme to set.\n   */\n  private _setTheme(theme: ITheme): void {\n    this._theme = theme;\n    if (this._colorManager) {\n      this._colorManager.setTheme(theme);\n    }\n    if (this._renderService) {\n      this._renderService.setColors(this._colorManager.colors);\n    }\n    if (this.viewport) {\n      this.viewport.onThemeChange(this._colorManager.colors);\n    }\n  }\n\n  /**\n   * Bind certain mouse events to the terminal.\n   * By default only 3 button + wheel up/down is ativated. For higher buttons\n   * no mouse report will be created. Typically the standard actions will be active.\n   *\n   * There are several reasons not to enable support for higher buttons/wheel:\n   * - Button 4 and 5 are typically used for history back and forward navigation,\n   *   there is no straight forward way to supress/intercept those standard actions.\n   * - Support for higher buttons does not work in some platform/browser combinations.\n   * - Left/right wheel was not tested.\n   * - Emulators vary in mouse button support, typically only 3 buttons and\n   *   wheel up/down work reliable.\n   *\n   * TODO: Move mouse event code into its own file.\n   */\n  public bindMouse(): void {\n    const self = this;\n    const el = this.element;\n\n    // send event to CoreMouseService\n    function sendEvent(ev: MouseEvent | WheelEvent): boolean {\n      let pos;\n\n      // get mouse coordinates\n      pos = self._mouseService.getRawByteCoords(ev, self.screenElement, self.cols, self.rows);\n      if (!pos) {\n        return false;\n      }\n\n      let but: CoreMouseButton;\n      let action: CoreMouseAction;\n      switch ((<any>ev).overrideType || ev.type) {\n        case 'mousemove':\n          action = CoreMouseAction.MOVE;\n          if (ev.buttons === undefined) {\n            // buttons is not supported on macOS, try to get a value from button instead\n            but = CoreMouseButton.NONE;\n            if (ev.button !== undefined) {\n              but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n            }\n          } else {\n            // according to MDN buttons only reports up to button 5 (AUX2)\n            but = ev.buttons & 1 ? CoreMouseButton.LEFT :\n                  ev.buttons & 4 ? CoreMouseButton.MIDDLE :\n                  ev.buttons & 2 ? CoreMouseButton.RIGHT :\n                  CoreMouseButton.NONE; // fallback to NONE\n          }\n          break;\n        case 'mouseup':\n          action = CoreMouseAction.UP;\n          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n          break;\n        case 'mousedown':\n          action = CoreMouseAction.DOWN;\n          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;\n          break;\n        case 'wheel':\n          // only UP/DOWN wheel events are respected\n          if ((ev as WheelEvent).deltaY !== 0) {\n            action = (ev as WheelEvent).deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;\n          }\n          but = CoreMouseButton.WHEEL;\n          break;\n        default:\n          // dont handle other event types by accident\n          return false;\n      }\n\n      // exit if we cannot determine valid button/action values\n      // do nothing for higher buttons than wheel\n      if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {\n        return false;\n      }\n\n      return self._coreMouseService.triggerMouseEvent({\n        col: pos.x - 33, // FIXME: why -33 here?\n        row: pos.y - 33,\n        button: but,\n        action,\n        ctrl: ev.ctrlKey,\n        alt: ev.altKey,\n        shift: ev.shiftKey\n      });\n    }\n\n    /**\n     * Event listener state handling.\n     * We listen to the onProtocolChange event of CoreMouseService and put\n     * requested listeners in `requestedEvents`. With this the listeners\n     * have all bits to do the event listener juggling.\n     * Note: 'mousedown' currently is \"always on\" and not managed\n     * by onProtocolChange.\n     */\n    const requestedEvents: {[key: string]: ((ev: Event) => void) | null} = {\n      mouseup: null,\n      wheel: null,\n      mousedrag: null,\n      mousemove: null\n    };\n    const eventListeners: {[key: string]: (ev: Event) => void} = {\n      mouseup: (ev: MouseEvent) => {\n        sendEvent(ev);\n        if (!ev.buttons) {\n          // if no other button is held remove global handlers\n          this._document.removeEventListener('mouseup', requestedEvents.mouseup);\n          if (requestedEvents.mousedrag) {\n            this._document.removeEventListener('mousemove', requestedEvents.mousedrag);\n          }\n        }\n        return this.cancel(ev);\n      },\n      wheel: (ev: WheelEvent) => {\n        sendEvent(ev);\n        ev.preventDefault();\n        return this.cancel(ev);\n      },\n      mousedrag: (ev: MouseEvent) => {\n        // deal only with move while a button is held\n        if (ev.buttons) {\n          sendEvent(ev);\n        }\n      },\n      mousemove: (ev: MouseEvent) => {\n        // deal only with move without any button\n        if (!ev.buttons) {\n          sendEvent(ev);\n        }\n      }\n    };\n    this._coreMouseService.onProtocolChange(events => {\n      // apply global changes on events\n      this.mouseEvents = events;\n      if (events) {\n        if (this.optionsService.options.logLevel === 'debug') {\n          this._logService.debug('Binding to mouse events:', this._coreMouseService.explainEvents(events));\n        }\n        this.element.classList.add('enable-mouse-events');\n        this._selectionService.disable();\n      } else {\n        this._logService.debug('Unbinding from mouse events.');\n        this.element.classList.remove('enable-mouse-events');\n        this._selectionService.enable();\n      }\n\n      // add/remove handlers from requestedEvents\n\n      if (!(events & CoreMouseEventType.MOVE)) {\n        el.removeEventListener('mousemove', requestedEvents.mousemove);\n        requestedEvents.mousemove = null;\n      } else if (!requestedEvents.mousemove) {\n        el.addEventListener('mousemove', eventListeners.mousemove);\n        requestedEvents.mousemove = eventListeners.mousemove;\n      }\n\n      if (!(events & CoreMouseEventType.WHEEL)) {\n        el.removeEventListener('wheel', requestedEvents.wheel);\n        requestedEvents.wheel = null;\n      } else if (!requestedEvents.wheel) {\n        el.addEventListener('wheel', eventListeners.wheel);\n        requestedEvents.wheel = eventListeners.wheel;\n      }\n\n      if (!(events & CoreMouseEventType.UP)) {\n        this._document.removeEventListener('mouseup', requestedEvents.mouseup);\n        requestedEvents.mouseup = null;\n      } else if (!requestedEvents.mouseup) {\n        requestedEvents.mouseup = eventListeners.mouseup;\n      }\n\n      if (!(events & CoreMouseEventType.DRAG)) {\n        this._document.removeEventListener('mousemove', requestedEvents.mousedrag);\n        requestedEvents.mousedrag = null;\n      } else if (!requestedEvents.mousedrag) {\n        requestedEvents.mousedrag = eventListeners.mousedrag;\n      }\n    });\n    // force initial onProtocolChange so we dont miss early mouse requests\n    this._coreMouseService.activeProtocol = this._coreMouseService.activeProtocol;\n\n    /**\n     * \"Always on\" event listeners.\n     */\n    this.register(addDisposableDomListener(el, 'mousedown', (ev: MouseEvent) => {\n      ev.preventDefault();\n      this.focus();\n\n      // Don't send the mouse button to the pty if mouse events are disabled or\n      // if the selection manager is having selection forced (ie. a modifier is\n      // held).\n      if (!this.mouseEvents || this._selectionService.shouldForceSelection(ev)) {\n        return;\n      }\n\n      sendEvent(ev);\n\n      // Register additional global handlers which should keep reporting outside\n      // of the terminal element.\n      // Note: Other emulators also do this for 'mousedown' while a button\n      // is held, we currently limit 'mousedown' to the terminal only.\n      if (requestedEvents.mouseup) {\n        this._document.addEventListener('mouseup', requestedEvents.mouseup);\n      }\n      if (requestedEvents.mousedrag) {\n        this._document.addEventListener('mousemove', requestedEvents.mousedrag);\n      }\n\n      return this.cancel(ev);\n    }));\n\n    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {\n      if (!requestedEvents.wheel) {\n        // Convert wheel events into up/down events when the buffer does not have scrollback, this\n        // enables scrolling in apps hosted in the alt buffer such as vim or tmux.\n        if (!this.buffer.hasScrollback) {\n          const amount = this.viewport.getLinesScrolled(ev);\n\n          // Do nothing if there's no vertical scroll\n          if (amount === 0) {\n            return;\n          }\n\n          // Construct and send sequences\n          const sequence = C0.ESC + (this._coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + ( ev.deltaY < 0 ? 'A' : 'B');\n          let data = '';\n          for (let i = 0; i < Math.abs(amount); i++) {\n            data += sequence;\n          }\n          this._coreService.triggerDataEvent(data, true);\n        }\n        return;\n      }\n    }));\n\n    // allow wheel scrolling in\n    // the shell for example\n    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {\n      if (requestedEvents.wheel) return;\n      if (!this.viewport.onWheel(ev)) {\n        return this.cancel(ev);\n      }\n    }));\n\n    this.register(addDisposableDomListener(el, 'touchstart', (ev: TouchEvent) => {\n      if (this.mouseEvents) return;\n      this.viewport.onTouchStart(ev);\n      return this.cancel(ev);\n    }));\n\n    this.register(addDisposableDomListener(el, 'touchmove', (ev: TouchEvent) => {\n      if (this.mouseEvents) return;\n      if (!this.viewport.onTouchMove(ev)) {\n        return this.cancel(ev);\n      }\n    }));\n  }\n\n\n  /**\n   * Tells the renderer to refresh terminal content between two rows (inclusive) at the next\n   * opportunity.\n   * @param start The row to start from (between 0 and this.rows - 1).\n   * @param end The row to end at (between start and this.rows - 1).\n   */\n  public refresh(start: number, end: number): void {\n    if (this._renderService) {\n      this._renderService.refreshRows(start, end);\n    }\n  }\n\n  /**\n   * Queues linkification for the specified rows.\n   * @param start The row to start from (between 0 and this.rows - 1).\n   * @param end The row to end at (between start and this.rows - 1).\n   */\n  private _queueLinkification(start: number, end: number): void {\n    if (this.linkifier) {\n      this.linkifier.linkifyRows(start, end);\n    }\n  }\n\n  /**\n   * Change the cursor style for different selection modes\n   */\n  public updateCursorStyle(ev: KeyboardEvent): void {\n    if (this._selectionService && this._selectionService.shouldColumnSelect(ev)) {\n      this.element.classList.add('column-select');\n    } else {\n      this.element.classList.remove('column-select');\n    }\n  }\n\n  /**\n   * Display the cursor element\n   */\n  public showCursor(): void {\n    if (!this.cursorState) {\n      this.cursorState = 1;\n      this.refresh(this.buffer.y, this.buffer.y);\n    }\n  }\n\n  /**\n   * Scroll the terminal down 1 row, creating a blank line.\n   * @param isWrapped Whether the new line is wrapped from the previous line.\n   */\n  public scroll(isWrapped: boolean = false): void {\n    let newLine: IBufferLine;\n    newLine = this._blankLine;\n    const eraseAttr = this.eraseAttrData();\n    if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) {\n      newLine = this.buffer.getBlankLine(eraseAttr, isWrapped);\n      this._blankLine = newLine;\n    }\n    newLine.isWrapped = isWrapped;\n\n    const topRow = this.buffer.ybase + this.buffer.scrollTop;\n    const bottomRow = this.buffer.ybase + this.buffer.scrollBottom;\n\n    if (this.buffer.scrollTop === 0) {\n      // Determine whether the buffer is going to be trimmed after insertion.\n      const willBufferBeTrimmed = this.buffer.lines.isFull;\n\n      // Insert the line using the fastest method\n      if (bottomRow === this.buffer.lines.length - 1) {\n        if (willBufferBeTrimmed) {\n          this.buffer.lines.recycle().copyFrom(newLine);\n        } else {\n          this.buffer.lines.push(newLine.clone());\n        }\n      } else {\n        this.buffer.lines.splice(bottomRow + 1, 0, newLine.clone());\n      }\n\n      // Only adjust ybase and ydisp when the buffer is not trimmed\n      if (!willBufferBeTrimmed) {\n        this.buffer.ybase++;\n        // Only scroll the ydisp with ybase if the user has not scrolled up\n        if (!this._userScrolling) {\n          this.buffer.ydisp++;\n        }\n      } else {\n        // When the buffer is full and the user has scrolled up, keep the text\n        // stable unless ydisp is right at the top\n        if (this._userScrolling) {\n          this.buffer.ydisp = Math.max(this.buffer.ydisp - 1, 0);\n        }\n      }\n    } else {\n      // scrollTop is non-zero which means no line will be going to the\n      // scrollback, instead we can just shift them in-place.\n      const scrollRegionHeight = bottomRow - topRow + 1/*as it's zero-based*/;\n      this.buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);\n      this.buffer.lines.set(bottomRow, newLine.clone());\n    }\n\n    // Move the viewport to the bottom of the buffer unless the user is\n    // scrolling.\n    if (!this._userScrolling) {\n      this.buffer.ydisp = this.buffer.ybase;\n    }\n\n    // Flag rows that need updating\n    this._dirtyRowService.markRangeDirty(this.buffer.scrollTop, this.buffer.scrollBottom);\n\n    this._onScroll.fire(this.buffer.ydisp);\n  }\n\n  /**\n   * Scroll the display of the terminal\n   * @param disp The number of lines to scroll down (negative scroll up).\n   * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used\n   * to avoid unwanted events being handled by the viewport when the event was triggered from the\n   * viewport originally.\n   */\n  public scrollLines(disp: number, suppressScrollEvent?: boolean): void {\n    if (disp < 0) {\n      if (this.buffer.ydisp === 0) {\n        return;\n      }\n      this._userScrolling = true;\n    } else if (disp + this.buffer.ydisp >= this.buffer.ybase) {\n      this._userScrolling = false;\n    }\n\n    const oldYdisp = this.buffer.ydisp;\n    this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0);\n\n    // No change occurred, don't trigger scroll/refresh\n    if (oldYdisp === this.buffer.ydisp) {\n      return;\n    }\n\n    if (!suppressScrollEvent) {\n      this._onScroll.fire(this.buffer.ydisp);\n    }\n\n    this.refresh(0, this.rows - 1);\n  }\n\n  /**\n   * Scroll the display of the terminal by a number of pages.\n   * @param pageCount The number of pages to scroll (negative scrolls up).\n   */\n  public scrollPages(pageCount: number): void {\n    this.scrollLines(pageCount * (this.rows - 1));\n  }\n\n  /**\n   * Scrolls the display of the terminal to the top.\n   */\n  public scrollToTop(): void {\n    this.scrollLines(-this.buffer.ydisp);\n  }\n\n  /**\n   * Scrolls the display of the terminal to the bottom.\n   */\n  public scrollToBottom(): void {\n    this.scrollLines(this.buffer.ybase - this.buffer.ydisp);\n  }\n\n  public scrollToLine(line: number): void {\n    const scrollAmount = line - this.buffer.ydisp;\n    if (scrollAmount !== 0) {\n      this.scrollLines(scrollAmount);\n    }\n  }\n\n  public paste(data: string): void {\n    paste(data, this.textarea, this.bracketedPasteMode, this._coreService);\n  }\n\n  /**\n   * Attaches a custom key event handler which is run before keys are processed,\n   * giving consumers of xterm.js ultimate control as to what keys should be\n   * processed by the terminal and what keys should not.\n   * @param customKeyEventHandler The custom KeyboardEvent handler to attach.\n   * This is a function that takes a KeyboardEvent, allowing consumers to stop\n   * propagation and/or prevent the default action. The function returns whether\n   * the event should be processed by xterm.js.\n   */\n  public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {\n    this._customKeyEventHandler = customKeyEventHandler;\n  }\n\n  /** Add handler for ESC escape sequence. See xterm.d.ts for details. */\n  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {\n    return this._inputHandler.addEscHandler(id, callback);\n  }\n\n  /** Add handler for DCS escape sequence. See xterm.d.ts for details. */\n  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {\n    return this._inputHandler.addDcsHandler(id, callback);\n  }\n\n  /** Add handler for CSI escape sequence. See xterm.d.ts for details. */\n  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {\n    return this._inputHandler.addCsiHandler(id, callback);\n  }\n  /** Add handler for OSC escape sequence. See xterm.d.ts for details. */\n  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {\n    return this._inputHandler.addOscHandler(ident, callback);\n  }\n\n  /**\n   * Registers a link matcher, allowing custom link patterns to be matched and\n   * handled.\n   * @param regex The regular expression to search for, specifically\n   * this searches the textContent of the rows. You will want to use \\s to match\n   * a space ' ' character for example.\n   * @param handler The callback when the link is called.\n   * @param options Options for the link matcher.\n   * @return The ID of the new matcher, this can be used to deregister.\n   */\n  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: ILinkMatcherOptions): number {\n    const matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);\n    this.refresh(0, this.rows - 1);\n    return matcherId;\n  }\n\n  /**\n   * Deregisters a link matcher if it has been registered.\n   * @param matcherId The link matcher's ID (returned after register)\n   */\n  public deregisterLinkMatcher(matcherId: number): void {\n    if (this.linkifier.deregisterLinkMatcher(matcherId)) {\n      this.refresh(0, this.rows - 1);\n    }\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n    const joinerId = this._renderService.registerCharacterJoiner(handler);\n    this.refresh(0, this.rows - 1);\n    return joinerId;\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): void {\n    if (this._renderService.deregisterCharacterJoiner(joinerId)) {\n      this.refresh(0, this.rows - 1);\n    }\n  }\n\n  public get markers(): IMarker[] {\n    return this.buffer.markers;\n  }\n\n  public addMarker(cursorYOffset: number): IMarker {\n    // Disallow markers on the alt buffer\n    if (this.buffer !== this.buffers.normal) {\n      return;\n    }\n\n    return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);\n  }\n\n  /**\n   * Gets whether the terminal has an active selection.\n   */\n  public hasSelection(): boolean {\n    return this._selectionService ? this._selectionService.hasSelection : false;\n  }\n\n  /**\n   * Selects text within the terminal.\n   * @param column The column the selection starts at..\n   * @param row The row the selection starts at.\n   * @param length The length of the selection.\n   */\n  public select(column: number, row: number, length: number): void {\n    this._selectionService.setSelection(column, row, length);\n  }\n\n  /**\n   * Gets the terminal's current selection, this is useful for implementing copy\n   * behavior outside of xterm.js.\n   */\n  public getSelection(): string {\n    return this._selectionService ? this._selectionService.selectionText : '';\n  }\n\n  public getSelectionPosition(): ISelectionPosition | undefined {\n    if (!this._selectionService.hasSelection) {\n      return undefined;\n    }\n\n    return {\n      startColumn: this._selectionService.selectionStart[0],\n      startRow: this._selectionService.selectionStart[1],\n      endColumn: this._selectionService.selectionEnd[0],\n      endRow: this._selectionService.selectionEnd[1]\n    };\n  }\n\n  /**\n   * Clears the current terminal selection.\n   */\n  public clearSelection(): void {\n    if (this._selectionService) {\n      this._selectionService.clearSelection();\n    }\n  }\n\n  /**\n   * Selects all text within the terminal.\n   */\n  public selectAll(): void {\n    if (this._selectionService) {\n      this._selectionService.selectAll();\n    }\n  }\n\n  public selectLines(start: number, end: number): void {\n    if (this._selectionService) {\n      this._selectionService.selectLines(start, end);\n    }\n  }\n\n  /**\n   * Handle a keydown event\n   * Key Resources:\n   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n   * @param ev The keydown event to be handled.\n   */\n  protected _keyDown(event: KeyboardEvent): boolean {\n    this._keyDownHandled = false;\n\n    if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {\n      return false;\n    }\n\n    if (!this._compositionHelper.keydown(event)) {\n      if (this.buffer.ybase !== this.buffer.ydisp) {\n        this.scrollToBottom();\n      }\n      return false;\n    }\n\n    const result = evaluateKeyboardEvent(event, this._coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);\n\n    this.updateCursorStyle(event);\n\n    if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {\n      const scrollCount = this.rows - 1;\n      this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);\n      return this.cancel(event, true);\n    }\n\n    if (result.type === KeyboardResultType.SELECT_ALL) {\n      this.selectAll();\n    }\n\n    if (this._isThirdLevelShift(this.browser, event)) {\n      return true;\n    }\n\n    if (result.cancel) {\n      // The event is canceled at the end already, is this necessary?\n      this.cancel(event, true);\n    }\n\n    if (!result.key) {\n      return true;\n    }\n\n    // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers\n    // will announce deleted characters. This will not work 100% of the time but it should cover\n    // most scenarios.\n    if (result.key === C0.ETX || result.key === C0.CR) {\n      this.textarea.value = '';\n    }\n\n    this._onKey.fire({ key: result.key, domEvent: event });\n    this.showCursor();\n    this._coreService.triggerDataEvent(result.key, true);\n\n    // Cancel events when not in screen reader mode so events don't get bubbled up and handled by\n    // other listeners. When screen reader mode is enabled, this could cause issues if the event\n    // is handled at a higher level, this is a compromise in order to echo keys to the screen\n    // reader.\n    if (!this.optionsService.options.screenReaderMode) {\n      return this.cancel(event, true);\n    }\n\n    this._keyDownHandled = true;\n  }\n\n  private _isThirdLevelShift(browser: IBrowser, ev: IKeyboardEvent): boolean {\n    const thirdLevelKey =\n        (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||\n        (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);\n\n    if (ev.type === 'keypress') {\n      return thirdLevelKey;\n    }\n\n    // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)\n    return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);\n  }\n\n  /**\n   * Set the G level of the terminal\n   * @param g\n   */\n  public setgLevel(g: number): void {\n    this.glevel = g;\n    this.charset = this.charsets[g];\n  }\n\n  /**\n   * Set the charset for the given G level of the terminal\n   * @param g\n   * @param charset\n   */\n  public setgCharset(g: number, charset: ICharset): void {\n    this.charsets[g] = charset;\n    if (this.glevel === g) {\n      this.charset = charset;\n    }\n  }\n\n  protected _keyUp(ev: KeyboardEvent): void {\n    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n      return;\n    }\n\n    if (!wasModifierKeyOnlyEvent(ev)) {\n      this.focus();\n    }\n\n    this.updateCursorStyle(ev);\n  }\n\n  /**\n   * Handle a keypress event.\n   * Key Resources:\n   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent\n   * @param ev The keypress event to be handled.\n   */\n  protected _keyPress(ev: KeyboardEvent): boolean {\n    let key;\n\n    if (this._keyDownHandled) {\n      return false;\n    }\n\n    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {\n      return false;\n    }\n\n    this.cancel(ev);\n\n    if (ev.charCode) {\n      key = ev.charCode;\n    } else if (ev.which === null || ev.which === undefined) {\n      key = ev.keyCode;\n    } else if (ev.which !== 0 && ev.charCode !== 0) {\n      key = ev.which;\n    } else {\n      return false;\n    }\n\n    if (!key || (\n      (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)\n    )) {\n      return false;\n    }\n\n    key = String.fromCharCode(key);\n\n    this._onKey.fire({ key, domEvent: ev });\n    this.showCursor();\n    this._coreService.triggerDataEvent(key, true);\n\n    return true;\n  }\n\n  /**\n   * Ring the bell.\n   * Note: We could do sweet things with webaudio here\n   */\n  public bell(): void {\n    if (this._soundBell()) {\n      this._soundService.playBellSound();\n    }\n\n    if (this._visualBell()) {\n      this.element.classList.add('visual-bell-active');\n      clearTimeout(this._visualBellTimer);\n      this._visualBellTimer = window.setTimeout(() => {\n        this.element.classList.remove('visual-bell-active');\n      }, 200);\n    }\n  }\n\n  /**\n   * Resizes the terminal.\n   *\n   * @param x The number of columns to resize to.\n   * @param y The number of rows to resize to.\n   */\n  public resize(x: number, y: number): void {\n    if (isNaN(x) || isNaN(y)) {\n      return;\n    }\n\n    if (x === this.cols && y === this.rows) {\n      // Check if we still need to measure the char size (fixes #785).\n      if (this._charSizeService && !this._charSizeService.hasValidSize) {\n        this._charSizeService.measure();\n      }\n      return;\n    }\n\n    if (x < MINIMUM_COLS) x = MINIMUM_COLS;\n    if (y < MINIMUM_ROWS) y = MINIMUM_ROWS;\n\n    this.buffers.resize(x, y);\n\n    this._bufferService.resize(x, y);\n    this.buffers.setupTabStops(this.cols);\n\n    if (this._charSizeService) {\n      this._charSizeService.measure();\n    }\n\n    // Sync the scroll area to make sure scroll events don't fire and scroll the viewport to an\n    // invalid location\n    this.viewport.syncScrollArea(true);\n\n    this.refresh(0, this.rows - 1);\n    this._onResize.fire({ cols: x, rows: y });\n  }\n\n  /**\n   * Clear the entire buffer, making the prompt line the new first line.\n   */\n  public clear(): void {\n    if (this.buffer.ybase === 0 && this.buffer.y === 0) {\n      // Don't clear if it's already clear\n      return;\n    }\n    this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y));\n    this.buffer.lines.length = 1;\n    this.buffer.ydisp = 0;\n    this.buffer.ybase = 0;\n    this.buffer.y = 0;\n    for (let i = 1; i < this.rows; i++) {\n      this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));\n    }\n    this.refresh(0, this.rows - 1);\n    this._onScroll.fire(this.buffer.ydisp);\n  }\n\n  /**\n   * Evaluate if the current terminal is the given argument.\n   * @param term The terminal name to evaluate\n   */\n  public is(term: string): boolean {\n    return (this.options.termName + '').indexOf(term) === 0;\n  }\n\n  /**\n   * Emit the data event and populate the given data.\n   * @param data The data to populate in the event.\n   */\n  // public handler(data: string): void {\n  //   // Prevents all events to pty process if stdin is disabled\n  //   if (this.options.disableStdin) {\n  //     return;\n  //   }\n\n  //   // Clear the selection if the selection manager is available and has an active selection\n  //   if (this.selectionService && this.selectionService.hasSelection) {\n  //     this.selectionService.clearSelection();\n  //   }\n\n  //   // Input is being sent to the terminal, the terminal should focus the prompt.\n  //   if (this.buffer.ybase !== this.buffer.ydisp) {\n  //     this.scrollToBottom();\n  //   }\n  //   this._onData.fire(data);\n  // }\n\n  /**\n   * Emit the 'title' event and populate the given title.\n   * @param title The title to populate in the event.\n   */\n  public handleTitle(title: string): void {\n    this._onTitleChange.fire(title);\n  }\n\n  /**\n   * Reset terminal.\n   * Note: Calling this directly from JS is synchronous but does not clear\n   * input buffers and does not reset the parser, thus the terminal will\n   * continue to apply pending input data.\n   * If you need in band reset (synchronous with input data) consider\n   * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).\n   */\n  public reset(): void {\n    /**\n     * Since _setup handles a full terminal creation, we have to carry forward\n     * a few things that should not reset.\n     */\n    this.options.rows = this.rows;\n    this.options.cols = this.cols;\n    const customKeyEventHandler = this._customKeyEventHandler;\n    const inputHandler = this._inputHandler;\n    const cursorState = this.cursorState;\n    const userScrolling = this._userScrolling;\n\n    this._setup();\n    this._bufferService.reset();\n    this._coreService.reset();\n    this._coreMouseService.reset();\n    if (this._selectionService) {\n      this._selectionService.reset();\n    }\n\n    // reattach\n    this._customKeyEventHandler = customKeyEventHandler;\n    this._inputHandler = inputHandler;\n    this.cursorState = cursorState;\n    this._userScrolling = userScrolling;\n\n    // do a full screen refresh\n    this.refresh(0, this.rows - 1);\n    if (this.viewport) {\n      this.viewport.syncScrollArea();\n    }\n  }\n\n  // TODO: Remove cancel function and cancelEvents option\n  public cancel(ev: Event, force?: boolean): boolean {\n    if (!this.options.cancelEvents && !force) {\n      return;\n    }\n    ev.preventDefault();\n    ev.stopPropagation();\n    return false;\n  }\n\n  private _visualBell(): boolean {\n    return false;\n    // return this.options.bellStyle === 'visual' ||\n    //     this.options.bellStyle === 'both';\n  }\n\n  private _soundBell(): boolean {\n    return this.options.bellStyle === 'sound';\n    // return this.options.bellStyle === 'sound' ||\n    //     this.options.bellStyle === 'both';\n  }\n\n  public write(data: string | Uint8Array, callback?: () => void): void {\n    this._writeBuffer.write(data, callback);\n  }\n\n  public writeSync(data: string | Uint8Array): void {\n    this._writeBuffer.writeSync(data);\n  }\n}\n\n/**\n * Helpers\n */\n\nfunction wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {\n  return ev.keyCode === 16 || // Shift\n    ev.keyCode === 17 || // Ctrl\n    ev.keyCode === 18; // Alt\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharSizeService } from 'browser/services/Services';\nimport { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';\n\ninterface IPosition {\n  start: number;\n  end: number;\n}\n\n/**\n * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend\n * events, displaying the in-progress composition to the UI and forwarding the final composition\n * to the handler.\n */\nexport class CompositionHelper {\n  /**\n   * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or\n   * IME. This variable determines whether the compositionText should be displayed on the UI.\n   */\n  private _isComposing: boolean;\n\n  /**\n   * The position within the input textarea's value of the current composition.\n   */\n  private _compositionPosition: IPosition;\n\n  /**\n   * Whether a composition is in the process of being sent, setting this to false will cancel any\n   * in-progress composition.\n   */\n  private _isSendingComposition: boolean;\n\n  constructor(\n    private readonly _textarea: HTMLTextAreaElement,\n    private readonly _compositionView: HTMLElement,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @IOptionsService private readonly _optionsService: IOptionsService,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService,\n    @ICoreService private readonly _coreService: ICoreService\n  ) {\n    this._isComposing = false;\n    this._isSendingComposition = false;\n    this._compositionPosition = { start: 0, end: 0 };\n  }\n\n  /**\n   * Handles the compositionstart event, activating the composition view.\n   */\n  public compositionstart(): void {\n    this._isComposing = true;\n    this._compositionPosition.start = this._textarea.value.length;\n    this._compositionView.textContent = '';\n    this._compositionView.classList.add('active');\n  }\n\n  /**\n   * Handles the compositionupdate event, updating the composition view.\n   * @param ev The event.\n   */\n  public compositionupdate(ev: CompositionEvent): void {\n    this._compositionView.textContent = ev.data;\n    this.updateCompositionElements();\n    setTimeout(() => {\n      this._compositionPosition.end = this._textarea.value.length;\n    }, 0);\n  }\n\n  /**\n   * Handles the compositionend event, hiding the composition view and sending the composition to\n   * the handler.\n   */\n  public compositionend(): void {\n    this._finalizeComposition(true);\n  }\n\n  /**\n   * Handles the keydown event, routing any necessary events to the CompositionHelper functions.\n   * @param ev The keydown event.\n   * @return Whether the Terminal should continue processing the keydown event.\n   */\n  public keydown(ev: KeyboardEvent): boolean {\n    if (this._isComposing || this._isSendingComposition) {\n      if (ev.keyCode === 229) {\n        // Continue composing if the keyCode is the \"composition character\"\n        return false;\n      } else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {\n        // Continue composing if the keyCode is a modifier key\n        return false;\n      }\n      // Finish composition immediately. This is mainly here for the case where enter is\n      // pressed and the handler needs to be triggered before the command is executed.\n      this._finalizeComposition(false);\n    }\n\n    if (ev.keyCode === 229) {\n      // If the \"composition character\" is used but gets to this point it means a non-composition\n      // character (eg. numbers and punctuation) was pressed when the IME was active.\n      this._handleAnyTextareaChanges();\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Finalizes the composition, resuming regular input actions. This is called when a composition\n   * is ending.\n   * @param waitForPropagation Whether to wait for events to propagate before sending\n   *   the input. This should be false if a non-composition keystroke is entered before the\n   *   compositionend event is triggered, such as enter, so that the composition is sent before\n   *   the command is executed.\n   */\n  private _finalizeComposition(waitForPropagation: boolean): void {\n    this._compositionView.classList.remove('active');\n    this._isComposing = false;\n    this._clearTextareaPosition();\n\n    if (!waitForPropagation) {\n      // Cancel any delayed composition send requests and send the input immediately.\n      this._isSendingComposition = false;\n      const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);\n      this._coreService.triggerDataEvent(input, true);\n    } else {\n      // Make a deep copy of the composition position here as a new compositionstart event may\n      // fire before the setTimeout executes.\n      const currentCompositionPosition = {\n        start: this._compositionPosition.start,\n        end: this._compositionPosition.end\n      };\n\n      // Since composition* events happen before the changes take place in the textarea on most\n      // browsers, use a setTimeout with 0ms time to allow the native compositionend event to\n      // complete. This ensures the correct character is retrieved.\n      // This solution was used because:\n      // - The compositionend event's data property is unreliable, at least on Chromium\n      // - The last compositionupdate event's data property does not always accurately describe\n      //   the character, a counter example being Korean where an ending consonsant can move to\n      //   the following character if the following input is a vowel.\n      this._isSendingComposition = true;\n      setTimeout(() => {\n        // Ensure that the input has not already been sent\n        if (this._isSendingComposition) {\n          this._isSendingComposition = false;\n          let input;\n          if (this._isComposing) {\n            // Use the end position to get the string if a new composition has started.\n            input = this._textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);\n          } else {\n            // Don't use the end position here in order to pick up any characters after the\n            // composition has finished, for example when typing a non-composition character\n            // (eg. 2) after a composition character.\n            input = this._textarea.value.substring(currentCompositionPosition.start);\n          }\n          this._coreService.triggerDataEvent(input, true);\n        }\n      }, 0);\n    }\n  }\n\n  /**\n   * Apply any changes made to the textarea after the current event chain is allowed to complete.\n   * This should be called when not currently composing but a keydown event with the \"composition\n   * character\" (229) is triggered, in order to allow non-composition text to be entered when an\n   * IME is active.\n   */\n  private _handleAnyTextareaChanges(): void {\n    const oldValue = this._textarea.value;\n    setTimeout(() => {\n      // Ignore if a composition has started since the timeout\n      if (!this._isComposing) {\n        const newValue = this._textarea.value;\n        const diff = newValue.replace(oldValue, '');\n        if (diff.length > 0) {\n          this._coreService.triggerDataEvent(diff, true);\n        }\n      }\n    }, 0);\n  }\n\n  /**\n   * Positions the composition view on top of the cursor and the textarea just below it (so the\n   * IME helper dialog is positioned correctly).\n   * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is\n   *   necessary as the IME events across browsers are not consistently triggered.\n   */\n  public updateCompositionElements(dontRecurse?: boolean): void {\n    if (!this._isComposing) {\n      return;\n    }\n\n    if (this._bufferService.buffer.isCursorInViewport) {\n      const cellHeight = Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);\n      const cursorTop = this._bufferService.buffer.y * cellHeight;\n      const cursorLeft = this._bufferService.buffer.x * this._charSizeService.width;\n\n      this._compositionView.style.left = cursorLeft + 'px';\n      this._compositionView.style.top = cursorTop + 'px';\n      this._compositionView.style.height = cellHeight + 'px';\n      this._compositionView.style.lineHeight = cellHeight + 'px';\n      this._compositionView.style.fontFamily = this._optionsService.options.fontFamily;\n      this._compositionView.style.fontSize = this._optionsService.options.fontSize + 'px';\n      // Sync the textarea to the exact position of the composition view so the IME knows where the\n      // text is.\n      const compositionViewBounds = this._compositionView.getBoundingClientRect();\n      this._textarea.style.left = cursorLeft + 'px';\n      this._textarea.style.top = cursorTop + 'px';\n      this._textarea.style.width = compositionViewBounds.width + 'px';\n      this._textarea.style.height = compositionViewBounds.height + 'px';\n      this._textarea.style.lineHeight = compositionViewBounds.height + 'px';\n    }\n\n    if (!dontRecurse) {\n      setTimeout(() => this.updateCompositionElements(true), 0);\n    }\n  }\n\n  /**\n   * Clears the textarea's position so that the cursor does not blink on IE.\n   * @private\n   */\n  private _clearTextareaPosition(): void {\n    this._textarea.style.left = '';\n    this._textarea.style.top = '';\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'common/Lifecycle';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { IColorSet, IViewport } from 'browser/Types';\nimport { ICharSizeService, IRenderService } from 'browser/services/Services';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\nconst FALLBACK_SCROLL_BAR_WIDTH = 15;\n\n/**\n * Represents the viewport of a terminal, the visible area within the larger buffer of output.\n * Logic for the virtual scroll bar is included in this object.\n */\nexport class Viewport extends Disposable implements IViewport {\n  public scrollBarWidth: number = 0;\n  private _currentRowHeight: number = 0;\n  private _lastRecordedBufferLength: number = 0;\n  private _lastRecordedViewportHeight: number = 0;\n  private _lastRecordedBufferHeight: number = 0;\n  private _lastTouchY: number = 0;\n  private _lastScrollTop: number = 0;\n\n  // Stores a partial line amount when scrolling, this is used to keep track of how much of a line\n  // is scrolled so we can \"scroll\" over partial lines and feel natural on touchpads. This is a\n  // quick fix and could have a more robust solution in place that reset the value when needed.\n  private _wheelPartialScroll: number = 0;\n\n  private _refreshAnimationFrame: number | null = null;\n  private _ignoreNextScrollEvent: boolean = false;\n\n  constructor(\n    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,\n    private readonly _viewportElement: HTMLElement,\n    private readonly _scrollArea: HTMLElement,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @IOptionsService private readonly _optionsService: IOptionsService,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService,\n    @IRenderService private readonly _renderService: IRenderService\n  ) {\n    super();\n\n    // Measure the width of the scrollbar. If it is 0 we can assume it's an OSX overlay scrollbar.\n    // Unfortunately the overlay scrollbar would be hidden underneath the screen element in that case,\n    // therefore we account for a standard amount to make it visible\n    this.scrollBarWidth = (this._viewportElement.offsetWidth - this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH;\n    this.register(addDisposableDomListener(this._viewportElement, 'scroll', this._onScroll.bind(this)));\n\n    // Perform this async to ensure the ICharSizeService is ready.\n    setTimeout(() => this.syncScrollArea(), 0);\n  }\n\n  public onThemeChange(colors: IColorSet): void {\n    this._viewportElement.style.backgroundColor = colors.background.css;\n  }\n\n  /**\n   * Refreshes row height, setting line-height, viewport height and scroll area height if\n   * necessary.\n   */\n  private _refresh(immediate: boolean): void {\n    if (immediate) {\n      this._innerRefresh();\n      if (this._refreshAnimationFrame !== null) {\n        cancelAnimationFrame(this._refreshAnimationFrame);\n      }\n      return;\n    }\n    if (this._refreshAnimationFrame === null) {\n      this._refreshAnimationFrame = requestAnimationFrame(() => this._innerRefresh());\n    }\n  }\n\n  private _innerRefresh(): void {\n    if (this._charSizeService.height > 0) {\n      this._currentRowHeight = this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio;\n      this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;\n      const newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._renderService.dimensions.canvasHeight);\n      if (this._lastRecordedBufferHeight !== newBufferHeight) {\n        this._lastRecordedBufferHeight = newBufferHeight;\n        this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px';\n      }\n    }\n\n    // Sync scrollTop\n    const scrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;\n    if (this._viewportElement.scrollTop !== scrollTop) {\n      // Ignore the next scroll event which will be triggered by setting the scrollTop as we do not\n      // want this event to scroll the terminal\n      this._ignoreNextScrollEvent = true;\n      this._viewportElement.scrollTop = scrollTop;\n    }\n\n    this._refreshAnimationFrame = null;\n  }\n  /**\n   * Updates dimensions and synchronizes the scroll area if necessary.\n   */\n  public syncScrollArea(immediate: boolean = false): void {\n    // If buffer height changed\n    if (this._lastRecordedBufferLength !== this._bufferService.buffer.lines.length) {\n      this._lastRecordedBufferLength = this._bufferService.buffer.lines.length;\n      this._refresh(immediate);\n      return;\n    }\n\n    // If viewport height changed\n    if (this._lastRecordedViewportHeight !== this._renderService.dimensions.canvasHeight) {\n      this._refresh(immediate);\n      return;\n    }\n\n    // If the buffer position doesn't match last scroll top\n    const newScrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;\n    if (this._lastScrollTop !== newScrollTop) {\n      this._refresh(immediate);\n      return;\n    }\n\n    // If element's scroll top changed, this can happen when hiding the element\n    if (this._lastScrollTop !== this._viewportElement.scrollTop) {\n      this._refresh(immediate);\n      return;\n    }\n\n    // If row height changed\n    if (this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) {\n      this._refresh(immediate);\n      return;\n    }\n  }\n\n  /**\n   * Handles scroll events on the viewport, calculating the new viewport and requesting the\n   * terminal to scroll to it.\n   * @param ev The scroll event.\n   */\n  private _onScroll(ev: Event): void {\n    // Record current scroll top position\n    this._lastScrollTop = this._viewportElement.scrollTop;\n\n    // Don't attempt to scroll if the element is not visible, otherwise scrollTop will be corrupt\n    // which causes the terminal to scroll the buffer to the top\n    if (!this._viewportElement.offsetParent) {\n      return;\n    }\n\n    // Ignore the event if it was flagged to ignore (when the source of the event is from Viewport)\n    if (this._ignoreNextScrollEvent) {\n      this._ignoreNextScrollEvent = false;\n      return;\n    }\n\n    const newRow = Math.round(this._lastScrollTop / this._currentRowHeight);\n    const diff = newRow - this._bufferService.buffer.ydisp;\n    this._scrollLines(diff, true);\n  }\n\n  /**\n   * Handles bubbling of scroll event in case the viewport has reached top or bottom\n   * @param ev The scroll event.\n   * @param amount The amount scrolled\n   */\n  private _bubbleScroll(ev: Event, amount: number): boolean {\n    const scrollPosFromTop = this._viewportElement.scrollTop + this._lastRecordedViewportHeight;\n    if ((amount < 0 && this._viewportElement.scrollTop !== 0) ||\n        (amount > 0 &&  scrollPosFromTop < this._lastRecordedBufferHeight)) {\n      if (ev.cancelable) {\n        ev.preventDefault();\n      }\n      return false;\n    }\n    return true;\n  }\n\n  /**\n   * Handles mouse wheel events by adjusting the viewport's scrollTop and delegating the actual\n   * scrolling to `onScroll`, this event needs to be attached manually by the consumer of\n   * `Viewport`.\n   * @param ev The mouse wheel event.\n   */\n  public onWheel(ev: WheelEvent): boolean {\n    const amount = this._getPixelsScrolled(ev);\n    if (amount === 0) {\n      return false;\n    }\n    this._viewportElement.scrollTop += amount;\n    return this._bubbleScroll(ev, amount);\n  }\n\n  private _getPixelsScrolled(ev: WheelEvent): number {\n    // Do nothing if it's not a vertical scroll event\n    if (ev.deltaY === 0) {\n      return 0;\n    }\n\n    // Fallback to WheelEvent.DOM_DELTA_PIXEL\n    let amount = this._applyScrollModifier(ev.deltaY, ev);\n    if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {\n      amount *= this._currentRowHeight;\n    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n      amount *= this._currentRowHeight * this._bufferService.rows;\n    }\n    return amount;\n  }\n\n  /**\n   * Gets the number of pixels scrolled by the mouse event taking into account what type of delta\n   * is being used.\n   * @param ev The mouse wheel event.\n   */\n  public getLinesScrolled(ev: WheelEvent): number {\n    // Do nothing if it's not a vertical scroll event\n    if (ev.deltaY === 0) {\n      return 0;\n    }\n\n    // Fallback to WheelEvent.DOM_DELTA_LINE\n    let amount = this._applyScrollModifier(ev.deltaY, ev);\n    if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n      amount /= this._currentRowHeight + 0.0; // Prevent integer division\n      this._wheelPartialScroll += amount;\n      amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);\n      this._wheelPartialScroll %= 1;\n    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {\n      amount *= this._bufferService.rows;\n    }\n    return amount;\n  }\n\n  private _applyScrollModifier(amount: number, ev: WheelEvent): number {\n    const modifier = this._optionsService.options.fastScrollModifier;\n    // Multiply the scroll speed when the modifier is down\n    if ((modifier === 'alt' && ev.altKey) ||\n        (modifier === 'ctrl' && ev.ctrlKey) ||\n        (modifier === 'shift' && ev.shiftKey)) {\n      return amount * this._optionsService.options.fastScrollSensitivity * this._optionsService.options.scrollSensitivity;\n    }\n\n    return amount * this._optionsService.options.scrollSensitivity;\n  }\n\n  /**\n   * Handles the touchstart event, recording the touch occurred.\n   * @param ev The touch event.\n   */\n  public onTouchStart(ev: TouchEvent): void {\n    this._lastTouchY = ev.touches[0].pageY;\n  }\n\n  /**\n   * Handles the touchmove event, scrolling the viewport if the position shifted.\n   * @param ev The touch event.\n   */\n  public onTouchMove(ev: TouchEvent): boolean {\n    const deltaY = this._lastTouchY - ev.touches[0].pageY;\n    this._lastTouchY = ev.touches[0].pageY;\n    if (deltaY === 0) {\n      return false;\n    }\n    this._viewportElement.scrollTop += deltaY;\n    return this._bubbleScroll(ev, deltaY);\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ISelectionService } from 'browser/services/Services';\nimport { ICoreService } from 'common/services/Services';\n\n/**\n * Prepares text to be pasted into the terminal by normalizing the line endings\n * @param text The pasted text that needs processing before inserting into the terminal\n */\nexport function prepareTextForTerminal(text: string): string {\n  return text.replace(/\\r?\\n/g, '\\r');\n}\n\n/**\n * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste\n * @param text The pasted text to bracket\n */\nexport function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string {\n  if (bracketedPasteMode) {\n    return '\\x1b[200~' + text + '\\x1b[201~';\n  }\n  return text;\n}\n\n/**\n * Binds copy functionality to the given terminal.\n * @param ev The original copy event to be handled\n */\nexport function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void {\n  if (ev.clipboardData) {\n    ev.clipboardData.setData('text/plain', selectionService.selectionText);\n  }\n  // Prevent or the original text will be copied.\n  ev.preventDefault();\n}\n\n/**\n * Redirect the clipboard's data to the terminal's input handler.\n * @param ev The original paste event to be handled\n * @param term The terminal on which to apply the handled paste event\n */\nexport function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {\n  ev.stopPropagation();\n  if (ev.clipboardData) {\n    const text = ev.clipboardData.getData('text/plain');\n    paste(text, textarea, bracketedPasteMode, coreService);\n  }\n}\n\nexport function paste(text: string, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {\n  text = prepareTextForTerminal(text);\n  text = bracketTextForPaste(text, bracketedPasteMode);\n  coreService.triggerDataEvent(text, true);\n  textarea.value = '';\n}\n\n/**\n * Moves the textarea under the mouse cursor and focuses it.\n * @param ev The original right click event to be handled.\n * @param textarea The terminal's textarea.\n */\nexport function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void {\n\n  // Calculate textarea position relative to the screen element\n  const pos = screenElement.getBoundingClientRect();\n  const left = ev.clientX - pos.left - 10;\n  const top = ev.clientY - pos.top - 10;\n\n  // Bring textarea at the cursor position\n  textarea.style.position = 'absolute';\n  textarea.style.width = '20px';\n  textarea.style.height = '20px';\n  textarea.style.left = `${left}px`;\n  textarea.style.top = `${top}px`;\n  textarea.style.zIndex = '1000';\n\n  textarea.focus();\n\n  // Reset the terminal textarea's styling\n  // Timeout needs to be long enough for click event to be handled.\n  setTimeout(() => {\n    textarea.style.position = null;\n    textarea.style.width = null;\n    textarea.style.height = null;\n    textarea.style.left = null;\n    textarea.style.top = null;\n    textarea.style.zIndex = null;\n  }, 200);\n}\n\n/**\n * Bind to right-click event and allow right-click copy and paste.\n * @param ev The original right click event to be handled.\n * @param textarea The terminal's textarea.\n * @param selectionService The terminal's selection manager.\n * @param shouldSelectWord If true and there is no selection the current word will be selected\n */\nexport function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void {\n  moveTextAreaUnderMouseCursor(ev, textarea, screenElement);\n\n  if (shouldSelectWord && !selectionService.isClickInSelection(ev)) {\n    selectionService.selectWordAtCursor(ev);\n  }\n\n  // Get textarea ready to copy from the context menu\n  textarea.value = selectionService.selectionText;\n  textarea.select();\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IInputHandler, IInputHandlingTerminal } from './Types';\nimport { C0, C1 } from 'common/data/EscapeSequences';\nimport { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';\nimport { wcwidth } from 'common/CharWidth';\nimport { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';\nimport { Disposable } from 'common/Lifecycle';\nimport { concat } from 'common/TypedArrayUtils';\nimport { StringToUtf32, stringFromCodePoint, utf32ToString, Utf8ToUtf32 } from 'common/input/TextDecoder';\nimport { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';\nimport { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { IAttributeData, IDisposable } from 'common/Types';\nimport { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService } from 'common/services/Services';\nimport { OscHandler } from 'common/parser/OscParser';\nimport { DcsHandler } from 'common/parser/DcsParser';\n\n/**\n * Map collect to glevel. Used in `selectCharset`.\n */\nconst GLEVEL: {[key: string]: number} = {'(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2};\n\n/**\n * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.\n */\nconst MAX_PARSEBUFFER_LENGTH = 131072;\n\n\n/**\n * DCS subparser implementations\n */\n\n/**\n * DCS $ q Pt ST\n *   DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)\n *   Request Status String (DECRQSS), VT420 and up.\n *   Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)\n */\nclass DECRQSS implements IDcsHandler {\n  private _data: Uint32Array = new Uint32Array(0);\n\n  constructor(\n    private _bufferService: IBufferService,\n    private _coreService: ICoreService,\n    private _logService: ILogService,\n    private _optionsService: IOptionsService\n  ) { }\n\n  hook(params: IParams): void {\n    this._data = new Uint32Array(0);\n  }\n\n  put(data: Uint32Array, start: number, end: number): void {\n    this._data = concat(this._data, data.subarray(start, end));\n  }\n\n  unhook(success: boolean): void {\n    if (!success) {\n      this._data = new Uint32Array(0);\n      return;\n    }\n    const data = utf32ToString(this._data);\n    this._data = new Uint32Array(0);\n    switch (data) {\n      // valid: DCS 1 $ r Pt ST (xterm)\n      case '\"q': // DECSCA\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0\"q${C0.ESC}\\\\`);\n      case '\"p': // DECSCL\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r61\"p${C0.ESC}\\\\`);\n      case 'r': // DECSTBM\n        const pt = '' + (this._bufferService.buffer.scrollTop + 1) +\n                ';' + (this._bufferService.buffer.scrollBottom + 1) + 'r';\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${pt}${C0.ESC}\\\\`);\n      case 'm': // SGR\n        // TODO: report real settings instead of 0m\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0m${C0.ESC}\\\\`);\n      case ' q': // DECSCUSR\n        const STYLES: {[key: string]: number} = {'block': 2, 'underline': 4, 'bar': 6};\n        let style = STYLES[this._optionsService.options.cursorStyle];\n        style -= this._optionsService.options.cursorBlink ? 1 : 0;\n        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${style} q${C0.ESC}\\\\`);\n      default:\n        // invalid: DCS 0 $ r Pt ST (xterm)\n        this._logService.debug('Unknown DCS $q %s', data);\n        this._coreService.triggerDataEvent(`${C0.ESC}P0$r${C0.ESC}\\\\`);\n    }\n  }\n}\n\n/**\n * DCS Ps; Ps| Pt ST\n *   DECUDK (https://vt100.net/docs/vt510-rm/DECUDK.html)\n *   not supported\n */\n\n/**\n * DCS + q Pt ST (xterm)\n *   Request Terminfo String\n *   not implemented\n */\n\n/**\n * DCS + p Pt ST (xterm)\n *   Set Terminfo Data\n *   not supported\n */\n\n\n\n/**\n * The terminal's standard implementation of IInputHandler, this handles all\n * input from the Parser.\n *\n * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand\n * each function's header comment.\n */\nexport class InputHandler extends Disposable implements IInputHandler {\n  private _parseBuffer: Uint32Array = new Uint32Array(4096);\n  private _stringDecoder: StringToUtf32 = new StringToUtf32();\n  private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();\n  private _workCell: CellData = new CellData();\n\n  private _onCursorMove = new EventEmitter<void>();\n  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }\n  private _onLineFeed = new EventEmitter<void>();\n  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }\n  private _onScroll = new EventEmitter<number>();\n  public get onScroll(): IEvent<number> { return this._onScroll.event; }\n\n  constructor(\n    protected _terminal: IInputHandlingTerminal,\n    private readonly _bufferService: IBufferService,\n    private readonly _coreService: ICoreService,\n    private readonly _dirtyRowService: IDirtyRowService,\n    private readonly _logService: ILogService,\n    private readonly _optionsService: IOptionsService,\n    private readonly _coreMouseService: ICoreMouseService,\n    private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser())\n  {\n    super();\n\n    this.register(this._parser);\n\n    /**\n     * custom fallback handlers\n     */\n    this._parser.setCsiHandlerFallback((ident, params) => {\n      this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });\n    });\n    this._parser.setEscHandlerFallback(ident => {\n      this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });\n    });\n    this._parser.setExecuteHandlerFallback(code => {\n      this._logService.debug('Unknown EXECUTE code: ', { code });\n    });\n    this._parser.setOscHandlerFallback((identifier, action, data) => {\n      this._logService.debug('Unknown OSC code: ', { identifier, action, data });\n    });\n    this._parser.setDcsHandlerFallback((ident, action, payload) => {\n      if (action === 'HOOK') {\n        payload = payload.toArray();\n      }\n      this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });\n    });\n\n    /**\n     * print handler\n     */\n    this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));\n\n    /**\n     * CSI handler\n     */\n    this._parser.setCsiHandler({final: '@'}, params => this.insertChars(params));\n    this._parser.setCsiHandler({intermediates: ' ', final: '@'}, params => this.scrollLeft(params));\n    this._parser.setCsiHandler({final: 'A'}, params => this.cursorUp(params));\n    this._parser.setCsiHandler({intermediates: ' ', final: 'A'}, params => this.scrollRight(params));\n    this._parser.setCsiHandler({final: 'B'}, params => this.cursorDown(params));\n    this._parser.setCsiHandler({final: 'C'}, params => this.cursorForward(params));\n    this._parser.setCsiHandler({final: 'D'}, params => this.cursorBackward(params));\n    this._parser.setCsiHandler({final: 'E'}, params => this.cursorNextLine(params));\n    this._parser.setCsiHandler({final: 'F'}, params => this.cursorPrecedingLine(params));\n    this._parser.setCsiHandler({final: 'G'}, params => this.cursorCharAbsolute(params));\n    this._parser.setCsiHandler({final: 'H'}, params => this.cursorPosition(params));\n    this._parser.setCsiHandler({final: 'I'}, params => this.cursorForwardTab(params));\n    this._parser.setCsiHandler({final: 'J'}, params => this.eraseInDisplay(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'J'}, params => this.eraseInDisplay(params));\n    this._parser.setCsiHandler({final: 'K'}, params => this.eraseInLine(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'K'}, params => this.eraseInLine(params));\n    this._parser.setCsiHandler({final: 'L'}, params => this.insertLines(params));\n    this._parser.setCsiHandler({final: 'M'}, params => this.deleteLines(params));\n    this._parser.setCsiHandler({final: 'P'}, params => this.deleteChars(params));\n    this._parser.setCsiHandler({final: 'S'}, params => this.scrollUp(params));\n    this._parser.setCsiHandler({final: 'T'}, params => this.scrollDown(params));\n    this._parser.setCsiHandler({final: 'X'}, params => this.eraseChars(params));\n    this._parser.setCsiHandler({final: 'Z'}, params => this.cursorBackwardTab(params));\n    this._parser.setCsiHandler({final: '`'}, params => this.charPosAbsolute(params));\n    this._parser.setCsiHandler({final: 'a'}, params => this.hPositionRelative(params));\n    this._parser.setCsiHandler({final: 'b'}, params => this.repeatPrecedingCharacter(params));\n    this._parser.setCsiHandler({final: 'c'}, params => this.sendDeviceAttributesPrimary(params));\n    this._parser.setCsiHandler({prefix: '>', final: 'c'}, params => this.sendDeviceAttributesSecondary(params));\n    this._parser.setCsiHandler({final: 'd'}, params => this.linePosAbsolute(params));\n    this._parser.setCsiHandler({final: 'e'}, params => this.vPositionRelative(params));\n    this._parser.setCsiHandler({final: 'f'}, params => this.hVPosition(params));\n    this._parser.setCsiHandler({final: 'g'}, params => this.tabClear(params));\n    this._parser.setCsiHandler({final: 'h'}, params => this.setMode(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'h'}, params => this.setModePrivate(params));\n    this._parser.setCsiHandler({final: 'l'}, params => this.resetMode(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'l'}, params => this.resetModePrivate(params));\n    this._parser.setCsiHandler({final: 'm'}, params => this.charAttributes(params));\n    this._parser.setCsiHandler({final: 'n'}, params => this.deviceStatus(params));\n    this._parser.setCsiHandler({prefix: '?', final: 'n'}, params => this.deviceStatusPrivate(params));\n    this._parser.setCsiHandler({intermediates: '!', final: 'p'}, params => this.softReset(params));\n    this._parser.setCsiHandler({intermediates: ' ', final: 'q'}, params => this.setCursorStyle(params));\n    this._parser.setCsiHandler({final: 'r'}, params => this.setScrollRegion(params));\n    this._parser.setCsiHandler({final: 's'}, params => this.saveCursor(params));\n    this._parser.setCsiHandler({final: 'u'}, params => this.restoreCursor(params));\n    this._parser.setCsiHandler({intermediates: '\\'', final: '}'}, params => this.insertColumns(params));\n    this._parser.setCsiHandler({intermediates: '\\'', final: '~'}, params => this.deleteColumns(params));\n\n    /**\n     * execute handler\n     */\n    this._parser.setExecuteHandler(C0.BEL, () => this.bell());\n    this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());\n    this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());\n    this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());\n    this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());\n    this._parser.setExecuteHandler(C0.BS, () => this.backspace());\n    this._parser.setExecuteHandler(C0.HT, () => this.tab());\n    this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());\n    this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());\n    // FIXME:   What do to with missing? Old code just added those to print.\n\n    this._parser.setExecuteHandler(C1.IND, () => this.index());\n    this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());\n    this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());\n\n    /**\n     * OSC handler\n     */\n    //   0 - icon name + title\n    this._parser.setOscHandler(0, new OscHandler((data: string) => this.setTitle(data)));\n    //   1 - icon name\n    //   2 - title\n    this._parser.setOscHandler(2, new OscHandler((data: string) => this.setTitle(data)));\n    //   3 - set property X in the form \"prop=value\"\n    //   4 - Change Color Number\n    //   5 - Change Special Color Number\n    //   6 - Enable/disable Special Color Number c\n    //   7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)\n    //  10 - Change VT100 text foreground color to Pt.\n    //  11 - Change VT100 text background color to Pt.\n    //  12 - Change text cursor color to Pt.\n    //  13 - Change mouse foreground color to Pt.\n    //  14 - Change mouse background color to Pt.\n    //  15 - Change Tektronix foreground color to Pt.\n    //  16 - Change Tektronix background color to Pt.\n    //  17 - Change highlight background color to Pt.\n    //  18 - Change Tektronix cursor color to Pt.\n    //  19 - Change highlight foreground color to Pt.\n    //  46 - Change Log File to Pt.\n    //  50 - Set Font to Pt.\n    //  51 - reserved for Emacs shell.\n    //  52 - Manipulate Selection Data.\n    // 104 ; c - Reset Color Number c.\n    // 105 ; c - Reset Special Color Number c.\n    // 106 ; c; f - Enable/disable Special Color Number c.\n    // 110 - Reset VT100 text foreground color.\n    // 111 - Reset VT100 text background color.\n    // 112 - Reset text cursor color.\n    // 113 - Reset mouse foreground color.\n    // 114 - Reset mouse background color.\n    // 115 - Reset Tektronix foreground color.\n    // 116 - Reset Tektronix background color.\n    // 117 - Reset highlight color.\n    // 118 - Reset Tektronix cursor color.\n    // 119 - Reset highlight foreground color.\n\n    /**\n     * ESC handlers\n     */\n    this._parser.setEscHandler({final: '7'}, () => this.saveCursor());\n    this._parser.setEscHandler({final: '8'}, () => this.restoreCursor());\n    this._parser.setEscHandler({final: 'D'}, () => this.index());\n    this._parser.setEscHandler({final: 'E'}, () => this.nextLine());\n    this._parser.setEscHandler({final: 'H'}, () => this.tabSet());\n    this._parser.setEscHandler({final: 'M'}, () => this.reverseIndex());\n    this._parser.setEscHandler({final: '='}, () => this.keypadApplicationMode());\n    this._parser.setEscHandler({final: '>'}, () => this.keypadNumericMode());\n    this._parser.setEscHandler({final: 'c'}, () => this.reset());\n    this._parser.setEscHandler({final: 'n'}, () => this.setgLevel(2));\n    this._parser.setEscHandler({final: 'o'}, () => this.setgLevel(3));\n    this._parser.setEscHandler({final: '|'}, () => this.setgLevel(3));\n    this._parser.setEscHandler({final: '}'}, () => this.setgLevel(2));\n    this._parser.setEscHandler({final: '~'}, () => this.setgLevel(1));\n    this._parser.setEscHandler({intermediates: '%', final: '@'}, () => this.selectDefaultCharset());\n    this._parser.setEscHandler({intermediates: '%', final: 'G'}, () => this.selectDefaultCharset());\n    for (const flag in CHARSETS) {\n      this._parser.setEscHandler({intermediates: '(', final: flag}, () => this.selectCharset('(' + flag));\n      this._parser.setEscHandler({intermediates: ')', final: flag}, () => this.selectCharset(')' + flag));\n      this._parser.setEscHandler({intermediates: '*', final: flag}, () => this.selectCharset('*' + flag));\n      this._parser.setEscHandler({intermediates: '+', final: flag}, () => this.selectCharset('+' + flag));\n      this._parser.setEscHandler({intermediates: '-', final: flag}, () => this.selectCharset('-' + flag));\n      this._parser.setEscHandler({intermediates: '.', final: flag}, () => this.selectCharset('.' + flag));\n      this._parser.setEscHandler({intermediates: '/', final: flag}, () => this.selectCharset('/' + flag)); // TODO: supported?\n    }\n    this._parser.setEscHandler({intermediates: '#', final: '8'}, () => this.screenAlignmentPattern());\n\n    /**\n     * error handler\n     */\n    this._parser.setErrorHandler((state: IParsingState) => {\n      this._logService.error('Parsing error: ', state);\n      return state;\n    });\n\n    /**\n     * DCS handler\n     */\n    this._parser.setDcsHandler({intermediates: '$', final: 'q'}, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService));\n  }\n\n  public dispose(): void {\n    super.dispose();\n  }\n\n  public parse(data: string | Uint8Array): void {\n    let buffer = this._bufferService.buffer;\n    const cursorStartX = buffer.x;\n    const cursorStartY = buffer.y;\n\n    this._logService.debug('parsing data', data);\n\n    // resize input buffer if needed\n    if (this._parseBuffer.length < data.length) {\n      if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {\n        this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));\n      }\n    }\n\n    // process big data in smaller chunks\n    if (data.length > MAX_PARSEBUFFER_LENGTH) {\n      for (let i = 0; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {\n        const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;\n        const len = (typeof data === 'string')\n          ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)\n          : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);\n        this._parser.parse(this._parseBuffer, len);\n      }\n    } else {\n      const len = (typeof data === 'string')\n        ? this._stringDecoder.decode(data, this._parseBuffer)\n        : this._utf8Decoder.decode(data, this._parseBuffer);\n      this._parser.parse(this._parseBuffer, len);\n    }\n\n    buffer = this._bufferService.buffer;\n    if (buffer.x !== cursorStartX || buffer.y !== cursorStartY) {\n      this._onCursorMove.fire();\n    }\n    this._terminal.refresh(this._dirtyRowService.start, this._dirtyRowService.end);\n  }\n\n  public print(data: Uint32Array, start: number, end: number): void {\n    let code: number;\n    let chWidth: number;\n    const buffer = this._bufferService.buffer;\n    const charset = this._terminal.charset;\n    const screenReaderMode = this._optionsService.options.screenReaderMode;\n    const cols = this._bufferService.cols;\n    const wraparoundMode = this._terminal.wraparoundMode;\n    const insertMode = this._terminal.insertMode;\n    const curAttr = this._terminal.curAttrData;\n    let bufferRow = buffer.lines.get(buffer.y + buffer.ybase);\n\n    this._dirtyRowService.markDirty(buffer.y);\n    for (let pos = start; pos < end; ++pos) {\n      code = data[pos];\n\n      // calculate print space\n      // expensive call, therefore we save width in line buffer\n      chWidth = wcwidth(code);\n\n      // get charset replacement character\n      // charset is only defined for ASCII, therefore we only\n      // search for an replacement char if code < 127\n      if (code < 127 && charset) {\n        const ch = charset[String.fromCharCode(code)];\n        if (ch) {\n          code = ch.charCodeAt(0);\n        }\n      }\n\n      if (screenReaderMode) {\n        this._terminal.onA11yCharEmitter.fire(stringFromCodePoint(code));\n      }\n\n      // insert combining char at last cursor position\n      // FIXME: needs handling after cursor jumps\n      // buffer.x should never be 0 for a combining char\n      // since they always follow a cell consuming char\n      // therefore we can test for buffer.x to avoid overflow left\n      if (!chWidth && buffer.x) {\n        if (!bufferRow.getWidth(buffer.x - 1)) {\n          // found empty cell after fullwidth, need to go 2 cells back\n          // it is save to step 2 cells back here\n          // since an empty cell is only set by fullwidth chars\n          bufferRow.addCodepointToCell(buffer.x - 2, code);\n        } else {\n          bufferRow.addCodepointToCell(buffer.x - 1, code);\n        }\n        continue;\n      }\n\n      // goto next line if ch would overflow\n      // TODO: needs a global min terminal width of 2\n      // FIXME: additionally ensure chWidth fits into a line\n      //   -->  maybe forbid cols<xy at higher level as it would\n      //        introduce a bad runtime penalty here\n      if (buffer.x + chWidth - 1 >= cols) {\n        // autowrap - DECAWM\n        // automatically wraps to the beginning of the next line\n        if (wraparoundMode) {\n          buffer.x = 0;\n          buffer.y++;\n          if (buffer.y === buffer.scrollBottom + 1) {\n            buffer.y--;\n            this._terminal.scroll(true);\n          } else {\n            if (buffer.y >= this._bufferService.rows) {\n              buffer.y = this._bufferService.rows - 1;\n            }\n            // The line already exists (eg. the initial viewport), mark it as a\n            // wrapped line\n            buffer.lines.get(buffer.y).isWrapped = true;\n          }\n          // row changed, get it again\n          bufferRow = buffer.lines.get(buffer.y + buffer.ybase);\n        } else {\n          buffer.x = cols - 1;\n          if (chWidth === 2) {\n            // FIXME: check for xterm behavior\n            // What to do here? We got a wide char that does not fit into last cell\n            continue;\n          }\n        }\n      }\n\n      // insert mode: move characters to right\n      if (insertMode) {\n        // right shift cells according to the width\n        bufferRow.insertCells(buffer.x, chWidth, buffer.getNullCell(curAttr));\n        // test last cell - since the last cell has only room for\n        // a halfwidth char any fullwidth shifted there is lost\n        // and will be set to empty cell\n        if (bufferRow.getWidth(cols - 1) === 2) {\n          bufferRow.setCellFromCodePoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr.fg, curAttr.bg);\n        }\n      }\n\n      // write current char to buffer and advance cursor\n      bufferRow.setCellFromCodePoint(buffer.x++, code, chWidth, curAttr.fg, curAttr.bg);\n\n      // fullwidth char - also set next cell to placeholder stub and advance cursor\n      // for graphemes bigger than fullwidth we can simply loop to zero\n      // we already made sure above, that buffer.x + chWidth will not overflow right\n      if (chWidth > 0) {\n        while (--chWidth) {\n          // other than a regular empty cell a cell following a wide char has no width\n          bufferRow.setCellFromCodePoint(buffer.x++, 0, 0, curAttr.fg, curAttr.bg);\n        }\n      }\n    }\n    // store last char in Parser.precedingCodepoint for REP to work correctly\n    // This needs to check whether:\n    //  - fullwidth + surrogates: reset\n    //  - combining: only base char gets carried on (bug in xterm?)\n    if (end) {\n      bufferRow.loadCell(buffer.x - 1, this._workCell);\n      if (this._workCell.getWidth() === 2 || this._workCell.getCode() > 0xFFFF) {\n        this._parser.precedingCodepoint = 0;\n      } else if (this._workCell.isCombined()) {\n        this._parser.precedingCodepoint = this._workCell.getChars().charCodeAt(0);\n      } else {\n        this._parser.precedingCodepoint = this._workCell.content;\n      }\n    }\n    this._dirtyRowService.markDirty(buffer.y);\n  }\n\n  /**\n   * Forward addCsiHandler from parser.\n   */\n  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {\n    return this._parser.addCsiHandler(id, callback);\n  }\n\n  /**\n   * Forward addDcsHandler from parser.\n   */\n  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {\n    return this._parser.addDcsHandler(id, new DcsHandler(callback));\n  }\n\n  /**\n   * Forward addEscHandler from parser.\n   */\n  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {\n    return this._parser.addEscHandler(id, callback);\n  }\n\n  /**\n   * Forward addOscHandler from parser.\n   */\n  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {\n    return this._parser.addOscHandler(ident, new OscHandler(callback));\n  }\n\n  /**\n   * BEL\n   * Bell (Ctrl-G).\n   */\n  public bell(): void {\n    this._terminal.bell();\n  }\n\n  /**\n   * LF\n   * Line Feed or New Line (NL).  (LF  is Ctrl-J).\n   */\n  public lineFeed(): void {\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    if (this._optionsService.options.convertEol) {\n      buffer.x = 0;\n    }\n    buffer.y++;\n    if (buffer.y === buffer.scrollBottom + 1) {\n      buffer.y--;\n      this._terminal.scroll();\n    } else if (buffer.y >= this._bufferService.rows) {\n      buffer.y = this._bufferService.rows - 1;\n    }\n    // If the end of the line is hit, prevent this action from wrapping around to the next line.\n    if (buffer.x >= this._bufferService.cols) {\n      buffer.x--;\n    }\n\n    this._onLineFeed.fire();\n  }\n\n  /**\n   * CR\n   * Carriage Return (Ctrl-M).\n   */\n  public carriageReturn(): void {\n    this._bufferService.buffer.x = 0;\n  }\n\n  /**\n   * BS\n   * Backspace (Ctrl-H).\n   */\n  public backspace(): void {\n    this._restrictCursor();\n    if (this._bufferService.buffer.x > 0) {\n      this._bufferService.buffer.x--;\n    }\n  }\n\n  /**\n   * TAB\n   * Horizontal Tab (HT) (Ctrl-I).\n   */\n  public tab(): void {\n    if (this._bufferService.buffer.x >= this._bufferService.cols) {\n      return;\n    }\n    const originalX = this._bufferService.buffer.x;\n    this._bufferService.buffer.x = this._bufferService.buffer.nextStop();\n    if (this._optionsService.options.screenReaderMode) {\n      this._terminal.onA11yTabEmitter.fire(this._bufferService.buffer.x - originalX);\n    }\n  }\n\n  /**\n   * SO\n   * Shift Out (Ctrl-N) -> Switch to Alternate Character Set.  This invokes the\n   * G1 character set.\n   */\n  public shiftOut(): void {\n    this._terminal.setgLevel(1);\n  }\n\n  /**\n   * SI\n   * Shift In (Ctrl-O) -> Switch to Standard Character Set.  This invokes the G0\n   * character set (the default).\n   */\n  public shiftIn(): void {\n    this._terminal.setgLevel(0);\n  }\n\n  /**\n   * Restrict cursor to viewport size / scroll margin (origin mode).\n   */\n  private _restrictCursor(): void {\n    this._bufferService.buffer.x = Math.min(this._bufferService.cols - 1, Math.max(0, this._bufferService.buffer.x));\n    this._bufferService.buffer.y = this._terminal.originMode\n      ? Math.min(this._bufferService.buffer.scrollBottom, Math.max(this._bufferService.buffer.scrollTop, this._bufferService.buffer.y))\n      : Math.min(this._bufferService.rows - 1, Math.max(0, this._bufferService.buffer.y));\n  }\n\n  /**\n   * Set absolute cursor position.\n   */\n  private _setCursor(x: number, y: number): void {\n    if (this._terminal.originMode) {\n      this._bufferService.buffer.x = x;\n      this._bufferService.buffer.y = this._bufferService.buffer.scrollTop + y;\n    } else {\n      this._bufferService.buffer.x = x;\n      this._bufferService.buffer.y = y;\n    }\n    this._restrictCursor();\n  }\n\n  /**\n   * Set relative cursor position.\n   */\n  private _moveCursor(x: number, y: number): void {\n    // for relative changes we have to make sure we are within 0 .. cols/rows - 1\n    // before calculating the new position\n    this._restrictCursor();\n    this._setCursor(this._bufferService.buffer.x + x, this._bufferService.buffer.y + y);\n  }\n\n  /**\n   * CSI Ps A\n   * Cursor Up Ps Times (default = 1) (CUU).\n   */\n  public cursorUp(params: IParams): void {\n    // stop at scrollTop\n    const diffToTop = this._bufferService.buffer.y - this._bufferService.buffer.scrollTop;\n    if (diffToTop >= 0) {\n      this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));\n    } else {\n      this._moveCursor(0, -(params.params[0] || 1));\n    }\n  }\n\n  /**\n   * CSI Ps B\n   * Cursor Down Ps Times (default = 1) (CUD).\n   */\n  public cursorDown(params: IParams): void {\n    // stop at scrollBottom\n    const diffToBottom = this._bufferService.buffer.scrollBottom - this._bufferService.buffer.y;\n    if (diffToBottom >= 0) {\n      this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));\n    } else {\n      this._moveCursor(0, params.params[0] || 1);\n    }\n  }\n\n  /**\n   * CSI Ps C\n   * Cursor Forward Ps Times (default = 1) (CUF).\n   */\n  public cursorForward(params: IParams): void {\n    this._moveCursor(params.params[0] || 1, 0);\n  }\n\n  /**\n   * CSI Ps D\n   * Cursor Backward Ps Times (default = 1) (CUB).\n   */\n  public cursorBackward(params: IParams): void {\n    this._moveCursor(-(params.params[0] || 1), 0);\n  }\n\n  /**\n   * CSI Ps E\n   * Cursor Next Line Ps Times (default = 1) (CNL).\n   * Other than cursorDown (CUD) also set the cursor to first column.\n   */\n  public cursorNextLine(params: IParams): void {\n    this.cursorDown(params);\n    this._bufferService.buffer.x = 0;\n  }\n\n  /**\n   * CSI Ps F\n   * Cursor Previous Line Ps Times (default = 1) (CPL).\n   * Other than cursorUp (CUU) also set the cursor to first column.\n   */\n  public cursorPrecedingLine(params: IParams): void {\n    this.cursorUp(params);\n    this._bufferService.buffer.x = 0;\n  }\n\n  /**\n   * CSI Ps G\n   * Cursor Character Absolute  [column] (default = [row,1]) (CHA).\n   */\n  public cursorCharAbsolute(params: IParams): void {\n    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);\n  }\n\n  /**\n   * CSI Ps ; Ps H\n   * Cursor Position [row;column] (default = [1,1]) (CUP).\n   */\n  public cursorPosition(params: IParams): void {\n    this._setCursor(\n      // col\n      (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,\n      // row\n      (params.params[0] || 1) - 1);\n  }\n\n  /**\n   * CSI Pm `  Character Position Absolute\n   *   [column] (default = [row,1]) (HPA).\n   * Currently same functionality as CHA.\n   */\n  public charPosAbsolute(params: IParams): void {\n    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);\n  }\n\n  /**\n   * CSI Pm a  Character Position Relative\n   *   [columns] (default = [row,col+1]) (HPR)\n   * Currently same functionality as CUF.\n   */\n  public hPositionRelative(params: IParams): void {\n    this._moveCursor(params.params[0] || 1, 0);\n  }\n\n  /**\n   * CSI Pm d  Vertical Position Absolute (VPA)\n   *   [row] (default = [1,column])\n   */\n  public linePosAbsolute(params: IParams): void {\n    this._setCursor(this._bufferService.buffer.x, (params.params[0] || 1) - 1);\n  }\n\n  /**\n   * CSI Pm e  Vertical Position Relative (VPR)\n   *   [rows] (default = [row+1,column])\n   * reuse CSI Ps B ?\n   */\n  public vPositionRelative(params: IParams): void {\n    this._moveCursor(0, params.params[0] || 1);\n  }\n\n  /**\n   * CSI Ps ; Ps f\n   *   Horizontal and Vertical Position [row;column] (default =\n   *   [1,1]) (HVP).\n   *   Same as CUP.\n   */\n  public hVPosition(params: IParams): void {\n    this.cursorPosition(params);\n  }\n\n  /**\n   * CSI Ps g  Tab Clear (TBC).\n   *     Ps = 0  -> Clear Current Column (default).\n   *     Ps = 3  -> Clear All.\n   * Potentially:\n   *   Ps = 2  -> Clear Stops on Line.\n   *   http://vt100.net/annarbor/aaa-ug/section6.html\n   */\n  public tabClear(params: IParams): void {\n    const param = params.params[0];\n    if (param === 0) {\n      delete this._bufferService.buffer.tabs[this._bufferService.buffer.x];\n    } else if (param === 3) {\n      this._bufferService.buffer.tabs = {};\n    }\n  }\n\n  /**\n   * CSI Ps I\n   *   Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).\n   */\n  public cursorForwardTab(params: IParams): void {\n    if (this._bufferService.buffer.x >= this._bufferService.cols) {\n      return;\n    }\n    let param = params.params[0] || 1;\n    while (param--) {\n      this._bufferService.buffer.x = this._bufferService.buffer.nextStop();\n    }\n  }\n\n  /**\n   * CSI Ps Z  Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).\n   */\n  public cursorBackwardTab(params: IParams): void {\n    if (this._bufferService.buffer.x >= this._bufferService.cols) {\n      return;\n    }\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    while (param--) {\n      buffer.x = buffer.prevStop();\n    }\n  }\n\n\n  /**\n   * Helper method to erase cells in a terminal row.\n   * The cell gets replaced with the eraseChar of the terminal.\n   * @param y row index\n   * @param start first cell index to be erased\n   * @param end   end - 1 is last erased cell\n   */\n  private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false): void {\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);\n    line.replaceCells(\n      start,\n      end,\n      this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n    );\n    if (clearWrap) {\n      line.isWrapped = false;\n    }\n  }\n\n  /**\n   * Helper method to reset cells in a terminal row.\n   * The cell gets replaced with the eraseChar of the terminal and the isWrapped property is set to false.\n   * @param y row index\n   */\n  private _resetBufferLine(y: number): void {\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);\n    line.fill(this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData()));\n    line.isWrapped = false;\n  }\n\n  /**\n   * CSI Ps J  Erase in Display (ED).\n   *     Ps = 0  -> Erase Below (default).\n   *     Ps = 1  -> Erase Above.\n   *     Ps = 2  -> Erase All.\n   *     Ps = 3  -> Erase Saved Lines (xterm).\n   * CSI ? Ps J\n   *   Erase in Display (DECSED).\n   *     Ps = 0  -> Selective Erase Below (default).\n   *     Ps = 1  -> Selective Erase Above.\n   *     Ps = 2  -> Selective Erase All.\n   */\n  public eraseInDisplay(params: IParams): void {\n    this._restrictCursor();\n    let j;\n    switch (params.params[0]) {\n      case 0:\n        j = this._bufferService.buffer.y;\n        this._dirtyRowService.markDirty(j);\n        this._eraseInBufferLine(j++, this._bufferService.buffer.x, this._bufferService.cols, this._bufferService.buffer.x === 0);\n        for (; j < this._bufferService.rows; j++) {\n          this._resetBufferLine(j);\n        }\n        this._dirtyRowService.markDirty(j);\n        break;\n      case 1:\n        j = this._bufferService.buffer.y;\n        this._dirtyRowService.markDirty(j);\n        // Deleted front part of line and everything before. This line will no longer be wrapped.\n        this._eraseInBufferLine(j, 0, this._bufferService.buffer.x + 1, true);\n        if (this._bufferService.buffer.x + 1 >= this._bufferService.cols) {\n          // Deleted entire previous line. This next line can no longer be wrapped.\n          this._bufferService.buffer.lines.get(j + 1).isWrapped = false;\n        }\n        while (j--) {\n          this._resetBufferLine(j);\n        }\n        this._dirtyRowService.markDirty(0);\n        break;\n      case 2:\n        j = this._bufferService.rows;\n        this._dirtyRowService.markDirty(j - 1);\n        while (j--) {\n          this._resetBufferLine(j);\n        }\n        this._dirtyRowService.markDirty(0);\n        break;\n      case 3:\n        // Clear scrollback (everything not in viewport)\n        const scrollBackSize = this._bufferService.buffer.lines.length - this._bufferService.rows;\n        if (scrollBackSize > 0) {\n          this._bufferService.buffer.lines.trimStart(scrollBackSize);\n          this._bufferService.buffer.ybase = Math.max(this._bufferService.buffer.ybase - scrollBackSize, 0);\n          this._bufferService.buffer.ydisp = Math.max(this._bufferService.buffer.ydisp - scrollBackSize, 0);\n          // Force a scroll event to refresh viewport\n          this._onScroll.fire(0);\n        }\n        break;\n    }\n  }\n\n  /**\n   * CSI Ps K  Erase in Line (EL).\n   *     Ps = 0  -> Erase to Right (default).\n   *     Ps = 1  -> Erase to Left.\n   *     Ps = 2  -> Erase All.\n   * CSI ? Ps K\n   *   Erase in Line (DECSEL).\n   *     Ps = 0  -> Selective Erase to Right (default).\n   *     Ps = 1  -> Selective Erase to Left.\n   *     Ps = 2  -> Selective Erase All.\n   */\n  public eraseInLine(params: IParams): void {\n    this._restrictCursor();\n    switch (params.params[0]) {\n      case 0:\n        this._eraseInBufferLine(this._bufferService.buffer.y, this._bufferService.buffer.x, this._bufferService.cols);\n        break;\n      case 1:\n        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.buffer.x + 1);\n        break;\n      case 2:\n        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.cols);\n        break;\n    }\n    this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n  }\n\n  /**\n   * CSI Ps L\n   * Insert Ps Line(s) (default = 1) (IL).\n   */\n  public insertLines(params: IParams): void {\n    this._restrictCursor();\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n\n    const row: number = buffer.y + buffer.ybase;\n\n    const scrollBottomRowsOffset = this._bufferService.rows - 1 - buffer.scrollBottom;\n    const scrollBottomAbsolute = this._bufferService.rows - 1 + buffer.ybase - scrollBottomRowsOffset + 1;\n    while (param--) {\n      // test: echo -e '\\e[44m\\e[1L\\e[0m'\n      // blankLine(true) - xterm/linux behavior\n      buffer.lines.splice(scrollBottomAbsolute - 1, 1);\n      buffer.lines.splice(row, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));\n    }\n\n    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);\n    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n  }\n\n  /**\n   * CSI Ps M\n   * Delete Ps Line(s) (default = 1) (DL).\n   */\n  public deleteLines(params: IParams): void {\n    this._restrictCursor();\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n\n    const row: number = buffer.y + buffer.ybase;\n\n    let j: number;\n    j = this._bufferService.rows - 1 - buffer.scrollBottom;\n    j = this._bufferService.rows - 1 + buffer.ybase - j;\n    while (param--) {\n      // test: echo -e '\\e[44m\\e[1M\\e[0m'\n      // blankLine(true) - xterm/linux behavior\n      buffer.lines.splice(row, 1);\n      buffer.lines.splice(j, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));\n    }\n\n    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);\n    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?\n  }\n\n  /**\n   * CSI Ps @\n   * Insert Ps (Blank) Character(s) (default = 1) (ICH).\n   */\n  public insertChars(params: IParams): void {\n    this._restrictCursor();\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);\n    if (line) {\n      line.insertCells(\n        this._bufferService.buffer.x,\n        params.params[0] || 1,\n        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n      );\n      this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n    }\n  }\n\n  /**\n   * CSI Ps P\n   * Delete Ps Character(s) (default = 1) (DCH).\n   */\n  public deleteChars(params: IParams): void {\n    this._restrictCursor();\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);\n    if (line) {\n      line.deleteCells(\n        this._bufferService.buffer.x,\n        params.params[0] || 1,\n        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n      );\n      this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n    }\n  }\n\n  /**\n   * CSI Ps S  Scroll up Ps lines (default = 1) (SU).\n   */\n  public scrollUp(params: IParams): void {\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    while (param--) {\n      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 1);\n      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps T  Scroll down Ps lines (default = 1) (SD).\n   */\n  public scrollDown(params: IParams): void {\n    let param = params.params[0] || 1;\n\n    // make buffer local for faster access\n    const buffer = this._bufferService.buffer;\n\n    while (param--) {\n      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 1);\n      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 0, buffer.getBlankLine(DEFAULT_ATTR_DATA));\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps SP @  Scroll left Ps columns (default = 1) (SL) ECMA-48\n   *\n   * Notation: (Pn)\n   * Representation: CSI Pn 02/00 04/00\n   * Parameter default value: Pn = 1\n   * SL causes the data in the presentation component to be moved by n character positions\n   * if the line orientation is horizontal, or by n line positions if the line orientation\n   * is vertical, such that the data appear to move to the left; where n equals the value of Pn.\n   * The active presentation position is not affected by this control function.\n   *\n   * Supported:\n   *   - always left shift (no line orientation setting respected)\n   */\n  public scrollLeft(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = buffer.lines.get(buffer.ybase + y);\n      line.deleteCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps SP A  Scroll right Ps columns (default = 1) (SR) ECMA-48\n   *\n   * Notation: (Pn)\n   * Representation: CSI Pn 02/00 04/01\n   * Parameter default value: Pn = 1\n   * SR causes the data in the presentation component to be moved by n character positions\n   * if the line orientation is horizontal, or by n line positions if the line orientation\n   * is vertical, such that the data appear to move to the right; where n equals the value of Pn.\n   * The active presentation position is not affected by this control function.\n   *\n   * Supported:\n   *   - always right shift (no line orientation setting respected)\n   */\n  public scrollRight(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = buffer.lines.get(buffer.ybase + y);\n      line.insertCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Pm ' }\n   * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.\n   */\n  public insertColumns(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = this._bufferService.buffer.lines.get(buffer.ybase + y);\n      line.insertCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Pm ' ~\n   * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.\n   */\n  public deleteColumns(params: IParams): void {\n    const buffer = this._bufferService.buffer;\n    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {\n      return;\n    }\n    const param = params.params[0] || 1;\n    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {\n      const line = buffer.lines.get(buffer.ybase + y);\n      line.deleteCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));\n      line.isWrapped = false;\n    }\n    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n  }\n\n  /**\n   * CSI Ps X\n   * Erase Ps Character(s) (default = 1) (ECH).\n   */\n  public eraseChars(params: IParams): void {\n    this._restrictCursor();\n    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);\n    if (line) {\n      line.replaceCells(\n        this._bufferService.buffer.x,\n        this._bufferService.buffer.x + (params.params[0] || 1),\n        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())\n      );\n      this._dirtyRowService.markDirty(this._bufferService.buffer.y);\n    }\n  }\n\n  /**\n   * CSI Ps b  Repeat the preceding graphic character Ps times (REP).\n   * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)\n   *    Notation: (Pn)\n   *    Representation: CSI Pn 06/02\n   *    Parameter default value: Pn = 1\n   *    REP is used to indicate that the preceding character in the data stream,\n   *    if it is a graphic character (represented by one or more bit combinations) including SPACE,\n   *    is to be repeated n times, where n equals the value of Pn.\n   *    If the character preceding REP is a control function or part of a control function,\n   *    the effect of REP is not defined by this Standard.\n   *\n   * Since we propagate the terminal as xterm-256color we have to follow xterm's behavior:\n   *    - fullwidth + surrogate chars are ignored\n   *    - for combining chars only the base char gets repeated\n   *    - text attrs are applied normally\n   *    - wrap around is respected\n   *    - any valid sequence resets the carried forward char\n   *\n   * Note: To get reset on a valid sequence working correctly without much runtime penalty,\n   * the preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.\n   */\n  public repeatPrecedingCharacter(params: IParams): void {\n    if (!this._parser.precedingCodepoint) {\n      return;\n    }\n    // call print to insert the chars and handle correct wrapping\n    const length = params.params[0] || 1;\n    const data = new Uint32Array(length);\n    for (let i = 0; i < length; ++i) {\n      data[i] = this._parser.precedingCodepoint;\n    }\n    this.print(data, 0, data.length);\n  }\n\n  /**\n   * CSI Ps c  Send Device Attributes (Primary DA).\n   *     Ps = 0  or omitted -> request attributes from terminal.  The\n   *     response depends on the decTerminalID resource setting.\n   *     -> CSI ? 1 ; 2 c  (``VT100 with Advanced Video Option'')\n   *     -> CSI ? 1 ; 0 c  (``VT101 with No Options'')\n   *     -> CSI ? 6 c  (``VT102'')\n   *     -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c  (``VT220'')\n   *   The VT100-style response parameters do not mean anything by\n   *   themselves.  VT220 parameters do, telling the host what fea-\n   *   tures the terminal supports:\n   *     Ps = 1  -> 132-columns.\n   *     Ps = 2  -> Printer.\n   *     Ps = 6  -> Selective erase.\n   *     Ps = 8  -> User-defined keys.\n   *     Ps = 9  -> National replacement character sets.\n   *     Ps = 1 5  -> Technical characters.\n   *     Ps = 2 2  -> ANSI color, e.g., VT525.\n   *     Ps = 2 9  -> ANSI text locator (i.e., DEC Locator mode).\n   * CSI > Ps c\n   *   Send Device Attributes (Secondary DA).\n   *     Ps = 0  or omitted -> request the terminal's identification\n   *     code.  The response depends on the decTerminalID resource set-\n   *     ting.  It should apply only to VT220 and up, but xterm extends\n   *     this to VT100.\n   *     -> CSI  > Pp ; Pv ; Pc c\n   *   where Pp denotes the terminal type\n   *     Pp = 0  -> ``VT100''.\n   *     Pp = 1  -> ``VT220''.\n   *   and Pv is the firmware version (for xterm, this was originally\n   *   the XFree86 patch number, starting with 95).  In a DEC termi-\n   *   nal, Pc indicates the ROM cartridge registration number and is\n   *   always zero.\n   * More information:\n   *   xterm/charproc.c - line 2012, for more information.\n   *   vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)\n   */\n  public sendDeviceAttributesPrimary(params: IParams): void {\n    if (params.params[0] > 0) {\n      return;\n    }\n    if (this._terminal.is('xterm') || this._terminal.is('rxvt-unicode') || this._terminal.is('screen')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');\n    } else if (this._terminal.is('linux')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[?6c');\n    }\n  }\n  public sendDeviceAttributesSecondary(params: IParams): void {\n    if (params.params[0] > 0) {\n      return;\n    }\n    // xterm and urxvt\n    // seem to spit this\n    // out around ~370 times (?).\n    if (this._terminal.is('xterm')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');\n    } else if (this._terminal.is('rxvt-unicode')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');\n    } else if (this._terminal.is('linux')) {\n      // not supported by linux console.\n      // linux console echoes parameters.\n      this._coreService.triggerDataEvent(params.params[0] + 'c');\n    } else if (this._terminal.is('screen')) {\n      this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');\n    }\n  }\n\n  /**\n   * CSI Pm h  Set Mode (SM).\n   *     Ps = 2  -> Keyboard Action Mode (AM).\n   *     Ps = 4  -> Insert Mode (IRM).\n   *     Ps = 1 2  -> Send/receive (SRM).\n   *     Ps = 2 0  -> Automatic Newline (LNM).\n   * CSI ? Pm h\n   *   DEC Private Mode Set (DECSET).\n   *     Ps = 1  -> Application Cursor Keys (DECCKM).\n   *     Ps = 2  -> Designate USASCII for character sets G0-G3\n   *     (DECANM), and set VT100 mode.\n   *     Ps = 3  -> 132 Column Mode (DECCOLM).\n   *     Ps = 4  -> Smooth (Slow) Scroll (DECSCLM).\n   *     Ps = 5  -> Reverse Video (DECSCNM).\n   *     Ps = 6  -> Origin Mode (DECOM).\n   *     Ps = 7  -> Wraparound Mode (DECAWM).\n   *     Ps = 8  -> Auto-repeat Keys (DECARM).\n   *     Ps = 9  -> Send Mouse X & Y on button press.  See the sec-\n   *     tion Mouse Tracking.\n   *     Ps = 1 0  -> Show toolbar (rxvt).\n   *     Ps = 1 2  -> Start Blinking Cursor (att610).\n   *     Ps = 1 8  -> Print form feed (DECPFF).\n   *     Ps = 1 9  -> Set print extent to full screen (DECPEX).\n   *     Ps = 2 5  -> Show Cursor (DECTCEM).\n   *     Ps = 3 0  -> Show scrollbar (rxvt).\n   *     Ps = 3 5  -> Enable font-shifting functions (rxvt).\n   *     Ps = 3 8  -> Enter Tektronix Mode (DECTEK).\n   *     Ps = 4 0  -> Allow 80 -> 132 Mode.\n   *     Ps = 4 1  -> more(1) fix (see curses resource).\n   *     Ps = 4 2  -> Enable Nation Replacement Character sets (DECN-\n   *     RCM).\n   *     Ps = 4 4  -> Turn On Margin Bell.\n   *     Ps = 4 5  -> Reverse-wraparound Mode.\n   *     Ps = 4 6  -> Start Logging.  This is normally disabled by a\n   *     compile-time option.\n   *     Ps = 4 7  -> Use Alternate Screen Buffer.  (This may be dis-\n   *     abled by the titeInhibit resource).\n   *     Ps = 6 6  -> Application keypad (DECNKM).\n   *     Ps = 6 7  -> Backarrow key sends backspace (DECBKM).\n   *     Ps = 1 0 0 0  -> Send Mouse X & Y on button press and\n   *     release.  See the section Mouse Tracking.\n   *     Ps = 1 0 0 1  -> Use Hilite Mouse Tracking.\n   *     Ps = 1 0 0 2  -> Use Cell Motion Mouse Tracking.\n   *     Ps = 1 0 0 3  -> Use All Motion Mouse Tracking.\n   *     Ps = 1 0 0 4  -> Send FocusIn/FocusOut events.\n   *     Ps = 1 0 0 5  -> Enable Extended Mouse Mode.\n   *     Ps = 1 0 1 0  -> Scroll to bottom on tty output (rxvt).\n   *     Ps = 1 0 1 1  -> Scroll to bottom on key press (rxvt).\n   *     Ps = 1 0 3 4  -> Interpret \"meta\" key, sets eighth bit.\n   *     (enables the eightBitInput resource).\n   *     Ps = 1 0 3 5  -> Enable special modifiers for Alt and Num-\n   *     Lock keys.  (This enables the numLock resource).\n   *     Ps = 1 0 3 6  -> Send ESC   when Meta modifies a key.  (This\n   *     enables the metaSendsEscape resource).\n   *     Ps = 1 0 3 7  -> Send DEL from the editing-keypad Delete\n   *     key.\n   *     Ps = 1 0 3 9  -> Send ESC  when Alt modifies a key.  (This\n   *     enables the altSendsEscape resource).\n   *     Ps = 1 0 4 0  -> Keep selection even if not highlighted.\n   *     (This enables the keepSelection resource).\n   *     Ps = 1 0 4 1  -> Use the CLIPBOARD selection.  (This enables\n   *     the selectToClipboard resource).\n   *     Ps = 1 0 4 2  -> Enable Urgency window manager hint when\n   *     Control-G is received.  (This enables the bellIsUrgent\n   *     resource).\n   *     Ps = 1 0 4 3  -> Enable raising of the window when Control-G\n   *     is received.  (enables the popOnBell resource).\n   *     Ps = 1 0 4 7  -> Use Alternate Screen Buffer.  (This may be\n   *     disabled by the titeInhibit resource).\n   *     Ps = 1 0 4 8  -> Save cursor as in DECSC.  (This may be dis-\n   *     abled by the titeInhibit resource).\n   *     Ps = 1 0 4 9  -> Save cursor as in DECSC and use Alternate\n   *     Screen Buffer, clearing it first.  (This may be disabled by\n   *     the titeInhibit resource).  This combines the effects of the 1\n   *     0 4 7  and 1 0 4 8  modes.  Use this with terminfo-based\n   *     applications rather than the 4 7  mode.\n   *     Ps = 1 0 5 0  -> Set terminfo/termcap function-key mode.\n   *     Ps = 1 0 5 1  -> Set Sun function-key mode.\n   *     Ps = 1 0 5 2  -> Set HP function-key mode.\n   *     Ps = 1 0 5 3  -> Set SCO function-key mode.\n   *     Ps = 1 0 6 0  -> Set legacy keyboard emulation (X11R6).\n   *     Ps = 1 0 6 1  -> Set VT220 keyboard emulation.\n   *     Ps = 2 0 0 4  -> Set bracketed paste mode.\n   * Modes:\n   *   http: *vt100.net/docs/vt220-rm/chapter4.html\n   */\n  public setMode(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 4:\n          this._terminal.insertMode = true;\n          break;\n        case 20:\n          // this._t.convertEol = true;\n          break;\n      }\n    }\n  }\n  public setModePrivate(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 1:\n          this._coreService.decPrivateModes.applicationCursorKeys = true;\n          break;\n        case 2:\n          this._terminal.setgCharset(0, DEFAULT_CHARSET);\n          this._terminal.setgCharset(1, DEFAULT_CHARSET);\n          this._terminal.setgCharset(2, DEFAULT_CHARSET);\n          this._terminal.setgCharset(3, DEFAULT_CHARSET);\n          // set VT100 mode here\n          break;\n        case 3: // 132 col mode\n          // TODO: move DECCOLM into compat addon\n          this._terminal.savedCols = this._bufferService.cols;\n          this._terminal.resize(132, this._bufferService.rows);\n          this._terminal.reset();\n          break;\n        case 6:\n          this._terminal.originMode = true;\n          this._setCursor(0, 0);\n          break;\n        case 7:\n          this._terminal.wraparoundMode = true;\n          break;\n        case 12:\n          // this.cursorBlink = true;\n          break;\n        case 66:\n          this._logService.debug('Serial port requested application keypad.');\n          this._terminal.applicationKeypad = true;\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          break;\n        case 9: // X10 Mouse\n          // no release, no motion, no wheel, no modifiers.\n          this._coreMouseService.activeProtocol = 'X10';\n          break;\n        case 1000: // vt200 mouse\n          // no motion.\n          this._coreMouseService.activeProtocol = 'VT200';\n          break;\n        case 1002: // button event mouse\n          this._coreMouseService.activeProtocol = 'DRAG';\n          break;\n        case 1003: // any event mouse\n          // any event - sends motion events,\n          // even if there is no button held down.\n          this._coreMouseService.activeProtocol = 'ANY';\n          break;\n        case 1004: // send focusin/focusout events\n          // focusin: ^[[I\n          // focusout: ^[[O\n          this._terminal.sendFocus = true;\n          break;\n        case 1005: // utf8 ext mode mouse - removed in #2507\n          this._logService.debug('DECSET 1005 not supported (see #2507)');\n          break;\n        case 1006: // sgr ext mode mouse\n          this._coreMouseService.activeEncoding = 'SGR';\n          break;\n        case 1015: // urxvt ext mode mouse - removed in #2507\n          this._logService.debug('DECSET 1015 not supported (see #2507)');\n          break;\n        case 25: // show cursor\n          this._terminal.cursorHidden = false;\n          break;\n        case 1048: // alt screen cursor\n          this.saveCursor();\n          break;\n        case 1049: // alt screen buffer cursor\n          this.saveCursor();\n          // FALL-THROUGH\n        case 47: // alt screen buffer\n        case 1047: // alt screen buffer\n          this._bufferService.buffers.activateAltBuffer(this._terminal.eraseAttrData());\n          this._terminal.refresh(0, this._bufferService.rows - 1);\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          this._terminal.showCursor();\n          break;\n        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n          this._terminal.bracketedPasteMode = true;\n          break;\n      }\n    }\n  }\n\n\n  /**\n   * CSI Pm l  Reset Mode (RM).\n   *     Ps = 2  -> Keyboard Action Mode (AM).\n   *     Ps = 4  -> Replace Mode (IRM).\n   *     Ps = 1 2  -> Send/receive (SRM).\n   *     Ps = 2 0  -> Normal Linefeed (LNM).\n   * CSI ? Pm l\n   *   DEC Private Mode Reset (DECRST).\n   *     Ps = 1  -> Normal Cursor Keys (DECCKM).\n   *     Ps = 2  -> Designate VT52 mode (DECANM).\n   *     Ps = 3  -> 80 Column Mode (DECCOLM).\n   *     Ps = 4  -> Jump (Fast) Scroll (DECSCLM).\n   *     Ps = 5  -> Normal Video (DECSCNM).\n   *     Ps = 6  -> Normal Cursor Mode (DECOM).\n   *     Ps = 7  -> No Wraparound Mode (DECAWM).\n   *     Ps = 8  -> No Auto-repeat Keys (DECARM).\n   *     Ps = 9  -> Don't send Mouse X & Y on button press.\n   *     Ps = 1 0  -> Hide toolbar (rxvt).\n   *     Ps = 1 2  -> Stop Blinking Cursor (att610).\n   *     Ps = 1 8  -> Don't print form feed (DECPFF).\n   *     Ps = 1 9  -> Limit print to scrolling region (DECPEX).\n   *     Ps = 2 5  -> Hide Cursor (DECTCEM).\n   *     Ps = 3 0  -> Don't show scrollbar (rxvt).\n   *     Ps = 3 5  -> Disable font-shifting functions (rxvt).\n   *     Ps = 4 0  -> Disallow 80 -> 132 Mode.\n   *     Ps = 4 1  -> No more(1) fix (see curses resource).\n   *     Ps = 4 2  -> Disable Nation Replacement Character sets (DEC-\n   *     NRCM).\n   *     Ps = 4 4  -> Turn Off Margin Bell.\n   *     Ps = 4 5  -> No Reverse-wraparound Mode.\n   *     Ps = 4 6  -> Stop Logging.  (This is normally disabled by a\n   *     compile-time option).\n   *     Ps = 4 7  -> Use Normal Screen Buffer.\n   *     Ps = 6 6  -> Numeric keypad (DECNKM).\n   *     Ps = 6 7  -> Backarrow key sends delete (DECBKM).\n   *     Ps = 1 0 0 0  -> Don't send Mouse X & Y on button press and\n   *     release.  See the section Mouse Tracking.\n   *     Ps = 1 0 0 1  -> Don't use Hilite Mouse Tracking.\n   *     Ps = 1 0 0 2  -> Don't use Cell Motion Mouse Tracking.\n   *     Ps = 1 0 0 3  -> Don't use All Motion Mouse Tracking.\n   *     Ps = 1 0 0 4  -> Don't send FocusIn/FocusOut events.\n   *     Ps = 1 0 0 5  -> Disable Extended Mouse Mode.\n   *     Ps = 1 0 1 0  -> Don't scroll to bottom on tty output\n   *     (rxvt).\n   *     Ps = 1 0 1 1  -> Don't scroll to bottom on key press (rxvt).\n   *     Ps = 1 0 3 4  -> Don't interpret \"meta\" key.  (This disables\n   *     the eightBitInput resource).\n   *     Ps = 1 0 3 5  -> Disable special modifiers for Alt and Num-\n   *     Lock keys.  (This disables the numLock resource).\n   *     Ps = 1 0 3 6  -> Don't send ESC  when Meta modifies a key.\n   *     (This disables the metaSendsEscape resource).\n   *     Ps = 1 0 3 7  -> Send VT220 Remove from the editing-keypad\n   *     Delete key.\n   *     Ps = 1 0 3 9  -> Don't send ESC  when Alt modifies a key.\n   *     (This disables the altSendsEscape resource).\n   *     Ps = 1 0 4 0  -> Do not keep selection when not highlighted.\n   *     (This disables the keepSelection resource).\n   *     Ps = 1 0 4 1  -> Use the PRIMARY selection.  (This disables\n   *     the selectToClipboard resource).\n   *     Ps = 1 0 4 2  -> Disable Urgency window manager hint when\n   *     Control-G is received.  (This disables the bellIsUrgent\n   *     resource).\n   *     Ps = 1 0 4 3  -> Disable raising of the window when Control-\n   *     G is received.  (This disables the popOnBell resource).\n   *     Ps = 1 0 4 7  -> Use Normal Screen Buffer, clearing screen\n   *     first if in the Alternate Screen.  (This may be disabled by\n   *     the titeInhibit resource).\n   *     Ps = 1 0 4 8  -> Restore cursor as in DECRC.  (This may be\n   *     disabled by the titeInhibit resource).\n   *     Ps = 1 0 4 9  -> Use Normal Screen Buffer and restore cursor\n   *     as in DECRC.  (This may be disabled by the titeInhibit\n   *     resource).  This combines the effects of the 1 0 4 7  and 1 0\n   *     4 8  modes.  Use this with terminfo-based applications rather\n   *     than the 4 7  mode.\n   *     Ps = 1 0 5 0  -> Reset terminfo/termcap function-key mode.\n   *     Ps = 1 0 5 1  -> Reset Sun function-key mode.\n   *     Ps = 1 0 5 2  -> Reset HP function-key mode.\n   *     Ps = 1 0 5 3  -> Reset SCO function-key mode.\n   *     Ps = 1 0 6 0  -> Reset legacy keyboard emulation (X11R6).\n   *     Ps = 1 0 6 1  -> Reset keyboard emulation to Sun/PC style.\n   *     Ps = 2 0 0 4  -> Reset bracketed paste mode.\n   */\n  public resetMode(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 4:\n          this._terminal.insertMode = false;\n          break;\n        case 20:\n          // this._t.convertEol = false;\n          break;\n      }\n    }\n  }\n  public resetModePrivate(params: IParams): void {\n    for (let i = 0; i < params.length; i++) {\n      switch (params.params[i]) {\n        case 1:\n          this._coreService.decPrivateModes.applicationCursorKeys = false;\n          break;\n        case 3:\n          // TODO: move DECCOLM into compat addon\n          // Note: This impl currently does not enforce col 80, instead reverts\n          // to previous terminal width before entering DECCOLM 132\n          if (this._bufferService.cols === 132 && this._terminal.savedCols) {\n            this._terminal.resize(this._terminal.savedCols, this._bufferService.rows);\n          }\n          delete this._terminal.savedCols;\n          this._terminal.reset();\n          break;\n        case 6:\n          this._terminal.originMode = false;\n          this._setCursor(0, 0);\n          break;\n        case 7:\n          this._terminal.wraparoundMode = false;\n          break;\n        case 12:\n          // this.cursorBlink = false;\n          break;\n        case 66:\n          this._logService.debug('Switching back to normal keypad.');\n          this._terminal.applicationKeypad = false;\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          break;\n        case 9: // X10 Mouse\n        case 1000: // vt200 mouse\n        case 1002: // button event mouse\n        case 1003: // any event mouse\n          this._coreMouseService.activeProtocol = 'NONE';\n          break;\n        case 1004: // send focusin/focusout events\n          this._terminal.sendFocus = false;\n          break;\n        case 1005: // utf8 ext mode mouse - removed in #2507\n          this._logService.debug('DECRST 1005 not supported (see #2507)');\n          break;\n        case 1006: // sgr ext mode mouse\n          this._coreMouseService.activeEncoding = 'DEFAULT';\n          break;\n        case 1015: // urxvt ext mode mouse - removed in #2507\n        this._logService.debug('DECRST 1015 not supported (see #2507)');\n          break;\n        case 25: // hide cursor\n          this._terminal.cursorHidden = true;\n          break;\n        case 1048: // alt screen cursor\n          this.restoreCursor();\n          break;\n        case 1049: // alt screen buffer cursor\n           // FALL-THROUGH\n        case 47: // normal screen buffer\n        case 1047: // normal screen buffer - clearing it first\n          // Ensure the selection manager has the correct buffer\n          this._bufferService.buffers.activateNormalBuffer();\n          if (params.params[i] === 1049) {\n            this.restoreCursor();\n          }\n          this._terminal.refresh(0, this._bufferService.rows - 1);\n          if (this._terminal.viewport) {\n            this._terminal.viewport.syncScrollArea();\n          }\n          this._terminal.showCursor();\n          break;\n        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)\n          this._terminal.bracketedPasteMode = false;\n          break;\n      }\n    }\n  }\n\n  /**\n   * Helper to extract and apply color params/subparams.\n   * Returns advance for params index.\n   */\n  private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {\n    // normalize params\n    // meaning: [target, CM, ign, val, val, val]\n    // RGB    : [ 38/48,  2, ign,   r,   g,   b]\n    // P256   : [ 38/48,  5, ign,   v, ign, ign]\n    const accu = [0, 0, -1, 0, 0, 0];\n\n    // alignment placeholder for non color space sequences\n    let cSpace = 0;\n\n    // return advance we took in params\n    let advance = 0;\n\n    do {\n      accu[advance + cSpace] = params.params[pos + advance];\n      if (params.hasSubParams(pos + advance)) {\n        const subparams = params.getSubParams(pos + advance);\n        let i = 0;\n        do {\n          if (accu[1] === 5) {\n            cSpace = 1;\n          }\n          accu[advance + i + 1 + cSpace] = subparams[i];\n        } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);\n        break;\n      }\n      // exit early if can decide color mode with semicolons\n      if ((accu[1] === 5 && advance + cSpace >= 2)\n          || (accu[1] === 2 && advance + cSpace >= 5)) {\n        break;\n      }\n      // offset colorSpace slot for semicolon mode\n      if (accu[1]) {\n        cSpace = 1;\n      }\n    } while (++advance + pos < params.length && advance + cSpace < accu.length);\n\n    // set default values to 0\n    for (let i = 2; i < accu.length; ++i) {\n      if (accu[i] === -1) {\n        accu[i] = 0;\n      }\n    }\n\n    // apply colors\n    if (accu[0] === 38) {\n      if (accu[1] === 2) {\n        attr.fg |= Attributes.CM_RGB;\n        attr.fg &= ~Attributes.RGB_MASK;\n        attr.fg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);\n      } else if (accu[1] === 5) {\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.fg |= Attributes.CM_P256 | (accu[3] & 0xff);\n      }\n    } else if (accu[0] === 48) {\n      if (accu[1] === 2) {\n        attr.bg |= Attributes.CM_RGB;\n        attr.bg &= ~Attributes.RGB_MASK;\n        attr.bg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);\n      } else if (accu[1] === 5) {\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.bg |= Attributes.CM_P256 | (accu[3] & 0xff);\n      }\n    }\n\n    return advance;\n  }\n\n  /**\n   * CSI Pm m  Character Attributes (SGR).\n   *     Ps = 0  -> Normal (default).\n   *     Ps = 1  -> Bold.\n   *     Ps = 2  -> Faint, decreased intensity (ISO 6429).\n   *     Ps = 4  -> Underlined.\n   *     Ps = 5  -> Blink (appears as Bold).\n   *     Ps = 7  -> Inverse.\n   *     Ps = 8  -> Invisible, i.e., hidden (VT300).\n   *     Ps = 2 2  -> Normal (neither bold nor faint).\n   *     Ps = 2 4  -> Not underlined.\n   *     Ps = 2 5  -> Steady (not blinking).\n   *     Ps = 2 7  -> Positive (not inverse).\n   *     Ps = 2 8  -> Visible, i.e., not hidden (VT300).\n   *     Ps = 3 0  -> Set foreground color to Black.\n   *     Ps = 3 1  -> Set foreground color to Red.\n   *     Ps = 3 2  -> Set foreground color to Green.\n   *     Ps = 3 3  -> Set foreground color to Yellow.\n   *     Ps = 3 4  -> Set foreground color to Blue.\n   *     Ps = 3 5  -> Set foreground color to Magenta.\n   *     Ps = 3 6  -> Set foreground color to Cyan.\n   *     Ps = 3 7  -> Set foreground color to White.\n   *     Ps = 3 9  -> Set foreground color to default (original).\n   *     Ps = 4 0  -> Set background color to Black.\n   *     Ps = 4 1  -> Set background color to Red.\n   *     Ps = 4 2  -> Set background color to Green.\n   *     Ps = 4 3  -> Set background color to Yellow.\n   *     Ps = 4 4  -> Set background color to Blue.\n   *     Ps = 4 5  -> Set background color to Magenta.\n   *     Ps = 4 6  -> Set background color to Cyan.\n   *     Ps = 4 7  -> Set background color to White.\n   *     Ps = 4 9  -> Set background color to default (original).\n   *\n   *   If 16-color support is compiled, the following apply.  Assume\n   *   that xterm's resources are set so that the ISO color codes are\n   *   the first 8 of a set of 16.  Then the aixterm colors are the\n   *   bright versions of the ISO colors:\n   *     Ps = 9 0  -> Set foreground color to Black.\n   *     Ps = 9 1  -> Set foreground color to Red.\n   *     Ps = 9 2  -> Set foreground color to Green.\n   *     Ps = 9 3  -> Set foreground color to Yellow.\n   *     Ps = 9 4  -> Set foreground color to Blue.\n   *     Ps = 9 5  -> Set foreground color to Magenta.\n   *     Ps = 9 6  -> Set foreground color to Cyan.\n   *     Ps = 9 7  -> Set foreground color to White.\n   *     Ps = 1 0 0  -> Set background color to Black.\n   *     Ps = 1 0 1  -> Set background color to Red.\n   *     Ps = 1 0 2  -> Set background color to Green.\n   *     Ps = 1 0 3  -> Set background color to Yellow.\n   *     Ps = 1 0 4  -> Set background color to Blue.\n   *     Ps = 1 0 5  -> Set background color to Magenta.\n   *     Ps = 1 0 6  -> Set background color to Cyan.\n   *     Ps = 1 0 7  -> Set background color to White.\n   *\n   *   If xterm is compiled with the 16-color support disabled, it\n   *   supports the following, from rxvt:\n   *     Ps = 1 0 0  -> Set foreground and background color to\n   *     default.\n   *\n   *   If 88- or 256-color support is compiled, the following apply.\n   *     Ps = 3 8  ; 5  ; Ps -> Set foreground color to the second\n   *     Ps.\n   *     Ps = 4 8  ; 5  ; Ps -> Set background color to the second\n   *     Ps.\n   */\n  public charAttributes(params: IParams): void {\n    // Optimize a single SGR0.\n    if (params.length === 1 && params.params[0] === 0) {\n      this._terminal.curAttrData.fg = DEFAULT_ATTR_DATA.fg;\n      this._terminal.curAttrData.bg = DEFAULT_ATTR_DATA.bg;\n      return;\n    }\n\n    const l = params.length;\n    let p;\n    const attr = this._terminal.curAttrData;\n\n    for (let i = 0; i < l; i++) {\n      p = params.params[i];\n      if (p >= 30 && p <= 37) {\n        // fg color 8\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.fg |= Attributes.CM_P16 | (p - 30);\n      } else if (p >= 40 && p <= 47) {\n        // bg color 8\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.bg |= Attributes.CM_P16 | (p - 40);\n      } else if (p >= 90 && p <= 97) {\n        // fg color 16\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.fg |= Attributes.CM_P16 | (p - 90) | 8;\n      } else if (p >= 100 && p <= 107) {\n        // bg color 16\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);\n        attr.bg |= Attributes.CM_P16 | (p - 100) | 8;\n      } else if (p === 0) {\n        // default\n        attr.fg = DEFAULT_ATTR_DATA.fg;\n        attr.bg = DEFAULT_ATTR_DATA.bg;\n      } else if (p === 1) {\n        // bold text\n        attr.fg |= FgFlags.BOLD;\n      } else if (p === 3) {\n        // italic text\n        attr.bg |= BgFlags.ITALIC;\n      } else if (p === 4) {\n        // underlined text\n        attr.fg |= FgFlags.UNDERLINE;\n      } else if (p === 5) {\n        // blink\n        attr.fg |= FgFlags.BLINK;\n      } else if (p === 7) {\n        // inverse and positive\n        // test with: echo -e '\\e[31m\\e[42mhello\\e[7mworld\\e[27mhi\\e[m'\n        attr.fg |= FgFlags.INVERSE;\n      } else if (p === 8) {\n        // invisible\n        attr.fg |= FgFlags.INVISIBLE;\n      } else if (p === 2) {\n        // dimmed text\n        attr.bg |= BgFlags.DIM;\n      } else if (p === 22) {\n        // not bold nor faint\n        attr.fg &= ~FgFlags.BOLD;\n        attr.bg &= ~BgFlags.DIM;\n      } else if (p === 23) {\n        // not italic\n        attr.bg &= ~BgFlags.ITALIC;\n      } else if (p === 24) {\n        // not underlined\n        attr.fg &= ~FgFlags.UNDERLINE;\n      } else if (p === 25) {\n        // not blink\n        attr.fg &= ~FgFlags.BLINK;\n      } else if (p === 27) {\n        // not inverse\n        attr.fg &= ~FgFlags.INVERSE;\n      } else if (p === 28) {\n        // not invisible\n        attr.fg &= ~FgFlags.INVISIBLE;\n      } else if (p === 39) {\n        // reset fg\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n      } else if (p === 49) {\n        // reset bg\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n      } else if (p === 38 || p === 48) {\n        // fg color 256 and RGB\n        i += this._extractColor(params, i, attr);\n      } else if (p === 100) {\n        // reset fg/bg\n        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);\n      } else {\n        this._logService.debug('Unknown SGR attribute: %d.', p);\n      }\n    }\n  }\n\n  /**\n   * CSI Ps n  Device Status Report (DSR).\n   *     Ps = 5  -> Status Report.  Result (``OK'') is\n   *   CSI 0 n\n   *     Ps = 6  -> Report Cursor Position (CPR) [row;column].\n   *   Result is\n   *   CSI r ; c R\n   * CSI ? Ps n\n   *   Device Status Report (DSR, DEC-specific).\n   *     Ps = 6  -> Report Cursor Position (CPR) [row;column] as CSI\n   *     ? r ; c R (assumes page is zero).\n   *     Ps = 1 5  -> Report Printer status as CSI ? 1 0  n  (ready).\n   *     or CSI ? 1 1  n  (not ready).\n   *     Ps = 2 5  -> Report UDK status as CSI ? 2 0  n  (unlocked)\n   *     or CSI ? 2 1  n  (locked).\n   *     Ps = 2 6  -> Report Keyboard status as\n   *   CSI ? 2 7  ;  1  ;  0  ;  0  n  (North American).\n   *   The last two parameters apply to VT400 & up, and denote key-\n   *   board ready and LK01 respectively.\n   *     Ps = 5 3  -> Report Locator status as\n   *   CSI ? 5 3  n  Locator available, if compiled-in, or\n   *   CSI ? 5 0  n  No Locator, if not.\n   */\n  public deviceStatus(params: IParams): void {\n    switch (params.params[0]) {\n      case 5:\n        // status report\n        this._coreService.triggerDataEvent(`${C0.ESC}[0n`);\n        break;\n      case 6:\n        // cursor position\n        const y = this._bufferService.buffer.y + 1;\n        const x = this._bufferService.buffer.x + 1;\n        this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);\n        break;\n    }\n  }\n\n  public deviceStatusPrivate(params: IParams): void {\n    // modern xterm doesnt seem to\n    // respond to any of these except ?6, 6, and 5\n    switch (params.params[0]) {\n      case 6:\n        // cursor position\n        const y = this._bufferService.buffer.y + 1;\n        const x = this._bufferService.buffer.x + 1;\n        this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);\n        break;\n      case 15:\n        // no printer\n        // this.handler(C0.ESC + '[?11n');\n        break;\n      case 25:\n        // dont support user defined keys\n        // this.handler(C0.ESC + '[?21n');\n        break;\n      case 26:\n        // north american keyboard\n        // this.handler(C0.ESC + '[?27;1;0;0n');\n        break;\n      case 53:\n        // no dec locator/mouse\n        // this.handler(C0.ESC + '[?50n');\n        break;\n    }\n  }\n\n  /**\n   * CSI ! p   Soft terminal reset (DECSTR).\n   * http://vt100.net/docs/vt220-rm/table4-10.html\n   */\n  public softReset(params: IParams): void {\n    this._terminal.cursorHidden = false;\n    this._terminal.insertMode = false;\n    this._terminal.originMode = false;\n    this._terminal.wraparoundMode = true;  // defaults: xterm - true, vt100 - false\n    this._terminal.applicationKeypad = false; // ?\n    if (this._terminal.viewport) {\n      this._terminal.viewport.syncScrollArea();\n    }\n    this._coreService.decPrivateModes.applicationCursorKeys = false;\n    this._bufferService.buffer.scrollTop = 0;\n    this._bufferService.buffer.scrollBottom = this._bufferService.rows - 1;\n    this._terminal.curAttrData = DEFAULT_ATTR_DATA.clone();\n    this._bufferService.buffer.x = this._bufferService.buffer.y = 0; // ?\n    this._terminal.charset = null;\n    this._terminal.glevel = 0; // ??\n    this._terminal.charsets = [null]; // ??\n  }\n\n  /**\n   * CSI Ps SP q  Set cursor style (DECSCUSR, VT520).\n   *   Ps = 0  -> blinking block.\n   *   Ps = 1  -> blinking block (default).\n   *   Ps = 2  -> steady block.\n   *   Ps = 3  -> blinking underline.\n   *   Ps = 4  -> steady underline.\n   *   Ps = 5  -> blinking bar (xterm).\n   *   Ps = 6  -> steady bar (xterm).\n   */\n  public setCursorStyle(params: IParams): void {\n    const param = params.params[0] || 1;\n    switch (param) {\n      case 1:\n      case 2:\n        this._optionsService.options.cursorStyle = 'block';\n        break;\n      case 3:\n      case 4:\n        this._optionsService.options.cursorStyle = 'underline';\n        break;\n      case 5:\n      case 6:\n        this._optionsService.options.cursorStyle = 'bar';\n        break;\n    }\n    const isBlinking = param % 2 === 1;\n    this._optionsService.options.cursorBlink = isBlinking;\n  }\n\n  /**\n   * CSI Ps ; Ps r\n   *   Set Scrolling Region [top;bottom] (default = full size of win-\n   *   dow) (DECSTBM).\n   */\n  public setScrollRegion(params: IParams): void {\n    const top = params.params[0] || 1;\n    let bottom: number;\n\n    if (params.length < 2 || (bottom = params.params[1]) >  this._bufferService.rows || bottom === 0) {\n      bottom = this._bufferService.rows;\n    }\n\n    if (bottom > top) {\n      this._bufferService.buffer.scrollTop = top - 1;\n      this._bufferService.buffer.scrollBottom = bottom - 1;\n      this._setCursor(0, 0);\n    }\n  }\n\n\n  /**\n   * CSI s\n   * ESC 7\n   *   Save cursor (ANSI.SYS).\n   */\n  public saveCursor(params?: IParams): void {\n    this._bufferService.buffer.savedX = this._bufferService.buffer.x;\n    this._bufferService.buffer.savedY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;\n    this._bufferService.buffer.savedCurAttrData.fg = this._terminal.curAttrData.fg;\n    this._bufferService.buffer.savedCurAttrData.bg = this._terminal.curAttrData.bg;\n    this._bufferService.buffer.savedCharset = this._terminal.charset;\n  }\n\n\n  /**\n   * CSI u\n   * ESC 8\n   *   Restore cursor (ANSI.SYS).\n   */\n  public restoreCursor(params?: IParams): void {\n    this._bufferService.buffer.x = this._bufferService.buffer.savedX || 0;\n    this._bufferService.buffer.y = Math.max(this._bufferService.buffer.savedY - this._bufferService.buffer.ybase, 0);\n    this._terminal.curAttrData.fg = this._bufferService.buffer.savedCurAttrData.fg;\n    this._terminal.curAttrData.bg = this._bufferService.buffer.savedCurAttrData.bg;\n    this._terminal.charset = (this as any)._savedCharset;\n    if (this._bufferService.buffer.savedCharset) {\n      this._terminal.charset = this._bufferService.buffer.savedCharset;\n    }\n    this._restrictCursor();\n  }\n\n\n  /**\n   * OSC 0; <data> ST (set icon name + window title)\n   * OSC 2; <data> ST (set window title)\n   *   Proxy to set window title. Icon name is not supported.\n   */\n  public setTitle(data: string): void {\n    this._terminal.handleTitle(data);\n  }\n\n  /**\n   * ESC E\n   * C1.NEL\n   *   DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)\n   *   Moves cursor to first position on next line.\n   */\n  public nextLine(): void {\n    this._bufferService.buffer.x = 0;\n    this.index();\n  }\n\n  /**\n   * ESC =\n   *   DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)\n   *   Enables the numeric keypad to send application sequences to the host.\n   */\n  public keypadApplicationMode(): void {\n    this._logService.debug('Serial port requested application keypad.');\n    this._terminal.applicationKeypad = true;\n    if (this._terminal.viewport) {\n      this._terminal.viewport.syncScrollArea();\n    }\n  }\n\n  /**\n   * ESC >\n   *   DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)\n   *   Enables the keypad to send numeric characters to the host.\n   */\n  public keypadNumericMode(): void {\n    this._logService.debug('Switching back to normal keypad.');\n    this._terminal.applicationKeypad = false;\n    if (this._terminal.viewport) {\n      this._terminal.viewport.syncScrollArea();\n    }\n  }\n\n  /**\n   * ESC % @\n   * ESC % G\n   *   Select default character set. UTF-8 is not supported (string are unicode anyways)\n   *   therefore ESC % G does the same.\n   */\n  public selectDefaultCharset(): void {\n    this._terminal.setgLevel(0);\n    this._terminal.setgCharset(0, DEFAULT_CHARSET); // US (default)\n  }\n\n  /**\n   * ESC ( C\n   *   Designate G0 Character Set, VT100, ISO 2022.\n   * ESC ) C\n   *   Designate G1 Character Set (ISO 2022, VT100).\n   * ESC * C\n   *   Designate G2 Character Set (ISO 2022, VT220).\n   * ESC + C\n   *   Designate G3 Character Set (ISO 2022, VT220).\n   * ESC - C\n   *   Designate G1 Character Set (VT300).\n   * ESC . C\n   *   Designate G2 Character Set (VT300).\n   * ESC / C\n   *   Designate G3 Character Set (VT300). C = A  -> ISO Latin-1 Supplemental. - Supported?\n   */\n  public selectCharset(collectAndFlag: string): void {\n    if (collectAndFlag.length !== 2) {\n      this.selectDefaultCharset();\n      return;\n    }\n    if (collectAndFlag[0] === '/') {\n      return;  // TODO: Is this supported?\n    }\n    this._terminal.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);\n    return;\n  }\n\n  /**\n   * ESC D\n   * C1.IND\n   *   DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)\n   *   Moves the cursor down one line in the same column.\n   */\n  public index(): void {\n    this._restrictCursor();\n    const buffer = this._bufferService.buffer;\n    this._bufferService.buffer.y++;\n    if (buffer.y === buffer.scrollBottom + 1) {\n      buffer.y--;\n      this._terminal.scroll();\n    } else if (buffer.y >= this._bufferService.rows) {\n      buffer.y = this._bufferService.rows - 1;\n    }\n    this._restrictCursor();\n  }\n\n  /**\n   * ESC H\n   * C1.HTS\n   *   DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)\n   *   Sets a horizontal tab stop at the column position indicated by\n   *   the value of the active column when the terminal receives an HTS.\n   */\n  public tabSet(): void {\n    this._bufferService.buffer.tabs[this._bufferService.buffer.x] = true;\n  }\n\n  /**\n   * ESC M\n   * C1.RI\n   *   DEC mnemonic: HTS\n   *   Moves the cursor up one line in the same column. If the cursor is at the top margin,\n   *   the page scrolls down.\n   */\n  public reverseIndex(): void {\n    this._restrictCursor();\n    const buffer = this._bufferService.buffer;\n    if (buffer.y === buffer.scrollTop) {\n      // possibly move the code below to term.reverseScroll();\n      // test: echo -ne '\\e[1;1H\\e[44m\\eM\\e[0m'\n      // blankLine(true) is xterm/linux behavior\n      const scrollRegionHeight = buffer.scrollBottom - buffer.scrollTop;\n      buffer.lines.shiftElements(buffer.y + buffer.ybase, scrollRegionHeight, 1);\n      buffer.lines.set(buffer.y + buffer.ybase, buffer.getBlankLine(this._terminal.eraseAttrData()));\n      this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);\n    } else {\n      buffer.y--;\n      this._restrictCursor(); // quickfix to not run out of bounds\n    }\n  }\n\n  /**\n   * ESC c\n   *   DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)\n   *   Reset to initial state.\n   */\n  public reset(): void {\n    this._parser.reset();\n    this._terminal.reset();  // TODO: save to move from terminal?\n  }\n\n  /**\n   * ESC n\n   * ESC o\n   * ESC |\n   * ESC }\n   * ESC ~\n   *   DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)\n   *   When you use a locking shift, the character set remains in GL or GR until\n   *   you use another locking shift. (partly supported)\n   */\n  public setgLevel(level: number): void {\n    this._terminal.setgLevel(level);  // TODO: save to move from terminal?\n  }\n\n  /**\n   * ESC # 8\n   *   DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)\n   *   This control function fills the complete screen area with\n   *   a test pattern (E) used for adjusting screen alignment.\n   *\n   * TODO: move DECALN into compat addon\n   */\n  public screenAlignmentPattern(): void {\n    // prepare cell data\n    const cell = new CellData();\n    cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);\n    cell.fg = this._terminal.curAttrData.fg;\n    cell.bg = this._terminal.curAttrData.bg;\n\n    const buffer = this._bufferService.buffer;\n\n    this._setCursor(0, 0);\n    for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {\n      const row = buffer.y + buffer.ybase + yOffset;\n      buffer.lines.get(row).fill(cell);\n      buffer.lines.get(row).isWrapped = false;\n    }\n    this._dirtyRowService.markAllDirty();\n    this._setCursor(0, 0);\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType } from 'common/parser/Types';\nimport { ParserState, ParserAction } from 'common/parser/Constants';\nimport { Disposable } from 'common/Lifecycle';\nimport { IDisposable } from 'common/Types';\nimport { fill } from 'common/TypedArrayUtils';\nimport { Params } from 'common/parser/Params';\nimport { OscParser } from 'common/parser/OscParser';\nimport { DcsParser } from 'common/parser/DcsParser';\n\n/**\n * Table values are generated like this:\n *    index:  currentState << TableValue.INDEX_STATE_SHIFT | charCode\n *    value:  action << TableValue.TRANSITION_ACTION_SHIFT | nextState\n */\nconst enum TableAccess {\n  TRANSITION_ACTION_SHIFT = 4,\n  TRANSITION_STATE_MASK = 15,\n  INDEX_STATE_SHIFT = 8\n}\n\n/**\n * Transition table for EscapeSequenceParser.\n */\nexport class TransitionTable {\n  public table: Uint8Array;\n\n  constructor(length: number) {\n    this.table = new Uint8Array(length);\n  }\n\n  /**\n   * Set default transition.\n   * @param action default action\n   * @param next default next state\n   */\n  public setDefault(action: ParserAction, next: ParserState): void {\n    fill(this.table, action << TableAccess.TRANSITION_ACTION_SHIFT | next);\n  }\n\n  /**\n   * Add a transition to the transition table.\n   * @param code input character code\n   * @param state current parser state\n   * @param action parser action to be done\n   * @param next next parser state\n   */\n  public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {\n    this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n  }\n\n  /**\n   * Add transitions for multiple input character codes.\n   * @param codes input character code array\n   * @param state current parser state\n   * @param action parser action to be done\n   * @param next next parser state\n   */\n  public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {\n    for (let i = 0; i < codes.length; i++) {\n      this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;\n    }\n  }\n}\n\n\n// Pseudo-character placeholder for printable non-ascii characters (unicode).\nconst NON_ASCII_PRINTABLE = 0xA0;\n\n\n/**\n * VT500 compatible transition table.\n * Taken from https://vt100.net/emu/dec_ansi_parser.\n */\nexport const VT500_TRANSITION_TABLE = (function (): TransitionTable {\n  const table: TransitionTable = new TransitionTable(4095);\n\n  // range macro for byte\n  const BYTE_VALUES = 256;\n  const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);\n  const r = (start: number, end: number) => blueprint.slice(start, end);\n\n  // Default definitions.\n  const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded\n  const EXECUTABLES = r(0x00, 0x18);\n  EXECUTABLES.push(0x19);\n  EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));\n\n  const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);\n  let state: any;\n\n  // set default transition\n  table.setDefault(ParserAction.ERROR, ParserState.GROUND);\n  // printables\n  table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n  // global anywhere rules\n  for (state in states) {\n    table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);\n    table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);\n    table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);\n    table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator\n    table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE);  // ESC\n    table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING);  // OSC\n    table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n    table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY);  // CSI\n    table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY);  // DCS\n  }\n  // rules for executables and 7f\n  table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);\n  table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);\n  table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);\n  table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n  table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);\n  table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);\n  table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);\n  table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);\n  table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);\n  table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);\n  table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);\n  table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);\n  table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);\n  // osc\n  table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);\n  table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n  table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n  table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);\n  table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);\n  // sos/pm/apc does nothing\n  table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);\n  table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);\n  // csi entries\n  table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);\n  table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);\n  table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n  table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n  table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);\n  // esc_intermediate\n  table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n  table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);\n  table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);\n  // dcs entry\n  table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);\n  table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n  table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);\n  table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);\n  table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n  table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);\n  table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);\n  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n  table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n  table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);\n  table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n  table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n  table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);\n  table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n  table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n  table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);\n  table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);\n  // special handling of unicode chars\n  table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);\n  table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);\n  table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);\n  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);\n  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);\n  return table;\n})();\n\n\n/**\n * EscapeSequenceParser.\n * This class implements the ANSI/DEC compatible parser described by\n * Paul Williams (https://vt100.net/emu/dec_ansi_parser).\n *\n * To implement custom ANSI compliant escape sequences it is not needed to\n * alter this parser, instead consider registering a custom handler.\n * For non ANSI compliant sequences change the transition table with\n * the optional `transitions` constructor argument and\n * reimplement the `parse` method.\n *\n * This parser is currently hardcoded to operate in ZDM (Zero Default Mode)\n * as suggested by the original parser, thus empty parameters are set to 0.\n * This this is not in line with the latest ECMA-48 specification\n * (ZDM was part of the early specs and got completely removed later on).\n *\n * Other than the original parser from vt100.net this parser supports\n * sub parameters in digital parameters separated by colons. Empty sub parameters\n * are set to -1 (no ZDM for sub parameters).\n *\n * About prefix and intermediate bytes:\n * This parser follows the assumptions of the vt100.net parser with these restrictions:\n * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f\n * - max. two intermediates are respected, byte range 0x20 .. 0x2f\n * Note that this is not in line with ECMA-48 which does not limit either of those.\n * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently\n * there are no known sequences that follow the broader definition of the specification.\n *\n * TODO: implement error recovery hook via error handler return values\n */\nexport class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {\n  public initialState: number;\n  public currentState: number;\n  public precedingCodepoint: number;\n\n  // buffers over several parse calls\n  protected _params: Params;\n  protected _collect: number;\n\n  // handler lookup containers\n  protected _printHandler: PrintHandlerType;\n  protected _executeHandlers: {[flag: number]: ExecuteHandlerType};\n  protected _csiHandlers: IHandlerCollection<CsiHandlerType>;\n  protected _escHandlers: IHandlerCollection<EscHandlerType>;\n  protected _oscParser: IOscParser;\n  protected _dcsParser: IDcsParser;\n  protected _errorHandler: (state: IParsingState) => IParsingState;\n\n  // fallback handlers\n  protected _printHandlerFb: PrintFallbackHandlerType;\n  protected _executeHandlerFb: ExecuteFallbackHandlerType;\n  protected _csiHandlerFb: CsiFallbackHandlerType;\n  protected _escHandlerFb: EscFallbackHandlerType;\n  protected _errorHandlerFb: (state: IParsingState) => IParsingState;\n\n  constructor(readonly TRANSITIONS: TransitionTable = VT500_TRANSITION_TABLE) {\n    super();\n\n    this.initialState = ParserState.GROUND;\n    this.currentState = this.initialState;\n    this._params = new Params(); // defaults to 32 storable params/subparams\n    this._params.addParam(0);    // ZDM\n    this._collect = 0;\n    this.precedingCodepoint = 0;\n\n    // set default fallback handlers and handler lookup containers\n    this._printHandlerFb = (data, start, end): void => { };\n    this._executeHandlerFb = (code: number): void => { };\n    this._csiHandlerFb = (ident: number, params: IParams): void => { };\n    this._escHandlerFb = (ident: number): void => { };\n    this._errorHandlerFb = (state: IParsingState): IParsingState => state;\n    this._printHandler = this._printHandlerFb;\n    this._executeHandlers = Object.create(null);\n    this._csiHandlers = Object.create(null);\n    this._escHandlers = Object.create(null);\n    this._oscParser = new OscParser();\n    this._dcsParser = new DcsParser();\n    this._errorHandler = this._errorHandlerFb;\n\n    // swallow 7bit ST (ESC+\\)\n    this.setEscHandler({final: '\\\\'}, () => {});\n  }\n\n  protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {\n    let res = 0;\n    if (id.prefix) {\n      if (id.prefix.length > 1) {\n        throw new Error('only one byte as prefix supported');\n      }\n      res = id.prefix.charCodeAt(0);\n      if (res && 0x3c > res || res > 0x3f) {\n        throw new Error('prefix must be in range 0x3c .. 0x3f');\n      }\n    }\n    if (id.intermediates) {\n      if (id.intermediates.length > 2) {\n        throw new Error('only two bytes as intermediates are supported');\n      }\n      for (let i = 0; i < id.intermediates.length; ++i) {\n        const intermediate = id.intermediates.charCodeAt(i);\n        if (0x20 > intermediate || intermediate > 0x2f) {\n          throw new Error('intermediate must be in range 0x20 .. 0x2f');\n        }\n        res <<= 8;\n        res |= intermediate;\n      }\n    }\n    if (id.final.length !== 1) {\n      throw new Error('final must be a single byte');\n    }\n    const finalCode = id.final.charCodeAt(0);\n    if (finalRange[0] > finalCode || finalCode > finalRange[1]) {\n      throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);\n    }\n    res <<= 8;\n    res |= finalCode;\n\n    return res;\n  }\n\n  public identToString(ident: number): string {\n    const res: string[] = [];\n    while (ident) {\n      res.push(String.fromCharCode(ident & 0xFF));\n      ident >>= 8;\n    }\n    return res.reverse().join('');\n  }\n\n  public dispose(): void {\n    this._csiHandlers = Object.create(null);\n    this._executeHandlers = Object.create(null);\n    this._escHandlers = Object.create(null);\n    this._oscParser.dispose();\n    this._dcsParser.dispose();\n  }\n\n  public setPrintHandler(handler: PrintHandlerType): void {\n    this._printHandler = handler;\n  }\n  public clearPrintHandler(): void {\n    this._printHandler = this._printHandlerFb;\n  }\n\n  public addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {\n    const ident = this._identifier(id, [0x30, 0x7e]);\n    if (this._escHandlers[ident] === undefined) {\n      this._escHandlers[ident] = [];\n    }\n    const handlerList = this._escHandlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n  public setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void {\n    this._escHandlers[this._identifier(id, [0x30, 0x7e])] = [handler];\n  }\n  public clearEscHandler(id: IFunctionIdentifier): void {\n    if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];\n  }\n  public setEscHandlerFallback(handler: EscFallbackHandlerType): void {\n    this._escHandlerFb = handler;\n  }\n\n  public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {\n    this._executeHandlers[flag.charCodeAt(0)] = handler;\n  }\n  public clearExecuteHandler(flag: string): void {\n    if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];\n  }\n  public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {\n    this._executeHandlerFb = handler;\n  }\n\n  public addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {\n    const ident = this._identifier(id);\n    if (this._csiHandlers[ident] === undefined) {\n      this._csiHandlers[ident] = [];\n    }\n    const handlerList = this._csiHandlers[ident];\n    handlerList.push(handler);\n    return {\n      dispose: () => {\n        const handlerIndex = handlerList.indexOf(handler);\n        if (handlerIndex !== -1) {\n          handlerList.splice(handlerIndex, 1);\n        }\n      }\n    };\n  }\n  public setCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): void {\n    this._csiHandlers[this._identifier(id)] = [handler];\n  }\n  public clearCsiHandler(id: IFunctionIdentifier): void {\n    if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];\n  }\n  public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {\n    this._csiHandlerFb = callback;\n  }\n\n  public addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {\n    return this._dcsParser.addHandler(this._identifier(id), handler);\n  }\n  public setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void {\n    this._dcsParser.setHandler(this._identifier(id), handler);\n  }\n  public clearDcsHandler(id: IFunctionIdentifier): void {\n    this._dcsParser.clearHandler(this._identifier(id));\n  }\n  public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {\n    this._dcsParser.setHandlerFallback(handler);\n  }\n\n  public addOscHandler(ident: number, handler: IOscHandler): IDisposable {\n    return this._oscParser.addHandler(ident, handler);\n  }\n  public setOscHandler(ident: number, handler: IOscHandler): void {\n    this._oscParser.setHandler(ident, handler);\n  }\n  public clearOscHandler(ident: number): void {\n    this._oscParser.clearHandler(ident);\n  }\n  public setOscHandlerFallback(handler: OscFallbackHandlerType): void {\n    this._oscParser.setHandlerFallback(handler);\n  }\n\n  public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {\n    this._errorHandler = callback;\n  }\n  public clearErrorHandler(): void {\n    this._errorHandler = this._errorHandlerFb;\n  }\n\n  public reset(): void {\n    this.currentState = this.initialState;\n    this._oscParser.reset();\n    this._dcsParser.reset();\n    this._params.reset();\n    this._params.addParam(0); // ZDM\n    this._collect = 0;\n    this.precedingCodepoint = 0;\n  }\n\n\n\n  /**\n   * Parse UTF32 codepoints in `data` up to `length`.\n   *\n   * Note: For several actions with high data load the parsing is optimized\n   * by using local read ahead loops with hardcoded conditions to\n   * avoid costly table lookups. Make sure that any change of table values\n   * will be reflected in the loop conditions as well and vice versa.\n   * Affected states/actions:\n   * - GROUND:PRINT\n   * - CSI_PARAM:PARAM\n   * - DCS_PARAM:PARAM\n   * - OSC_STRING:OSC_PUT\n   * - DCS_PASSTHROUGH:DCS_PUT\n   */\n  public parse(data: Uint32Array, length: number): void {\n    let code = 0;\n    let transition = 0;\n    let currentState = this.currentState;\n    const osc = this._oscParser;\n    const dcs = this._dcsParser;\n    let collect = this._collect;\n    const params = this._params;\n    const table: Uint8Array = this.TRANSITIONS.table;\n\n    // process input string\n    for (let i = 0; i < length; ++i) {\n      code = data[i];\n\n      // normal transition & action lookup\n      transition = table[currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];\n      switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {\n        case ParserAction.PRINT:\n          // read ahead with loop unrolling\n          // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded\n          for (let j = i + 1; ; ++j) {\n            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {\n              this._printHandler(data, i, j);\n              i = j - 1;\n              break;\n            }\n          }\n          break;\n        case ParserAction.EXECUTE:\n          if (this._executeHandlers[code]) this._executeHandlers[code]();\n          else this._executeHandlerFb(code);\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.IGNORE:\n          break;\n        case ParserAction.ERROR:\n          const inject: IParsingState = this._errorHandler(\n            {\n              position: i,\n              code,\n              currentState,\n              collect,\n              params,\n              abort: false\n            });\n          if (inject.abort) return;\n          // inject values: currently not implemented\n          break;\n        case ParserAction.CSI_DISPATCH:\n          // Trigger CSI Handler\n          const handlers = this._csiHandlers[collect << 8 | code];\n          let j = handlers ? handlers.length - 1 : -1;\n          for (; j >= 0; j--) {\n            // undefined or true means success and to stop bubbling\n            if (handlers[j](params) !== false) {\n              break;\n            }\n          }\n          if (j < 0) {\n            this._csiHandlerFb(collect << 8 | code, params);\n          }\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.PARAM:\n          // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)\n          do {\n            switch (code) {\n              case 0x3b:\n                params.addParam(0);  // ZDM\n                break;\n              case 0x3a:\n                params.addSubParam(-1);\n                break;\n              default:  // 0x30 - 0x39\n                params.addDigit(code - 48);\n            }\n          } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);\n          i--;\n          break;\n        case ParserAction.COLLECT:\n          collect <<= 8;\n          collect |= code;\n          break;\n        case ParserAction.ESC_DISPATCH:\n          const handlersEsc = this._escHandlers[collect << 8 | code];\n          let jj = handlersEsc ? handlersEsc.length - 1 : -1;\n          for (; jj >= 0; jj--) {\n            // undefined or true means success and to stop bubbling\n            if (handlersEsc[jj]() !== false) {\n              break;\n            }\n          }\n          if (jj < 0) {\n            this._escHandlerFb(collect << 8 | code);\n          }\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.CLEAR:\n          params.reset();\n          params.addParam(0); // ZDM\n          collect = 0;\n          break;\n        case ParserAction.DCS_HOOK:\n          dcs.hook(collect << 8 | code, params);\n          break;\n        case ParserAction.DCS_PUT:\n          // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f\n          // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)\n          for (let j = i + 1; ; ++j) {\n            if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {\n              dcs.put(data, i, j);\n              i = j - 1;\n              break;\n            }\n          }\n          break;\n        case ParserAction.DCS_UNHOOK:\n          dcs.unhook(code !== 0x18 && code !== 0x1a);\n          if (code === 0x1b) transition |= ParserState.ESCAPE;\n          params.reset();\n          params.addParam(0); // ZDM\n          collect = 0;\n          this.precedingCodepoint = 0;\n          break;\n        case ParserAction.OSC_START:\n          osc.start();\n          break;\n        case ParserAction.OSC_PUT:\n          // inner loop: 0x20 (SP) included, 0x7F (DEL) included\n          for (let j = i + 1; ; j++) {\n            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code <= 0x9f)) {\n              osc.put(data, i, j);\n              i = j - 1;\n              break;\n            }\n          }\n          break;\n        case ParserAction.OSC_END:\n          osc.end(code !== 0x18 && code !== 0x1a);\n          if (code === 0x1b) transition |= ParserState.ESCAPE;\n          params.reset();\n          params.addParam(0); // ZDM\n          collect = 0;\n          this.precedingCodepoint = 0;\n          break;\n      }\n      currentState = transition & TableAccess.TRANSITION_STATE_MASK;\n    }\n\n    // save collected intermediates\n    this._collect = collect;\n\n    // save state\n    this.currentState = currentState;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { TextRenderLayer } from '../browser/renderer/TextRenderLayer';\nimport { SelectionRenderLayer } from '../browser/renderer/SelectionRenderLayer';\nimport { CursorRenderLayer } from './CursorRenderLayer';\nimport { IRenderLayer, IRenderer, IRenderDimensions, CharacterJoinerHandler, ICharacterJoinerRegistry } from 'browser/renderer/Types';\nimport { ITerminal } from '../Types';\nimport { LinkRenderLayer } from '../browser/renderer/LinkRenderLayer';\nimport { CharacterJoinerRegistry } from 'browser/renderer/CharacterJoinerRegistry';\nimport { Disposable } from 'common/Lifecycle';\nimport { IColorSet } from 'browser/Types';\nimport { ICharSizeService } from 'browser/services/Services';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { removeTerminalFromCache } from 'browser/renderer/atlas/CharAtlasCache';\n\nlet nextRendererId = 1;\n\nexport class Renderer extends Disposable implements IRenderer {\n  private _id = nextRendererId++;\n\n  private _renderLayers: IRenderLayer[];\n  private _devicePixelRatio: number;\n  private _characterJoinerRegistry: ICharacterJoinerRegistry;\n\n  public dimensions: IRenderDimensions;\n\n  constructor(\n    private _colors: IColorSet,\n    private readonly _terminal: ITerminal,\n    readonly bufferService: IBufferService,\n    private readonly _charSizeService: ICharSizeService,\n    readonly optionsService: IOptionsService\n  ) {\n    super();\n    const allowTransparency = this._terminal.options.allowTransparency;\n    this._characterJoinerRegistry = new CharacterJoinerRegistry(bufferService);\n\n    this._renderLayers = [\n      new TextRenderLayer(this._terminal.screenElement, 0, this._colors, this._characterJoinerRegistry, allowTransparency, this._id, bufferService, optionsService),\n      new SelectionRenderLayer(this._terminal.screenElement, 1, this._colors, this._id, bufferService, optionsService),\n      new LinkRenderLayer(this._terminal.screenElement, 2, this._colors, this._id, this._terminal.linkifier, bufferService, optionsService),\n      new CursorRenderLayer(this._terminal.screenElement, 3, this._colors, this._terminal, this._id, bufferService, optionsService)\n    ];\n    this.dimensions = {\n      scaledCharWidth: null,\n      scaledCharHeight: null,\n      scaledCellWidth: null,\n      scaledCellHeight: null,\n      scaledCharLeft: null,\n      scaledCharTop: null,\n      scaledCanvasWidth: null,\n      scaledCanvasHeight: null,\n      canvasWidth: null,\n      canvasHeight: null,\n      actualCellWidth: null,\n      actualCellHeight: null\n    };\n    this._devicePixelRatio = window.devicePixelRatio;\n    this._updateDimensions();\n    this.onOptionsChanged();\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this._renderLayers.forEach(l => l.dispose());\n    removeTerminalFromCache(this._id);\n  }\n\n  public onDevicePixelRatioChange(): void {\n    // If the device pixel ratio changed, the char atlas needs to be regenerated\n    // and the terminal needs to refreshed\n    if (this._devicePixelRatio !== window.devicePixelRatio) {\n      this._devicePixelRatio = window.devicePixelRatio;\n      this.onResize(this._terminal.cols, this._terminal.rows);\n    }\n  }\n\n  public setColors(colors: IColorSet): void {\n    this._colors = colors;\n\n    // Clear layers and force a full render\n    this._renderLayers.forEach(l => {\n      l.setColors(this._colors);\n      l.reset();\n    });\n  }\n\n  public onResize(cols: number, rows: number): void {\n    // Update character and canvas dimensions\n    this._updateDimensions();\n\n    // Resize all render layers\n    this._renderLayers.forEach(l => l.resize(this.dimensions));\n\n    // Resize the screen\n    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;\n    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;\n  }\n\n  public onCharSizeChanged(): void {\n    this.onResize(this._terminal.cols, this._terminal.rows);\n  }\n\n  public onBlur(): void {\n    this._runOperation(l => l.onBlur());\n  }\n\n  public onFocus(): void {\n    this._runOperation(l => l.onFocus());\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {\n    this._runOperation(l => l.onSelectionChanged(start, end, columnSelectMode));\n  }\n\n  public onCursorMove(): void {\n    this._runOperation(l => l.onCursorMove());\n  }\n\n  public onOptionsChanged(): void {\n    this._runOperation(l => l.onOptionsChanged());\n  }\n\n  public clear(): void {\n    this._runOperation(l => l.reset());\n  }\n\n  private _runOperation(operation: (layer: IRenderLayer) => void): void {\n    this._renderLayers.forEach(l => operation(l));\n  }\n\n  /**\n   * Performs the refresh loop callback, calling refresh only if a refresh is\n   * necessary before queueing up the next one.\n   */\n  public renderRows(start: number, end: number): void {\n    this._renderLayers.forEach(l => l.onGridChanged(start, end));\n  }\n\n  /**\n   * Recalculates the character and canvas dimensions.\n   */\n  private _updateDimensions(): void {\n    if (!this._charSizeService.hasValidSize) {\n      return;\n    }\n\n    // Calculate the scaled character width. Width is floored as it must be\n    // drawn to an integer grid in order for the CharAtlas \"stamps\" to not be\n    // blurry. When text is drawn to the grid not using the CharAtlas, it is\n    // clipped to ensure there is no overlap with the next cell.\n    this.dimensions.scaledCharWidth = Math.floor(this._charSizeService.width * window.devicePixelRatio);\n\n    // Calculate the scaled character height. Height is ceiled in case\n    // devicePixelRatio is a floating point number in order to ensure there is\n    // enough space to draw the character to the cell.\n    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);\n\n    // Calculate the scaled cell height, if lineHeight is not 1 then the value\n    // will be floored because since lineHeight can never be lower then 1, there\n    // is a guarentee that the scaled line height will always be larger than\n    // scaled char height.\n    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);\n\n    // Calculate the y coordinate within a cell that text should draw from in\n    // order to draw in the center of a cell.\n    this.dimensions.scaledCharTop = this._terminal.options.lineHeight === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2);\n\n    // Calculate the scaled cell width, taking the letterSpacing into account.\n    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);\n\n    // Calculate the x coordinate with a cell that text should draw from in\n    // order to draw in the center of a cell.\n    this.dimensions.scaledCharLeft = Math.floor(this._terminal.options.letterSpacing / 2);\n\n    // Recalculate the canvas dimensions; scaled* define the actual number of\n    // pixel in the canvas\n    this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight;\n    this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth;\n\n    // The the size of the canvas on the page. It's very important that this\n    // rounds to nearest integer and not ceils as browsers often set\n    // window.devicePixelRatio as something like 1.100000023841858, when it's\n    // actually 1.1. Ceiling causes blurriness as the backing canvas image is 1\n    // pixel too large for the canvas element size.\n    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);\n    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);\n\n    // Get the _actual_ dimensions of an individual cell. This needs to be\n    // derived from the canvasWidth/Height calculated above which takes into\n    // account window.devicePixelRatio. ICharSizeService.width/height by itself\n    // is insufficient when the page is not at 100% zoom level as it's measured\n    // in CSS pixels, but the actual char size on the canvas can differ.\n    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;\n    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n    return this._characterJoinerRegistry.registerCharacterJoiner(handler);\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): boolean {\n    return this._characterJoinerRegistry.deregisterCharacterJoiner(joinerId);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharacterJoinerRegistry, IRenderDimensions } from 'browser/renderer/Types';\nimport { CharData, ICellData } from 'common/Types';\nimport { GridCache } from 'browser/renderer/GridCache';\nimport { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { NULL_CELL_CODE, Content } from 'common/buffer/Constants';\nimport { JoinedCellData } from 'browser/renderer/CharacterJoinerRegistry';\nimport { IColorSet } from 'browser/Types';\nimport { CellData } from 'common/buffer/CellData';\nimport { IOptionsService, IBufferService } from 'common/services/Services';\n\n/**\n * This CharData looks like a null character, which will forc a clear and render\n * when the character changes (a regular space ' ' character may not as it's\n * drawn state is a cleared cell).\n */\n// const OVERLAP_OWNED_CHAR_DATA: CharData = [null, '', 0, -1];\n\nexport class TextRenderLayer extends BaseRenderLayer {\n  private _state: GridCache<CharData>;\n  private _characterWidth: number = 0;\n  private _characterFont: string = '';\n  private _characterOverlapCache: { [key: string]: boolean } = {};\n  private _characterJoinerRegistry: ICharacterJoinerRegistry;\n  private _workCell = new CellData();\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    characterJoinerRegistry: ICharacterJoinerRegistry,\n    alpha: boolean,\n    rendererId: number,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'text', zIndex, alpha, colors, rendererId, bufferService, optionsService);\n    this._state = new GridCache<CharData>();\n    this._characterJoinerRegistry = characterJoinerRegistry;\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n\n    // Clear the character width cache if the font or width has changed\n    const terminalFont = this._getFont(false, false);\n    if (this._characterWidth !== dim.scaledCharWidth || this._characterFont !== terminalFont) {\n      this._characterWidth = dim.scaledCharWidth;\n      this._characterFont = terminalFont;\n      this._characterOverlapCache = {};\n    }\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._state.clear();\n    this._state.resize(this._bufferService.cols, this._bufferService.rows);\n  }\n\n  public reset(): void {\n    this._state.clear();\n    this._clearAll();\n  }\n\n  private _forEachCell(\n    firstRow: number,\n    lastRow: number,\n    joinerRegistry: ICharacterJoinerRegistry | null,\n    callback: (\n      cell: ICellData,\n      x: number,\n      y: number\n    ) => void\n  ): void {\n    for (let y = firstRow; y <= lastRow; y++) {\n      const row = y + this._bufferService.buffer.ydisp;\n      const line = this._bufferService.buffer.lines.get(row);\n      const joinedRanges = joinerRegistry ? joinerRegistry.getJoinedCharacters(row) : [];\n      for (let x = 0; x < this._bufferService.cols; x++) {\n        line!.loadCell(x, this._workCell);\n        let cell = this._workCell;\n\n        // If true, indicates that the current character(s) to draw were joined.\n        let isJoined = false;\n        let lastCharX = x;\n\n        // The character to the left is a wide character, drawing is owned by\n        // the char at x-1\n        if (cell.getWidth() === 0) {\n          continue;\n        }\n\n        // Process any joined character ranges as needed. Because of how the\n        // ranges are produced, we know that they are valid for the characters\n        // and attributes of our input.\n        if (joinedRanges.length > 0 && x === joinedRanges[0][0]) {\n          isJoined = true;\n          const range = joinedRanges.shift()!;\n\n          // We already know the exact start and end column of the joined range,\n          // so we get the string and width representing it directly\n\n          cell = new JoinedCellData(\n            this._workCell,\n            line!.translateToString(true, range[0], range[1]),\n            range[1] - range[0]\n          );\n\n          // Skip over the cells occupied by this range in the loop\n          lastCharX = range[1] - 1;\n        }\n\n        // If the character is an overlapping char and the character to the\n        // right is a space, take ownership of the cell to the right. We skip\n        // this check for joined characters because their rendering likely won't\n        // yield the same result as rendering the last character individually.\n        if (!isJoined && this._isOverlapping(cell)) {\n          // If the character is overlapping, we want to force a re-render on every\n          // frame. This is specifically to work around the case where two\n          // overlaping chars `a` and `b` are adjacent, the cursor is moved to b and a\n          // space is added. Without this, the first half of `b` would never\n          // get removed, and `a` would not re-render because it thinks it's\n          // already in the correct state.\n          // this._state.cache[x][y] = OVERLAP_OWNED_CHAR_DATA;\n          if (lastCharX < line!.length - 1 && line!.getCodePoint(lastCharX + 1) === NULL_CELL_CODE) {\n            // patch width to 2\n            cell.content &= ~Content.WIDTH_MASK;\n            cell.content |= 2 << Content.WIDTH_SHIFT;\n            // this._clearChar(x + 1, y);\n            // The overlapping char's char data will force a clear and render when the\n            // overlapping char is no longer to the left of the character and also when\n            // the space changes to another character.\n            // this._state.cache[x + 1][y] = OVERLAP_OWNED_CHAR_DATA;\n          }\n        }\n\n        callback(\n          cell,\n          x,\n          y\n        );\n\n        x = lastCharX;\n      }\n    }\n  }\n\n  /**\n   * Draws the background for a specified range of columns. Tries to batch adjacent cells of the\n   * same color together to reduce draw calls.\n   */\n  private _drawBackground(firstRow: number, lastRow: number): void {\n    const ctx = this._ctx;\n    const cols = this._bufferService.cols;\n    let startX: number = 0;\n    let startY: number = 0;\n    let prevFillStyle: string | null = null;\n\n    ctx.save();\n\n    this._forEachCell(firstRow, lastRow, null, (cell, x, y) => {\n      // libvte and xterm both draw the background (but not foreground) of invisible characters,\n      // so we should too.\n      let nextFillStyle = null; // null represents default background color\n\n      if (cell.isInverse()) {\n        if (cell.isFgDefault()) {\n          nextFillStyle = this._colors.foreground.css;\n        } else if (cell.isFgRGB()) {\n          nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;\n        } else {\n          nextFillStyle = this._colors.ansi[cell.getFgColor()].css;\n        }\n      } else if (cell.isBgRGB()) {\n        nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;\n      } else if (cell.isBgPalette()) {\n        nextFillStyle = this._colors.ansi[cell.getBgColor()].css;\n      }\n\n      if (prevFillStyle === null) {\n        // This is either the first iteration, or the default background was set. Either way, we\n        // don't need to draw anything.\n        startX = x;\n        startY = y;\n      }\n\n      if (y !== startY) {\n        // our row changed, draw the previous row\n        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';\n        this._fillCells(startX, startY, cols - startX, 1);\n        startX = x;\n        startY = y;\n      } else if (prevFillStyle !== nextFillStyle) {\n        // our color changed, draw the previous characters in this row\n        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';\n        this._fillCells(startX, startY, x - startX, 1);\n        startX = x;\n        startY = y;\n      }\n\n      prevFillStyle = nextFillStyle;\n    });\n\n    // flush the last color we encountered\n    if (prevFillStyle !== null) {\n      ctx.fillStyle = prevFillStyle;\n      this._fillCells(startX, startY, cols - startX, 1);\n    }\n\n    ctx.restore();\n  }\n\n  private _drawForeground(firstRow: number, lastRow: number): void {\n    this._forEachCell(firstRow, lastRow, this._characterJoinerRegistry, (cell, x, y) => {\n      if (cell.isInvisible()) {\n        return;\n      }\n      this._drawChars(cell, x, y);\n      if (cell.isUnderline()) {\n        this._ctx.save();\n\n        if (cell.isInverse()) {\n          if (cell.isBgDefault()) {\n            this._ctx.fillStyle = this._colors.background.css;\n          } else if (cell.isBgRGB()) {\n            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;\n          } else {\n            this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;\n          }\n        } else {\n          if (cell.isFgDefault()) {\n            this._ctx.fillStyle = this._colors.foreground.css;\n          } else if (cell.isFgRGB()) {\n            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;\n          } else {\n            let fg = cell.getFgColor();\n            if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {\n              fg += 8;\n            }\n            this._ctx.fillStyle = this._colors.ansi[fg].css;\n          }\n        }\n\n        this._fillBottomLineAtCells(x, y, cell.getWidth());\n        this._ctx.restore();\n      }\n    });\n  }\n\n  public onGridChanged(firstRow: number, lastRow: number): void {\n    // Resize has not been called yet\n    if (this._state.cache.length === 0) {\n      return;\n    }\n\n    if (this._charAtlas) {\n      this._charAtlas.beginFrame();\n    }\n\n    this._clearCells(0, firstRow, this._bufferService.cols, lastRow - firstRow + 1);\n    this._drawBackground(firstRow, lastRow);\n    this._drawForeground(firstRow, lastRow);\n  }\n\n  public onOptionsChanged(): void {\n    this._setTransparency(this._optionsService.options.allowTransparency);\n  }\n\n  /**\n   * Whether a character is overlapping to the next cell.\n   */\n  private _isOverlapping(cell: ICellData): boolean {\n    // Only single cell characters can be overlapping, rendering issues can\n    // occur without this check\n    if (cell.getWidth() !== 1) {\n      return false;\n    }\n\n    // We assume that any ascii character will not overlap\n    if (cell.getCode() < 256) {\n      return false;\n    }\n\n    const chars = cell.getChars();\n\n    // Deliver from cache if available\n    if (this._characterOverlapCache.hasOwnProperty(chars)) {\n      return this._characterOverlapCache[chars];\n    }\n\n    // Setup the font\n    this._ctx.save();\n    this._ctx.font = this._characterFont;\n\n    // Measure the width of the character, but Math.floor it\n    // because that is what the renderer does when it calculates\n    // the character dimensions we are comparing against\n    const overlaps = Math.floor(this._ctx.measureText(chars).width) > this._characterWidth;\n\n    // Restore the original context\n    this._ctx.restore();\n\n    // Cache and return\n    this._characterOverlapCache[chars] = overlaps;\n    return overlaps;\n  }\n\n  /**\n   * Clear the charcater at the cell specified.\n   * @param x The column of the char.\n   * @param y The row of the char.\n   */\n  // private _clearChar(x: number, y: number): void {\n  //   let colsToClear = 1;\n  //   // Clear the adjacent character if it was wide\n  //   const state = this._state.cache[x][y];\n  //   if (state && state[CHAR_DATA_WIDTH_INDEX] === 2) {\n  //     colsToClear = 2;\n  //   }\n  //   this.clearCells(x, y, colsToClear, 1);\n  // }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nexport class GridCache<T> {\n  public cache: (T | undefined)[][];\n\n  public constructor() {\n    this.cache = [];\n  }\n\n  public resize(width: number, height: number): void {\n    for (let x = 0; x < width; x++) {\n      if (this.cache.length <= x) {\n        this.cache.push([]);\n      }\n      for (let y = this.cache[x].length; y < height; y++) {\n        this.cache[x].push(undefined);\n      }\n      this.cache[x].length = height;\n    }\n    this.cache.length = width;\n  }\n\n  public clear(): void {\n    for (let x = 0; x < this.cache.length; x++) {\n      for (let y = 0; y < this.cache[x].length; y++) {\n        this.cache[x][y] = undefined;\n      }\n    }\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { IGlyphIdentifier, ICharAtlasConfig } from 'browser/renderer/atlas/Types';\nimport { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';\nimport { DEFAULT_ANSI_COLORS } from 'browser/ColorManager';\nimport { LRUMap } from 'browser/renderer/atlas/LRUMap';\nimport { isFirefox, isSafari } from 'common/Platform';\nimport { IColor } from 'browser/Types';\nimport { throwIfFalsy } from 'browser/renderer/RendererUtils';\n\n// In practice we're probably never going to exhaust a texture this large. For debugging purposes,\n// however, it can be useful to set this to a really tiny value, to verify that LRU eviction works.\nconst TEXTURE_WIDTH = 1024;\nconst TEXTURE_HEIGHT = 1024;\n\nconst TRANSPARENT_COLOR = {\n  css: 'rgba(0, 0, 0, 0)',\n  rgba: 0\n};\n\n// Drawing to the cache is expensive: If we have to draw more than this number of glyphs to the\n// cache in a single frame, give up on trying to cache anything else, and try to finish the current\n// frame ASAP.\n//\n// This helps to limit the amount of damage a program can do when it would otherwise thrash the\n// cache.\nconst FRAME_CACHE_DRAW_LIMIT = 100;\n\n/**\n * The number of milliseconds to wait before generating the ImageBitmap, this is to debounce/batch\n * the operation as window.createImageBitmap is asynchronous.\n */\nconst GLYPH_BITMAP_COMMIT_DELAY = 100;\n\ninterface IGlyphCacheValue {\n  index: number;\n  isEmpty: boolean;\n  inBitmap: boolean;\n}\n\nexport function getGlyphCacheKey(glyph: IGlyphIdentifier): number {\n  // Note that this only returns a valid key when code < 256\n  // Layout:\n  // 0b00000000000000000000000000000001: italic (1)\n  // 0b00000000000000000000000000000010: dim (1)\n  // 0b00000000000000000000000000000100: bold (1)\n  // 0b00000000000000000000111111111000: fg (9)\n  // 0b00000000000111111111000000000000: bg (9)\n  // 0b00011111111000000000000000000000: code (8)\n  // 0b11100000000000000000000000000000: unused (3)\n  return glyph.code << 21 | glyph.bg << 12 | glyph.fg << 3 | (glyph.bold ? 0 : 4) + (glyph.dim ? 0 : 2) + (glyph.italic ? 0 : 1);\n}\n\nexport class DynamicCharAtlas extends BaseCharAtlas {\n  // An ordered map that we're using to keep track of where each glyph is in the atlas texture.\n  // It's ordered so that we can determine when to remove the old entries.\n  private _cacheMap: LRUMap<IGlyphCacheValue>;\n\n  // The texture that the atlas is drawn to\n  private _cacheCanvas: HTMLCanvasElement;\n  private _cacheCtx: CanvasRenderingContext2D;\n\n  // A temporary context that glyphs are drawn to before being transfered to the atlas.\n  private _tmpCtx: CanvasRenderingContext2D;\n\n  // The number of characters stored in the atlas by width/height\n  private _width: number;\n  private _height: number;\n\n  private _drawToCacheCount: number = 0;\n\n  // An array of glyph keys that are waiting on the bitmap to be generated.\n  private _glyphsWaitingOnBitmap: IGlyphCacheValue[] = [];\n\n  // The timeout that is used to batch bitmap generation so it's not requested for every new glyph.\n  private _bitmapCommitTimeout: number | null = null;\n\n  // The bitmap to draw from, this is much faster on other browsers than others.\n  private _bitmap: ImageBitmap | null = null;\n\n  constructor(document: Document, private _config: ICharAtlasConfig) {\n    super();\n    this._cacheCanvas = document.createElement('canvas');\n    this._cacheCanvas.width = TEXTURE_WIDTH;\n    this._cacheCanvas.height = TEXTURE_HEIGHT;\n    // The canvas needs alpha because we use clearColor to convert the background color to alpha.\n    // It might also contain some characters with transparent backgrounds if allowTransparency is\n    // set.\n    this._cacheCtx = throwIfFalsy(this._cacheCanvas.getContext('2d', {alpha: true}));\n\n    const tmpCanvas = document.createElement('canvas');\n    tmpCanvas.width = this._config.scaledCharWidth;\n    tmpCanvas.height = this._config.scaledCharHeight;\n    this._tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d', {alpha: this._config.allowTransparency}));\n\n    this._width = Math.floor(TEXTURE_WIDTH / this._config.scaledCharWidth);\n    this._height = Math.floor(TEXTURE_HEIGHT / this._config.scaledCharHeight);\n    const capacity = this._width * this._height;\n    this._cacheMap = new LRUMap(capacity);\n    this._cacheMap.prealloc(capacity);\n\n    // This is useful for debugging\n    // document.body.appendChild(this._cacheCanvas);\n  }\n\n  public dispose(): void {\n    if (this._bitmapCommitTimeout !== null) {\n      window.clearTimeout(this._bitmapCommitTimeout);\n      this._bitmapCommitTimeout = null;\n    }\n  }\n\n  public beginFrame(): void {\n    this._drawToCacheCount = 0;\n  }\n\n  public draw(\n    ctx: CanvasRenderingContext2D,\n    glyph: IGlyphIdentifier,\n    x: number,\n    y: number\n  ): boolean {\n    // Space is always an empty cell, special case this as it's so common\n    if (glyph.code === 32) {\n      return true;\n    }\n\n    // Exit early for uncachable glyphs\n    if (!this._canCache(glyph)) {\n      return false;\n    }\n\n    const glyphKey = getGlyphCacheKey(glyph);\n    const cacheValue = this._cacheMap.get(glyphKey);\n    if (cacheValue !== null && cacheValue !== undefined) {\n      this._drawFromCache(ctx, cacheValue, x, y);\n      return true;\n    } else if (this._drawToCacheCount < FRAME_CACHE_DRAW_LIMIT) {\n      let index;\n      if (this._cacheMap.size < this._cacheMap.capacity) {\n        index = this._cacheMap.size;\n      } else {\n        // we're out of space, so our call to set will delete this item\n        index = this._cacheMap.peek()!.index;\n      }\n      const cacheValue = this._drawToCache(glyph, index);\n      this._cacheMap.set(glyphKey, cacheValue);\n      this._drawFromCache(ctx, cacheValue, x, y);\n      return true;\n    }\n    return false;\n  }\n\n  private _canCache(glyph: IGlyphIdentifier): boolean {\n    // Only cache ascii and extended characters for now, to be safe. In the future, we could do\n    // something more complicated to determine the expected width of a character.\n    //\n    // If we switch the renderer over to webgl at some point, we may be able to use blending modes\n    // to draw overlapping glyphs from the atlas:\n    // https://github.com/servo/webrender/issues/464#issuecomment-255632875\n    // https://webglfundamentals.org/webgl/lessons/webgl-text-texture.html\n    return glyph.code < 256;\n  }\n\n  private _toCoordinateX(index: number): number {\n    return (index % this._width) * this._config.scaledCharWidth;\n  }\n\n  private _toCoordinateY(index: number): number {\n    return Math.floor(index / this._width) * this._config.scaledCharHeight;\n  }\n\n  private _drawFromCache(\n    ctx: CanvasRenderingContext2D,\n    cacheValue: IGlyphCacheValue,\n    x: number,\n    y: number\n  ): void {\n    // We don't actually need to do anything if this is whitespace.\n    if (cacheValue.isEmpty) {\n      return;\n    }\n    const cacheX = this._toCoordinateX(cacheValue.index);\n    const cacheY = this._toCoordinateY(cacheValue.index);\n    ctx.drawImage(\n      cacheValue.inBitmap ? this._bitmap! : this._cacheCanvas,\n      cacheX,\n      cacheY,\n      this._config.scaledCharWidth,\n      this._config.scaledCharHeight,\n      x,\n      y,\n      this._config.scaledCharWidth,\n      this._config.scaledCharHeight\n    );\n  }\n\n  private _getColorFromAnsiIndex(idx: number): IColor {\n    if (idx < this._config.colors.ansi.length) {\n      return this._config.colors.ansi[idx];\n    }\n    return DEFAULT_ANSI_COLORS[idx];\n  }\n\n  private _getBackgroundColor(glyph: IGlyphIdentifier): IColor {\n    if (this._config.allowTransparency) {\n      // The background color might have some transparency, so we need to render it as fully\n      // transparent in the atlas. Otherwise we'd end up drawing the transparent background twice\n      // around the anti-aliased edges of the glyph, and it would look too dark.\n      return TRANSPARENT_COLOR;\n    } else if (glyph.bg === INVERTED_DEFAULT_COLOR) {\n      return this._config.colors.foreground;\n    } else if (glyph.bg < 256) {\n      return this._getColorFromAnsiIndex(glyph.bg);\n    }\n    return this._config.colors.background;\n  }\n\n  private _getForegroundColor(glyph: IGlyphIdentifier): IColor {\n    if (glyph.fg === INVERTED_DEFAULT_COLOR) {\n      return this._config.colors.background;\n    } else if (glyph.fg < 256) {\n      // 256 color support\n      return this._getColorFromAnsiIndex(glyph.fg);\n    }\n    return this._config.colors.foreground;\n  }\n\n  // TODO: We do this (or something similar) in multiple places. We should split this off\n  // into a shared function.\n  private _drawToCache(glyph: IGlyphIdentifier, index: number): IGlyphCacheValue {\n    this._drawToCacheCount++;\n\n    this._tmpCtx.save();\n\n    // draw the background\n    const backgroundColor = this._getBackgroundColor(glyph);\n    // Use a 'copy' composite operation to clear any existing glyph out of _tmpCtxWithAlpha, regardless of\n    // transparency in backgroundColor\n    this._tmpCtx.globalCompositeOperation = 'copy';\n    this._tmpCtx.fillStyle = backgroundColor.css;\n    this._tmpCtx.fillRect(0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight);\n    this._tmpCtx.globalCompositeOperation = 'source-over';\n\n    // draw the foreground/glyph\n    const fontWeight = glyph.bold ? this._config.fontWeightBold : this._config.fontWeight;\n    const fontStyle = glyph.italic ? 'italic' : '';\n    this._tmpCtx.font =\n      `${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`;\n    this._tmpCtx.textBaseline = 'middle';\n\n    this._tmpCtx.fillStyle = this._getForegroundColor(glyph).css;\n\n    // Apply alpha to dim the character\n    if (glyph.dim) {\n      this._tmpCtx.globalAlpha = DIM_OPACITY;\n    }\n    // Draw the character\n    this._tmpCtx.fillText(glyph.chars, 0, this._config.scaledCharHeight / 2);\n    this._tmpCtx.restore();\n\n    // clear the background from the character to avoid issues with drawing over the previous\n    // character if it extends past it's bounds\n    const imageData = this._tmpCtx.getImageData(\n      0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight\n    );\n    let isEmpty = false;\n    if (!this._config.allowTransparency) {\n      isEmpty = clearColor(imageData, backgroundColor);\n    }\n\n    // copy the data from imageData to _cacheCanvas\n    const x = this._toCoordinateX(index);\n    const y = this._toCoordinateY(index);\n    // putImageData doesn't do any blending, so it will overwrite any existing cache entry for us\n    this._cacheCtx.putImageData(imageData, x, y);\n\n    // Add the glyph and queue it to the bitmap (if the browser supports it)\n    const cacheValue = {\n      index,\n      isEmpty,\n      inBitmap: false\n    };\n    this._addGlyphToBitmap(cacheValue);\n\n    return cacheValue;\n  }\n\n  private _addGlyphToBitmap(cacheValue: IGlyphCacheValue): void {\n    // Support is patchy for createImageBitmap at the moment, pass a canvas back\n    // if support is lacking as drawImage works there too. Firefox is also\n    // included here as ImageBitmap appears both buggy and has horrible\n    // performance (tested on v55).\n    if (!('createImageBitmap' in window) || isFirefox || isSafari) {\n      return;\n    }\n\n    // Add the glyph to the queue\n    this._glyphsWaitingOnBitmap.push(cacheValue);\n\n    // Check if bitmap generation timeout already exists\n    if (this._bitmapCommitTimeout !== null) {\n      return;\n    }\n\n    this._bitmapCommitTimeout = window.setTimeout(() => this._generateBitmap(), GLYPH_BITMAP_COMMIT_DELAY);\n  }\n\n  private _generateBitmap(): void {\n    const glyphsMovingToBitmap = this._glyphsWaitingOnBitmap;\n    this._glyphsWaitingOnBitmap = [];\n    window.createImageBitmap(this._cacheCanvas).then(bitmap => {\n      // Set bitmap\n      this._bitmap = bitmap;\n\n      // Mark all new glyphs as in bitmap, excluding glyphs that came in after\n      // the bitmap was requested\n      for (let i = 0; i < glyphsMovingToBitmap.length; i++) {\n        const value = glyphsMovingToBitmap[i];\n        // It doesn't matter if the value was already evicted, it will be\n        // released from memory after this block if so.\n        value.inBitmap = true;\n      }\n    });\n    this._bitmapCommitTimeout = null;\n  }\n}\n\n// This is used for debugging the renderer, just swap out `new DynamicCharAtlas` with\n// `new NoneCharAtlas`.\nexport class NoneCharAtlas extends BaseCharAtlas {\n  constructor(document: Document, config: ICharAtlasConfig) {\n    super();\n  }\n\n  public draw(\n    ctx: CanvasRenderingContext2D,\n    glyph: IGlyphIdentifier,\n    x: number,\n    y: number\n  ): boolean {\n    return false;\n  }\n}\n\n/**\n * Makes a partiicular rgb color in an ImageData completely transparent.\n * @returns True if the result is \"empty\", meaning all pixels are fully transparent.\n */\nfunction clearColor(imageData: ImageData, color: IColor): boolean {\n  let isEmpty = true;\n  const r = color.rgba >>> 24;\n  const g = color.rgba >>> 16 & 0xFF;\n  const b = color.rgba >>> 8 & 0xFF;\n  for (let offset = 0; offset < imageData.data.length; offset += 4) {\n    if (imageData.data[offset] === r &&\n        imageData.data[offset + 1] === g &&\n        imageData.data[offset + 2] === b) {\n      imageData.data[offset + 3] = 0;\n    } else {\n      isEmpty = false;\n    }\n  }\n  return isEmpty;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IGlyphIdentifier } from 'browser/renderer/atlas/Types';\nimport { IDisposable } from 'common/Types';\n\nexport abstract class BaseCharAtlas implements IDisposable {\n  private _didWarmUp: boolean = false;\n\n  public dispose(): void { }\n\n  /**\n   * Perform any work needed to warm the cache before it can be used. May be called multiple times.\n   * Implement _doWarmUp instead if you only want to get called once.\n   */\n  public warmUp(): void {\n    if (!this._didWarmUp) {\n      this._doWarmUp();\n      this._didWarmUp = true;\n    }\n  }\n\n  /**\n   * Perform any work needed to warm the cache before it can be used. Used by the default\n   * implementation of warmUp(), and will only be called once.\n   */\n  protected _doWarmUp(): void { }\n\n  /**\n   * Called when we start drawing a new frame.\n   *\n   * TODO: We rely on this getting called by TextRenderLayer. This should really be called by\n   * Renderer instead, but we need to make Renderer the source-of-truth for the char atlas, instead\n   * of BaseRenderLayer.\n   */\n  public beginFrame(): void { }\n\n  /**\n   * May be called before warmUp finishes, however it is okay for the implementation to\n   * do nothing and return false in that case.\n   *\n   * @param ctx Where to draw the character onto.\n   * @param glyph Information about what to draw\n   * @param x The position on the context to start drawing at\n   * @param y The position on the context to start drawing at\n   * @returns The success state. True if we drew the character.\n   */\n  public abstract draw(\n    ctx: CanvasRenderingContext2D,\n    glyph: IGlyphIdentifier,\n    x: number,\n    y: number\n  ): boolean;\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ninterface ILinkedListNode<T> {\n  prev: ILinkedListNode<T> | null;\n  next: ILinkedListNode<T> | null;\n  key: number | null;\n  value: T | null;\n}\n\nexport class LRUMap<T> {\n  private _map: { [key: number]: ILinkedListNode<T> } = {};\n  private _head: ILinkedListNode<T> | null = null;\n  private _tail: ILinkedListNode<T> | null = null;\n  private _nodePool: ILinkedListNode<T>[] = [];\n  public size: number = 0;\n\n  constructor(public capacity: number) { }\n\n  private _unlinkNode(node: ILinkedListNode<T>): void {\n    const prev = node.prev;\n    const next = node.next;\n    if (node === this._head) {\n      this._head = next;\n    }\n    if (node === this._tail) {\n      this._tail = prev;\n    }\n    if (prev !== null) {\n      prev.next = next;\n    }\n    if (next !== null) {\n      next.prev = prev;\n    }\n  }\n\n  private _appendNode(node: ILinkedListNode<T>): void {\n    const tail = this._tail;\n    if (tail !== null) {\n      tail.next = node;\n    }\n    node.prev = tail;\n    node.next = null;\n    this._tail = node;\n    if (this._head === null) {\n      this._head = node;\n    }\n  }\n\n  /**\n   * Preallocate a bunch of linked-list nodes. Allocating these nodes ahead of time means that\n   * they're more likely to live next to each other in memory, which seems to improve performance.\n   *\n   * Each empty object only consumes about 60 bytes of memory, so this is pretty cheap, even for\n   * large maps.\n   */\n  public prealloc(count: number): void {\n    const nodePool = this._nodePool;\n    for (let i = 0; i < count; i++) {\n      nodePool.push({\n        prev: null,\n        next: null,\n        key: null,\n        value: null\n      });\n    }\n  }\n\n  public get(key: number): T | null {\n    // This is unsafe: We're assuming our keyspace doesn't overlap with Object.prototype. However,\n    // it's faster than calling hasOwnProperty, and in our case, it would never overlap.\n    const node = this._map[key];\n    if (node !== undefined) {\n      this._unlinkNode(node);\n      this._appendNode(node);\n      return node.value;\n    }\n    return null;\n  }\n\n  /**\n   * Gets a value from a key without marking it as the most recently used item.\n   */\n  public peekValue(key: number): T | null {\n    const node = this._map[key];\n    if (node !== undefined) {\n      return node.value;\n    }\n    return null;\n  }\n\n  public peek(): T | null {\n    const head = this._head;\n    return head === null ? null : head.value;\n  }\n\n  public set(key: number, value: T): void {\n    // This is unsafe: See note above.\n    let node = this._map[key];\n    if (node !== undefined) {\n      // already exists, we just need to mutate it and move it to the end of the list\n      node = this._map[key];\n      this._unlinkNode(node);\n      node.value = value;\n    } else if (this.size >= this.capacity) {\n      // we're out of space: recycle the head node, move it to the tail\n      node = this._head!;\n      this._unlinkNode(node);\n      delete this._map[node.key!];\n      node.key = key;\n      node.value = value;\n      this._map[key] = node;\n    } else {\n      // make a new element\n      const nodePool = this._nodePool;\n      if (nodePool.length > 0) {\n        // use a preallocated node if we can\n        node = nodePool.pop()!;\n        node.key = key;\n        node.value = value;\n      } else {\n        node = {\n          prev: null,\n          next: null,\n          key,\n          value\n        };\n      }\n      this._map[key] = node;\n      this.size++;\n    }\n    this._appendNode(node);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions } from 'browser/renderer/Types';\nimport { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';\nimport { IColorSet } from 'browser/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\ninterface ISelectionState {\n  start?: [number, number];\n  end?: [number, number];\n  columnSelectMode?: boolean;\n  ydisp?: number;\n}\n\nexport class SelectionRenderLayer extends BaseRenderLayer {\n  private _state!: ISelectionState;\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    rendererId: number,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'selection', zIndex, true, colors, rendererId, bufferService, optionsService);\n    this._clearState();\n  }\n\n  private _clearState(): void {\n    this._state = {\n      start: undefined,\n      end: undefined,\n      columnSelectMode: undefined,\n      ydisp: undefined\n    };\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._clearState();\n  }\n\n  public reset(): void {\n    if (this._state.start && this._state.end) {\n      this._clearState();\n      this._clearAll();\n    }\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {\n    // Selection has not changed\n    if (!this._didStateChange(start, end, columnSelectMode, this._bufferService.buffer.ydisp)) {\n      return;\n    }\n\n    // Remove all selections\n    this._clearAll();\n\n    // Selection does not exist\n    if (!start || !end) {\n      this._clearState();\n      return;\n    }\n\n    // Translate from buffer position to viewport position\n    const viewportStartRow = start[1] - this._bufferService.buffer.ydisp;\n    const viewportEndRow = end[1] - this._bufferService.buffer.ydisp;\n    const viewportCappedStartRow = Math.max(viewportStartRow, 0);\n    const viewportCappedEndRow = Math.min(viewportEndRow, this._bufferService.rows - 1);\n\n    // No need to draw the selection\n    if (viewportCappedStartRow >= this._bufferService.rows || viewportCappedEndRow < 0) {\n      return;\n    }\n\n    this._ctx.fillStyle = this._colors.selection.css;\n\n    if (columnSelectMode) {\n      const startCol = start[0];\n      const width = end[0] - startCol;\n      const height = viewportCappedEndRow - viewportCappedStartRow + 1;\n      this._fillCells(startCol, viewportCappedStartRow, width, height);\n    } else {\n      // Draw first row\n      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;\n      const startRowEndCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;\n      this._fillCells(startCol, viewportCappedStartRow, startRowEndCol - startCol, 1);\n\n      // Draw middle rows\n      const middleRowsCount = Math.max(viewportCappedEndRow - viewportCappedStartRow - 1, 0);\n      this._fillCells(0, viewportCappedStartRow + 1, this._bufferService.cols, middleRowsCount);\n\n      // Draw final row\n      if (viewportCappedStartRow !== viewportCappedEndRow) {\n        // Only draw viewportEndRow if it's not the same as viewportStartRow\n        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;\n        this._fillCells(0, viewportCappedEndRow, endCol, 1);\n      }\n    }\n\n    // Save state for next render\n    this._state.start = [start[0], start[1]];\n    this._state.end = [end[0], end[1]];\n    this._state.columnSelectMode = columnSelectMode;\n    this._state.ydisp = this._bufferService.buffer.ydisp;\n  }\n\n  private _didStateChange(start: [number, number], end: [number, number], columnSelectMode: boolean, ydisp: number): boolean {\n    return !this._areCoordinatesEqual(start, this._state.start) ||\n      !this._areCoordinatesEqual(end, this._state.end) ||\n      columnSelectMode !== this._state.columnSelectMode ||\n      ydisp !== this._state.ydisp;\n  }\n\n  private _areCoordinatesEqual(coord1: [number, number] | undefined, coord2: [number, number] | undefined): boolean {\n    if (!coord1 || !coord2) {\n      return false;\n    }\n\n    return coord1[0] === coord2[0] && coord1[1] === coord2[1];\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions } from 'browser/renderer/Types';\nimport { BaseRenderLayer } from '../browser/renderer/BaseRenderLayer';\nimport { ITerminal } from '../Types';\nimport { ICellData } from 'common/Types';\nimport { CellData } from 'common/buffer/CellData';\nimport { IColorSet } from 'browser/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\ninterface ICursorState {\n  x: number;\n  y: number;\n  isFocused: boolean;\n  style: string;\n  width: number;\n}\n\n/**\n * The time between cursor blinks.\n */\nconst BLINK_INTERVAL = 600;\n\nexport class CursorRenderLayer extends BaseRenderLayer {\n  private _state: ICursorState;\n  private _cursorRenderers: {[key: string]: (x: number, y: number, cell: ICellData) => void};\n  private _cursorBlinkStateManager: CursorBlinkStateManager;\n  private _cell: ICellData = new CellData();\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    private _terminal: ITerminal,\n    rendererId: number,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'cursor', zIndex, true, colors, rendererId, bufferService, optionsService);\n    this._state = {\n      x: null,\n      y: null,\n      isFocused: null,\n      style: null,\n      width: null\n    };\n    this._cursorRenderers = {\n      'bar': this._renderBarCursor.bind(this),\n      'block': this._renderBlockCursor.bind(this),\n      'underline': this._renderUnderlineCursor.bind(this)\n    };\n    // TODO: Consider initial options? Maybe onOptionsChanged should be called at the end of open?\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._state = {\n      x: null,\n      y: null,\n      isFocused: null,\n      style: null,\n      width: null\n    };\n  }\n\n  public reset(): void {\n    this._clearCursor();\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.dispose();\n      this._cursorBlinkStateManager = null;\n      this.onOptionsChanged();\n    }\n  }\n\n  public onBlur(): void {\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.pause();\n    }\n    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);\n  }\n\n  public onFocus(): void {\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.resume();\n    } else {\n      this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);\n    }\n  }\n\n  public onOptionsChanged(): void {\n    if (this._optionsService.options.cursorBlink) {\n      if (!this._cursorBlinkStateManager) {\n        this._cursorBlinkStateManager = new CursorBlinkStateManager(this._terminal.isFocused, () => {\n          this._render(true);\n        });\n      }\n    } else {\n      if (this._cursorBlinkStateManager) {\n        this._cursorBlinkStateManager.dispose();\n        this._cursorBlinkStateManager = null;\n      }\n    }\n    // Request a refresh from the terminal as management of rendering is being\n    // moved back to the terminal\n    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);\n  }\n\n  public onCursorMove(): void {\n    if (this._cursorBlinkStateManager) {\n      this._cursorBlinkStateManager.restartBlinkAnimation();\n    }\n  }\n\n  public onGridChanged(startRow: number, endRow: number): void {\n    if (!this._cursorBlinkStateManager || this._cursorBlinkStateManager.isPaused) {\n      this._render(false);\n    } else {\n      this._cursorBlinkStateManager.restartBlinkAnimation();\n    }\n  }\n\n  private _render(triggeredByAnimationFrame: boolean): void {\n    // Don't draw the cursor if it's hidden\n    if (!this._terminal.cursorState || this._terminal.cursorHidden) {\n      this._clearCursor();\n      return;\n    }\n\n    const cursorY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;\n    const viewportRelativeCursorY = cursorY - this._bufferService.buffer.ydisp;\n\n    // Don't draw the cursor if it's off-screen\n    if (viewportRelativeCursorY < 0 || viewportRelativeCursorY >= this._bufferService.rows) {\n      this._clearCursor();\n      return;\n    }\n\n    this._bufferService.buffer.lines.get(cursorY).loadCell(this._bufferService.buffer.x, this._cell);\n    if (this._cell.content === undefined) {\n      return;\n    }\n\n    if (!this._terminal.isFocused) {\n      this._clearCursor();\n      this._ctx.save();\n      this._ctx.fillStyle = this._colors.cursor.css;\n      const cursorStyle = this._optionsService.options.cursorStyle;\n      if (cursorStyle && cursorStyle !== 'block') {\n        this._cursorRenderers[cursorStyle](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);\n      } else {\n        this._renderBlurCursor(this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);\n      }\n      this._ctx.restore();\n      this._state.x = this._bufferService.buffer.x;\n      this._state.y = viewportRelativeCursorY;\n      this._state.isFocused = false;\n      this._state.style = cursorStyle;\n      this._state.width = this._cell.getWidth();\n      return;\n    }\n\n    // Don't draw the cursor if it's blinking\n    if (this._cursorBlinkStateManager && !this._cursorBlinkStateManager.isCursorVisible) {\n      this._clearCursor();\n      return;\n    }\n\n    if (this._state) {\n      // The cursor is already in the correct spot, don't redraw\n      if (this._state.x === this._bufferService.buffer.x &&\n          this._state.y === viewportRelativeCursorY &&\n          this._state.isFocused === this._terminal.isFocused &&\n          this._state.style === this._optionsService.options.cursorStyle &&\n          this._state.width === this._cell.getWidth()) {\n        return;\n      }\n      this._clearCursor();\n    }\n\n    this._ctx.save();\n    this._cursorRenderers[this._optionsService.options.cursorStyle || 'block'](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);\n    this._ctx.restore();\n\n    this._state.x = this._bufferService.buffer.x;\n    this._state.y = viewportRelativeCursorY;\n    this._state.isFocused = false;\n    this._state.style = this._optionsService.options.cursorStyle;\n    this._state.width = this._cell.getWidth();\n  }\n\n  private _clearCursor(): void {\n    if (this._state) {\n      this._clearCells(this._state.x, this._state.y, this._state.width, 1);\n      this._state = {\n        x: null,\n        y: null,\n        isFocused: null,\n        style: null,\n        width: null\n      };\n    }\n  }\n\n  private _renderBarCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.fillStyle = this._colors.cursor.css;\n    this._fillLeftLineAtCell(x, y);\n    this._ctx.restore();\n  }\n\n  private _renderBlockCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.fillStyle = this._colors.cursor.css;\n    this._fillCells(x, y, cell.getWidth(), 1);\n    this._ctx.fillStyle = this._colors.cursorAccent.css;\n    this._fillCharTrueColor(cell, x, y);\n    this._ctx.restore();\n  }\n\n  private _renderUnderlineCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.fillStyle = this._colors.cursor.css;\n    this._fillBottomLineAtCells(x, y);\n    this._ctx.restore();\n  }\n\n  private _renderBlurCursor(x: number, y: number, cell: ICellData): void {\n    this._ctx.save();\n    this._ctx.strokeStyle = this._colors.cursor.css;\n    this._strokeRectAtCell(x, y, cell.getWidth(), 1);\n    this._ctx.restore();\n  }\n}\n\nclass CursorBlinkStateManager {\n  public isCursorVisible: boolean;\n\n  private _animationFrame: number;\n  private _blinkStartTimeout: number;\n  private _blinkInterval: number;\n\n  /**\n   * The time at which the animation frame was restarted, this is used on the\n   * next render to restart the timers so they don't need to restart the timers\n   * multiple times over a short period.\n   */\n  private _animationTimeRestarted: number;\n\n  constructor(\n    isFocused: boolean,\n    private _renderCallback: () => void\n  ) {\n    this.isCursorVisible = true;\n    if (isFocused) {\n      this._restartInterval();\n    }\n  }\n\n  public get isPaused(): boolean { return !(this._blinkStartTimeout || this._blinkInterval); }\n\n  public dispose(): void {\n    if (this._blinkInterval) {\n      window.clearInterval(this._blinkInterval);\n      this._blinkInterval = null;\n    }\n    if (this._blinkStartTimeout) {\n      window.clearTimeout(this._blinkStartTimeout);\n      this._blinkStartTimeout = null;\n    }\n    if (this._animationFrame) {\n      window.cancelAnimationFrame(this._animationFrame);\n      this._animationFrame = null;\n    }\n  }\n\n  public restartBlinkAnimation(): void {\n    if (this.isPaused) {\n      return;\n    }\n    // Save a timestamp so that the restart can be done on the next interval\n    this._animationTimeRestarted = Date.now();\n    // Force a cursor render to ensure it's visible and in the correct position\n    this.isCursorVisible = true;\n    if (!this._animationFrame) {\n      this._animationFrame = window.requestAnimationFrame(() => {\n        this._renderCallback();\n        this._animationFrame = null;\n      });\n    }\n  }\n\n  private _restartInterval(timeToStart: number = BLINK_INTERVAL): void {\n    // Clear any existing interval\n    if (this._blinkInterval) {\n      window.clearInterval(this._blinkInterval);\n    }\n\n    // Setup the initial timeout which will hide the cursor, this is done before\n    // the regular interval is setup in order to support restarting the blink\n    // animation in a lightweight way (without thrashing clearInterval and\n    // setInterval).\n    this._blinkStartTimeout = <number><any>setTimeout(() => {\n      // Check if another animation restart was requested while this was being\n      // started\n      if (this._animationTimeRestarted) {\n        const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);\n        this._animationTimeRestarted = null;\n        if (time > 0) {\n          this._restartInterval(time);\n          return;\n        }\n      }\n\n      // Hide the cursor\n      this.isCursorVisible = false;\n      this._animationFrame = window.requestAnimationFrame(() => {\n        this._renderCallback();\n        this._animationFrame = null;\n      });\n\n      // Setup the blink interval\n      this._blinkInterval = <number><any>setInterval(() => {\n        // Adjust the animation time if it was restarted\n        if (this._animationTimeRestarted) {\n          // calc time diff\n          // Make restart interval do a setTimeout initially?\n          const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);\n          this._animationTimeRestarted = null;\n          this._restartInterval(time);\n          return;\n        }\n\n        // Invert visibility and render\n        this.isCursorVisible = !this.isCursorVisible;\n        this._animationFrame = window.requestAnimationFrame(() => {\n          this._renderCallback();\n          this._animationFrame = null;\n        });\n      }, BLINK_INTERVAL);\n    }, timeToStart);\n  }\n\n  public pause(): void {\n    this.isCursorVisible = true;\n    if (this._blinkInterval) {\n      window.clearInterval(this._blinkInterval);\n      this._blinkInterval = null;\n    }\n    if (this._blinkStartTimeout) {\n      window.clearTimeout(this._blinkStartTimeout);\n      this._blinkStartTimeout = null;\n    }\n    if (this._animationFrame) {\n      window.cancelAnimationFrame(this._animationFrame);\n      this._animationFrame = null;\n    }\n  }\n\n  public resume(): void {\n    this._animationTimeRestarted = null;\n    this._restartInterval();\n    this.restartBlinkAnimation();\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderDimensions } from 'browser/renderer/Types';\nimport { BaseRenderLayer } from './BaseRenderLayer';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { is256Color } from 'browser/renderer/atlas/CharAtlasUtils';\nimport { IColorSet, ILinkifierEvent, ILinkifier } from 'browser/Types';\nimport { IBufferService, IOptionsService } from 'common/services/Services';\n\nexport class LinkRenderLayer extends BaseRenderLayer {\n  private _state: ILinkifierEvent | undefined;\n\n  constructor(\n    container: HTMLElement,\n    zIndex: number,\n    colors: IColorSet,\n    rendererId: number,\n    linkifier: ILinkifier,\n    readonly bufferService: IBufferService,\n    readonly optionsService: IOptionsService\n  ) {\n    super(container, 'link', zIndex, true, colors, rendererId, bufferService, optionsService);\n    linkifier.onLinkHover(e => this._onLinkHover(e));\n    linkifier.onLinkLeave(e => this._onLinkLeave(e));\n  }\n\n  public resize(dim: IRenderDimensions): void {\n    super.resize(dim);\n    // Resizing the canvas discards the contents of the canvas so clear state\n    this._state = undefined;\n  }\n\n  public reset(): void {\n    this._clearCurrentLink();\n  }\n\n  private _clearCurrentLink(): void {\n    if (this._state) {\n      this._clearCells(this._state.x1, this._state.y1, this._state.cols - this._state.x1, 1);\n      const middleRowCount = this._state.y2 - this._state.y1 - 1;\n      if (middleRowCount > 0) {\n        this._clearCells(0, this._state.y1 + 1, this._state.cols, middleRowCount);\n      }\n      this._clearCells(0, this._state.y2, this._state.x2, 1);\n      this._state = undefined;\n    }\n  }\n\n  private _onLinkHover(e: ILinkifierEvent): void {\n    if (e.fg === INVERTED_DEFAULT_COLOR) {\n      this._ctx.fillStyle = this._colors.background.css;\n    } else if (e.fg && is256Color(e.fg)) {\n      // 256 color support\n      this._ctx.fillStyle = this._colors.ansi[e.fg].css;\n    } else {\n      this._ctx.fillStyle = this._colors.foreground.css;\n    }\n\n    if (e.y1 === e.y2) {\n      // Single line link\n      this._fillBottomLineAtCells(e.x1, e.y1, e.x2 - e.x1);\n    } else {\n      // Multi-line link\n      this._fillBottomLineAtCells(e.x1, e.y1, e.cols - e.x1);\n      for (let y = e.y1 + 1; y < e.y2; y++) {\n        this._fillBottomLineAtCells(0, y, e.cols);\n      }\n      this._fillBottomLineAtCells(0, e.y2, e.x2);\n    }\n    this._state = e;\n  }\n\n  private _onLinkLeave(e: ILinkifierEvent): void {\n    this._clearCurrentLink();\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ILinkifierEvent, ILinkMatcher, LinkMatcherHandler, ILinkMatcherOptions, ILinkifier, IMouseZoneManager, IMouseZone, IRegisteredLinkMatcher } from 'browser/Types';\nimport { IBufferStringIteratorResult } from 'common/buffer/Types';\nimport { getStringCellWidth } from 'common/CharWidth';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { ILogService, IBufferService } from 'common/services/Services';\n\n/**\n * Limit of the unwrapping line expansion (overscan) at the top and bottom\n * of the actual viewport in ASCII characters.\n * A limit of 2000 should match most sane urls.\n */\nconst OVERSCAN_CHAR_LIMIT = 2000;\n\n/**\n * The Linkifier applies links to rows shortly after they have been refreshed.\n */\nexport class Linkifier implements ILinkifier {\n  /**\n   * The time to wait after a row is changed before it is linkified. This prevents\n   * the costly operation of searching every row multiple times, potentially a\n   * huge amount of times.\n   */\n  protected static _timeBeforeLatency = 200;\n\n  protected _linkMatchers: IRegisteredLinkMatcher[] = [];\n\n  private _mouseZoneManager: IMouseZoneManager | undefined;\n  private _element: HTMLElement | undefined;\n\n  private _rowsTimeoutId: number | undefined;\n  private _nextLinkMatcherId = 0;\n  private _rowsToLinkify: { start: number | undefined, end: number | undefined };\n\n  private _onLinkHover = new EventEmitter<ILinkifierEvent>();\n  public get onLinkHover(): IEvent<ILinkifierEvent> { return this._onLinkHover.event; }\n  private _onLinkLeave = new EventEmitter<ILinkifierEvent>();\n  public get onLinkLeave(): IEvent<ILinkifierEvent> { return this._onLinkLeave.event; }\n  private _onLinkTooltip = new EventEmitter<ILinkifierEvent>();\n  public get onLinkTooltip(): IEvent<ILinkifierEvent> { return this._onLinkTooltip.event; }\n\n  constructor(\n    protected readonly _bufferService: IBufferService,\n    private readonly _logService: ILogService\n  ) {\n    this._rowsToLinkify = {\n      start: undefined,\n      end: undefined\n    };\n  }\n\n  /**\n   * Attaches the linkifier to the DOM, enabling linkification.\n   * @param mouseZoneManager The mouse zone manager to register link zones with.\n   */\n  public attachToDom(element: HTMLElement, mouseZoneManager: IMouseZoneManager): void {\n    this._element = element;\n    this._mouseZoneManager = mouseZoneManager;\n  }\n\n  /**\n   * Queue linkification on a set of rows.\n   * @param start The row to linkify from (inclusive).\n   * @param end The row to linkify to (inclusive).\n   */\n  public linkifyRows(start: number, end: number): void {\n    // Don't attempt linkify if not yet attached to DOM\n    if (!this._mouseZoneManager) {\n      return;\n    }\n\n    // Increase range to linkify\n    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {\n      this._rowsToLinkify.start = start;\n      this._rowsToLinkify.end = end;\n    } else {\n      this._rowsToLinkify.start = Math.min(this._rowsToLinkify.start, start);\n      this._rowsToLinkify.end = Math.max(this._rowsToLinkify.end, end);\n    }\n\n    // Clear out any existing links on this row range\n    this._mouseZoneManager.clearAll(start, end);\n\n    // Restart timer\n    if (this._rowsTimeoutId) {\n      clearTimeout(this._rowsTimeoutId);\n    }\n    this._rowsTimeoutId = <number><any>setTimeout(() => this._linkifyRows(), Linkifier._timeBeforeLatency);\n  }\n\n  /**\n   * Linkifies the rows requested.\n   */\n  private _linkifyRows(): void {\n    this._rowsTimeoutId = undefined;\n    const buffer = this._bufferService.buffer;\n\n    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {\n      this._logService.debug('_rowToLinkify was unset before _linkifyRows was called');\n      return;\n    }\n\n    // Ensure the start row exists\n    const absoluteRowIndexStart = buffer.ydisp + this._rowsToLinkify.start;\n    if (absoluteRowIndexStart >= buffer.lines.length) {\n      return;\n    }\n\n    // Invalidate bad end row values (if a resize happened)\n    const absoluteRowIndexEnd = buffer.ydisp + Math.min(this._rowsToLinkify.end, this._bufferService.rows) + 1;\n\n    // Iterate over the range of unwrapped content strings within start..end\n    // (excluding).\n    // _doLinkifyRow gets full unwrapped lines with the start row as buffer offset\n    // for every matcher.\n    // The unwrapping is needed to also match content that got wrapped across\n    // several buffer lines. To avoid a worst case scenario where the whole buffer\n    // contains just a single unwrapped string we limit this line expansion beyond\n    // the viewport to +OVERSCAN_CHAR_LIMIT chars (overscan) at top and bottom.\n    // This comes with the tradeoff that matches longer than OVERSCAN_CHAR_LIMIT\n    // chars will not match anymore at the viewport borders.\n    const overscanLineLimit = Math.ceil(OVERSCAN_CHAR_LIMIT / this._bufferService.cols);\n    const iterator = this._bufferService.buffer.iterator(\n      false, absoluteRowIndexStart, absoluteRowIndexEnd, overscanLineLimit, overscanLineLimit);\n    while (iterator.hasNext()) {\n      const lineData: IBufferStringIteratorResult = iterator.next();\n      for (let i = 0; i < this._linkMatchers.length; i++) {\n        this._doLinkifyRow(lineData.range.first, lineData.content, this._linkMatchers[i]);\n      }\n    }\n\n    this._rowsToLinkify.start = undefined;\n    this._rowsToLinkify.end = undefined;\n  }\n\n  /**\n   * Registers a link matcher, allowing custom link patterns to be matched and\n   * handled.\n   * @param regex The regular expression to search for. Specifically, this\n   * searches the textContent of the rows. You will want to use \\s to match a\n   * space ' ' character for example.\n   * @param handler The callback when the link is called.\n   * @param options Options for the link matcher.\n   * @return The ID of the new matcher, this can be used to deregister.\n   */\n  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: ILinkMatcherOptions = {}): number {\n    if (!handler) {\n      throw new Error('handler must be defined');\n    }\n    const matcher: IRegisteredLinkMatcher = {\n      id: this._nextLinkMatcherId++,\n      regex,\n      handler,\n      matchIndex: options.matchIndex,\n      validationCallback: options.validationCallback,\n      hoverTooltipCallback: options.tooltipCallback,\n      hoverLeaveCallback: options.leaveCallback,\n      willLinkActivate: options.willLinkActivate,\n      priority: options.priority || 0\n    };\n    this._addLinkMatcherToList(matcher);\n    return matcher.id;\n  }\n\n  /**\n   * Inserts a link matcher to the list in the correct position based on the\n   * priority of each link matcher. New link matchers of equal priority are\n   * considered after older link matchers.\n   * @param matcher The link matcher to be added.\n   */\n  private _addLinkMatcherToList(matcher: IRegisteredLinkMatcher): void {\n    if (this._linkMatchers.length === 0) {\n      this._linkMatchers.push(matcher);\n      return;\n    }\n\n    for (let i = this._linkMatchers.length - 1; i >= 0; i--) {\n      if (matcher.priority <= this._linkMatchers[i].priority) {\n        this._linkMatchers.splice(i + 1, 0, matcher);\n        return;\n      }\n    }\n\n    this._linkMatchers.splice(0, 0, matcher);\n  }\n\n  /**\n   * Deregisters a link matcher if it has been registered.\n   * @param matcherId The link matcher's ID (returned after register)\n   * @return Whether a link matcher was found and deregistered.\n   */\n  public deregisterLinkMatcher(matcherId: number): boolean {\n    for (let i = 0; i < this._linkMatchers.length; i++) {\n      if (this._linkMatchers[i].id === matcherId) {\n        this._linkMatchers.splice(i, 1);\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Linkifies a row given a specific handler.\n   * @param rowIndex The row index to linkify (absolute index).\n   * @param text string content of the unwrapped row.\n   * @param matcher The link matcher for this line.\n   */\n  private _doLinkifyRow(rowIndex: number, text: string, matcher: ILinkMatcher): void {\n    // clone regex to do a global search on text\n    const rex = new RegExp(matcher.regex.source, (matcher.regex.flags || '') + 'g');\n    let match;\n    let stringIndex = -1;\n    while ((match = rex.exec(text)) !== null) {\n      const uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];\n      if (!uri) {\n        // something matched but does not comply with the given matchIndex\n        // since this is most likely a bug the regex itself we simply do nothing here\n        this._logService.debug('match found without corresponding matchIndex', match, matcher);\n        break;\n      }\n\n      // Get index, match.index is for the outer match which includes negated chars\n      // therefore we cannot use match.index directly, instead we search the position\n      // of the match group in text again\n      // also correct regex and string search offsets for the next loop run\n      stringIndex = text.indexOf(uri, stringIndex + 1);\n      rex.lastIndex = stringIndex + uri.length;\n      if (stringIndex < 0) {\n        // invalid stringIndex (should not have happened)\n        break;\n      }\n\n      // get the buffer index as [absolute row, col] for the match\n      const bufferIndex = this._bufferService.buffer.stringIndexToBufferIndex(rowIndex, stringIndex);\n      if (bufferIndex[0] < 0) {\n        // invalid bufferIndex (should not have happened)\n        break;\n      }\n\n      const line = this._bufferService.buffer.lines.get(bufferIndex[0]);\n      if (!line) {\n        break;\n      }\n\n      const attr = line.getFg(bufferIndex[1]);\n      const fg = attr ? (attr >> 9) & 0x1ff : undefined;\n\n      if (matcher.validationCallback) {\n        matcher.validationCallback(uri, isValid => {\n          // Discard link if the line has already changed\n          if (this._rowsTimeoutId) {\n            return;\n          }\n          if (isValid) {\n            this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);\n          }\n        });\n      } else {\n        this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);\n      }\n    }\n  }\n\n  /**\n   * Registers a link to the mouse zone manager.\n   * @param x The column the link starts.\n   * @param y The row the link is on.\n   * @param uri The URI of the link.\n   * @param matcher The link matcher for the link.\n   * @param fg The link color for hover event.\n   */\n  private _addLink(x: number, y: number, uri: string, matcher: ILinkMatcher, fg: number | undefined): void {\n    if (!this._mouseZoneManager || !this._element) {\n      return;\n    }\n\n    const width = getStringCellWidth(uri);\n    const x1 = x % this._bufferService.cols;\n    const y1 = y + Math.floor(x / this._bufferService.cols);\n    let x2 = (x1 + width) % this._bufferService.cols;\n    let y2 = y1 + Math.floor((x1 + width) / this._bufferService.cols);\n    if (x2 === 0) {\n      x2 = this._bufferService.cols;\n      y2--;\n    }\n\n    this._mouseZoneManager.add(new MouseZone(\n      x1 + 1,\n      y1 + 1,\n      x2 + 1,\n      y2 + 1,\n      e => {\n        if (matcher.handler) {\n          return matcher.handler(e, uri);\n        }\n        window.open(uri, '_blank');\n      },\n      () => {\n        this._onLinkHover.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));\n        this._element!.classList.add('xterm-cursor-pointer');\n      },\n      e => {\n        this._onLinkTooltip.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));\n        if (matcher.hoverTooltipCallback) {\n          // Note that IViewportRange use 1-based coordinates to align with escape sequences such\n          // as CUP which use 1,1 as the default for row/col\n          matcher.hoverTooltipCallback(e, uri, { start: { x: x1, y: y1 }, end: { x: x2, y: y2 } });\n        }\n      },\n      () => {\n        this._onLinkLeave.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));\n        this._element!.classList.remove('xterm-cursor-pointer');\n        if (matcher.hoverLeaveCallback) {\n          matcher.hoverLeaveCallback();\n        }\n      },\n      e => {\n        if (matcher.willLinkActivate) {\n          return matcher.willLinkActivate(e, uri);\n        }\n        return true;\n      }\n    ));\n  }\n\n  private _createLinkHoverEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {\n    return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };\n  }\n}\n\nexport class MouseZone implements IMouseZone {\n  constructor(\n    public x1: number,\n    public y1: number,\n    public x2: number,\n    public y2: number,\n    public clickCallback: (e: MouseEvent) => any,\n    public hoverCallback: (e: MouseEvent) => any,\n    public tooltipCallback: (e: MouseEvent) => any,\n    public leaveCallback: () => void,\n    public willLinkActivate: (e: MouseEvent) => boolean\n  ) {\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ISelectionRedrawRequestEvent } from 'browser/selection/Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { IBufferLine, IDisposable } from 'common/Types';\nimport * as Browser from 'common/Platform';\nimport { SelectionModel } from 'browser/selection/SelectionModel';\nimport { CellData } from 'common/buffer/CellData';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { ICharSizeService, IMouseService, ISelectionService } from 'browser/services/Services';\nimport { IBufferService, IOptionsService, ICoreService } from 'common/services/Services';\nimport { getCoordsRelativeToElement } from 'browser/input/Mouse';\nimport { moveToCellSequence } from 'browser/input/MoveToCell';\n\n/**\n * The number of pixels the mouse needs to be above or below the viewport in\n * order to scroll at the maximum speed.\n */\nconst DRAG_SCROLL_MAX_THRESHOLD = 50;\n\n/**\n * The maximum scrolling speed\n */\nconst DRAG_SCROLL_MAX_SPEED = 15;\n\n/**\n * The number of milliseconds between drag scroll updates.\n */\nconst DRAG_SCROLL_INTERVAL = 50;\n\n/**\n * The maximum amount of time that can have elapsed for an alt click to move the\n * cursor.\n */\nconst ALT_CLICK_MOVE_CURSOR_TIME = 500;\n\nconst NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);\nconst ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');\n\n/**\n * Represents a position of a word on a line.\n */\ninterface IWordPosition {\n  start: number;\n  length: number;\n}\n\n/**\n * A selection mode, this drives how the selection behaves on mouse move.\n */\nexport const enum SelectionMode {\n  NORMAL,\n  WORD,\n  LINE,\n  COLUMN\n}\n\n/**\n * A class that manages the selection of the terminal. With help from\n * SelectionModel, SelectionService handles with all logic associated with\n * dealing with the selection, including handling mouse interaction, wide\n * characters and fetching the actual text within the selection. Rendering is\n * not handled by the SelectionService but the onRedrawRequest event is fired\n * when the selection is ready to be redrawn (on an animation frame).\n */\nexport class SelectionService implements ISelectionService {\n  serviceBrand: any;\n\n  protected _model: SelectionModel;\n\n  /**\n   * The amount to scroll every drag scroll update (depends on how far the mouse\n   * drag is above or below the terminal).\n   */\n  private _dragScrollAmount: number = 0;\n\n  /**\n   * The current selection mode.\n   */\n  protected _activeSelectionMode: SelectionMode;\n\n  /**\n   * A setInterval timer that is active while the mouse is down whose callback\n   * scrolls the viewport when necessary.\n   */\n  private _dragScrollIntervalTimer: number | undefined;\n\n  /**\n   * The animation frame ID used for refreshing the selection.\n   */\n  private _refreshAnimationFrame: number | undefined;\n\n  /**\n   * Whether selection is enabled.\n   */\n  private _enabled = true;\n\n  private _mouseMoveListener: EventListener;\n  private _mouseUpListener: EventListener;\n  private _trimListener: IDisposable;\n  private _workCell: CellData = new CellData();\n\n  private _mouseDownTimeStamp: number = 0;\n\n  private _onLinuxMouseSelection = new EventEmitter<string>();\n  public get onLinuxMouseSelection(): IEvent<string> { return this._onLinuxMouseSelection.event; }\n  private _onRedrawRequest = new EventEmitter<ISelectionRedrawRequestEvent>();\n  public get onRedrawRequest(): IEvent<ISelectionRedrawRequestEvent> { return this._onRedrawRequest.event; }\n  private _onSelectionChange = new EventEmitter<void>();\n  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }\n\n  constructor(\n    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,\n    private readonly _element: HTMLElement,\n    private readonly _screenElement: HTMLElement,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @ICoreService private readonly _coreService: ICoreService,\n    @IMouseService private readonly _mouseService: IMouseService,\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    // Init listeners\n    this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);\n    this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);\n    this._coreService.onUserInput(() => {\n      if (this.hasSelection) {\n        this.clearSelection();\n      }\n    });\n    this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._onTrim(amount));\n    this._bufferService.buffers.onBufferActivate(e => this._onBufferActivate(e));\n\n    this.enable();\n\n    this._model = new SelectionModel(this._bufferService);\n    this._activeSelectionMode = SelectionMode.NORMAL;\n  }\n\n  public dispose(): void {\n    this._removeMouseDownListeners();\n  }\n\n  public reset(): void {\n    this.clearSelection();\n  }\n\n  /**\n   * Disables the selection manager. This is useful for when terminal mouse\n   * are enabled.\n   */\n  public disable(): void {\n    this.clearSelection();\n    this._enabled = false;\n  }\n\n  /**\n   * Enable the selection manager.\n   */\n  public enable(): void {\n    this._enabled = true;\n  }\n\n  public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }\n  public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }\n\n  /**\n   * Gets whether there is an active text selection.\n   */\n  public get hasSelection(): boolean {\n    const start = this._model.finalSelectionStart;\n    const end = this._model.finalSelectionEnd;\n    if (!start || !end) {\n      return false;\n    }\n    return start[0] !== end[0] || start[1] !== end[1];\n  }\n\n  /**\n   * Gets the text currently selected.\n   */\n  public get selectionText(): string {\n    const start = this._model.finalSelectionStart;\n    const end = this._model.finalSelectionEnd;\n    if (!start || !end) {\n      return '';\n    }\n\n    const buffer = this._bufferService.buffer;\n    const result: string[] = [];\n\n    if (this._activeSelectionMode === SelectionMode.COLUMN) {\n      // Ignore zero width selections\n      if (start[0] === end[0]) {\n        return '';\n      }\n\n      for (let i = start[1]; i <= end[1]; i++) {\n        const lineText = buffer.translateBufferLineToString(i, true, start[0], end[0]);\n        result.push(lineText);\n      }\n    } else {\n      // Get first row\n      const startRowEndCol = start[1] === end[1] ? end[0] : undefined;\n      result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));\n\n      // Get middle rows\n      for (let i = start[1] + 1; i <= end[1] - 1; i++) {\n        const bufferLine = buffer.lines.get(i);\n        const lineText = buffer.translateBufferLineToString(i, true);\n        if (bufferLine && bufferLine.isWrapped) {\n          result[result.length - 1] += lineText;\n        } else {\n          result.push(lineText);\n        }\n      }\n\n      // Get final row\n      if (start[1] !== end[1]) {\n        const bufferLine = buffer.lines.get(end[1]);\n        const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);\n        if (bufferLine && bufferLine!.isWrapped) {\n          result[result.length - 1] += lineText;\n        } else {\n          result.push(lineText);\n        }\n      }\n    }\n\n    // Format string by replacing non-breaking space chars with regular spaces\n    // and joining the array into a multi-line string.\n    const formattedResult = result.map(line => {\n      return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');\n    }).join(Browser.isWindows ? '\\r\\n' : '\\n');\n\n    return formattedResult;\n  }\n\n  /**\n   * Clears the current terminal selection.\n   */\n  public clearSelection(): void {\n    this._model.clearSelection();\n    this._removeMouseDownListeners();\n    this.refresh();\n    this._onSelectionChange.fire();\n  }\n\n  /**\n   * Queues a refresh, redrawing the selection on the next opportunity.\n   * @param isLinuxMouseSelection Whether the selection should be registered as a new\n   * selection on Linux.\n   */\n  public refresh(isLinuxMouseSelection?: boolean): void {\n    // Queue the refresh for the renderer\n    if (!this._refreshAnimationFrame) {\n      this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());\n    }\n\n    // If the platform is Linux and the refresh call comes from a mouse event,\n    // we need to update the selection for middle click to paste selection.\n    if (Browser.isLinux && isLinuxMouseSelection) {\n      const selectionText = this.selectionText;\n      if (selectionText.length) {\n        this._onLinuxMouseSelection.fire(this.selectionText);\n      }\n    }\n  }\n\n  /**\n   * Fires the refresh event, causing consumers to pick it up and redraw the\n   * selection state.\n   */\n  private _refresh(): void {\n    this._refreshAnimationFrame = undefined;\n    this._onRedrawRequest.fire({\n      start: this._model.finalSelectionStart,\n      end: this._model.finalSelectionEnd,\n      columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN\n    });\n  }\n\n  /**\n   * Checks if the current click was inside the current selection\n   * @param event The mouse event\n   */\n  public isClickInSelection(event: MouseEvent): boolean {\n    const coords = this._getMouseBufferCoords(event);\n    const start = this._model.finalSelectionStart;\n    const end = this._model.finalSelectionEnd;\n\n    if (!start || !end || !coords) {\n      return false;\n    }\n\n    return this._areCoordsInSelection(coords, start, end);\n  }\n\n  protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {\n    return (coords[1] > start[1] && coords[1] < end[1]) ||\n        (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||\n        (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||\n        (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);\n  }\n\n  /**\n   * Selects word at the current mouse event coordinates.\n   * @param event The mouse event.\n   */\n  public selectWordAtCursor(event: MouseEvent): void {\n    const coords = this._getMouseBufferCoords(event);\n    if (coords) {\n      this._selectWordAt(coords, false);\n      this._model.selectionEnd = undefined;\n      this.refresh(true);\n    }\n  }\n\n  /**\n   * Selects all text within the terminal.\n   */\n  public selectAll(): void {\n    this._model.isSelectAllActive = true;\n    this.refresh();\n    this._onSelectionChange.fire();\n  }\n\n  public selectLines(start: number, end: number): void {\n    this._model.clearSelection();\n    start = Math.max(start, 0);\n    end = Math.min(end, this._bufferService.buffer.lines.length - 1);\n    this._model.selectionStart = [0, start];\n    this._model.selectionEnd = [this._bufferService.cols, end];\n    this.refresh();\n    this._onSelectionChange.fire();\n  }\n\n  /**\n   * Handle the buffer being trimmed, adjust the selection position.\n   * @param amount The amount the buffer is being trimmed.\n   */\n  private _onTrim(amount: number): void {\n    const needsRefresh = this._model.onTrim(amount);\n    if (needsRefresh) {\n      this.refresh();\n    }\n  }\n\n  /**\n   * Gets the 0-based [x, y] buffer coordinates of the current mouse event.\n   * @param event The mouse event.\n   */\n  private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {\n    const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);\n    if (!coords) {\n      return undefined;\n    }\n\n    // Convert to 0-based\n    coords[0]--;\n    coords[1]--;\n\n    // Convert viewport coords to buffer coords\n    coords[1] += this._bufferService.buffer.ydisp;\n    return coords;\n  }\n\n  /**\n   * Gets the amount the viewport should be scrolled based on how far out of the\n   * terminal the mouse is.\n   * @param event The mouse event.\n   */\n  private _getMouseEventScrollAmount(event: MouseEvent): number {\n    let offset = getCoordsRelativeToElement(event, this._screenElement)[1];\n    const terminalHeight = this._bufferService.rows * Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);\n    if (offset >= 0 && offset <= terminalHeight) {\n      return 0;\n    }\n    if (offset > terminalHeight) {\n      offset -= terminalHeight;\n    }\n\n    offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);\n    offset /= DRAG_SCROLL_MAX_THRESHOLD;\n    return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));\n  }\n\n  /**\n   * Returns whether the selection manager should force selection, regardless of\n   * whether the terminal is in mouse events mode.\n   * @param event The mouse event.\n   */\n  public shouldForceSelection(event: MouseEvent): boolean {\n    if (Browser.isMac) {\n      return event.altKey && this._optionsService.options.macOptionClickForcesSelection;\n    }\n\n    return event.shiftKey;\n  }\n\n  /**\n   * Handles te mousedown event, setting up for a new selection.\n   * @param event The mousedown event.\n   */\n  public onMouseDown(event: MouseEvent): void {\n    this._mouseDownTimeStamp = event.timeStamp;\n    // If we have selection, we want the context menu on right click even if the\n    // terminal is in mouse mode.\n    if (event.button === 2 && this.hasSelection) {\n      return;\n    }\n\n    // Only action the primary button\n    if (event.button !== 0) {\n      return;\n    }\n\n    // Allow selection when using a specific modifier key, even when disabled\n    if (!this._enabled) {\n      if (!this.shouldForceSelection(event)) {\n        return;\n      }\n\n      // Don't send the mouse down event to the current process, we want to select\n      event.stopPropagation();\n    }\n\n    // Tell the browser not to start a regular selection\n    event.preventDefault();\n\n    // Reset drag scroll state\n    this._dragScrollAmount = 0;\n\n    if (this._enabled && event.shiftKey) {\n      this._onIncrementalClick(event);\n    } else {\n      if (event.detail === 1) {\n        this._onSingleClick(event);\n      } else if (event.detail === 2) {\n        this._onDoubleClick(event);\n      } else if (event.detail === 3) {\n        this._onTripleClick(event);\n      }\n    }\n\n    this._addMouseDownListeners();\n    this.refresh(true);\n  }\n\n  /**\n   * Adds listeners when mousedown is triggered.\n   */\n  private _addMouseDownListeners(): void {\n    // Listen on the document so that dragging outside of viewport works\n    if (this._screenElement.ownerDocument) {\n      this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);\n      this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);\n    }\n    this._dragScrollIntervalTimer = window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);\n  }\n\n  /**\n   * Removes the listeners that are registered when mousedown is triggered.\n   */\n  private _removeMouseDownListeners(): void {\n    if (this._screenElement.ownerDocument) {\n      this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);\n      this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);\n    }\n    clearInterval(this._dragScrollIntervalTimer);\n    this._dragScrollIntervalTimer = undefined;\n  }\n\n  /**\n   * Performs an incremental click, setting the selection end position to the mouse\n   * position.\n   * @param event The mouse event.\n   */\n  private _onIncrementalClick(event: MouseEvent): void {\n    if (this._model.selectionStart) {\n      this._model.selectionEnd = this._getMouseBufferCoords(event);\n    }\n  }\n\n  /**\n   * Performs a single click, resetting relevant state and setting the selection\n   * start position.\n   * @param event The mouse event.\n   */\n  private _onSingleClick(event: MouseEvent): void {\n    this._model.selectionStartLength = 0;\n    this._model.isSelectAllActive = false;\n    this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;\n\n    // Initialize the new selection\n    this._model.selectionStart = this._getMouseBufferCoords(event);\n    if (!this._model.selectionStart) {\n      return;\n    }\n    this._model.selectionEnd = undefined;\n\n    // Ensure the line exists\n    const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);\n    if (!line) {\n      return;\n    }\n\n    // Return early if the click event is not in the buffer (eg. in scroll bar)\n    if (line.length === this._model.selectionStart[0]) {\n      return;\n    }\n\n    // If the mouse is over the second half of a wide character, adjust the\n    // selection to cover the whole character\n    if (line.hasWidth(this._model.selectionStart[0]) === 0) {\n      this._model.selectionStart[0]++;\n    }\n  }\n\n  /**\n   * Performs a double click, selecting the current work.\n   * @param event The mouse event.\n   */\n  private _onDoubleClick(event: MouseEvent): void {\n    const coords = this._getMouseBufferCoords(event);\n    if (coords) {\n      this._activeSelectionMode = SelectionMode.WORD;\n      this._selectWordAt(coords, true);\n    }\n  }\n\n  /**\n   * Performs a triple click, selecting the current line and activating line\n   * select mode.\n   * @param event The mouse event.\n   */\n  private _onTripleClick(event: MouseEvent): void {\n    const coords = this._getMouseBufferCoords(event);\n    if (coords) {\n      this._activeSelectionMode = SelectionMode.LINE;\n      this._selectLineAt(coords[1]);\n    }\n  }\n\n  /**\n   * Returns whether the selection manager should operate in column select mode\n   * @param event the mouse or keyboard event\n   */\n  public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {\n    return event.altKey && !(Browser.isMac && this._optionsService.options.macOptionClickForcesSelection);\n  }\n\n  /**\n   * Handles the mousemove event when the mouse button is down, recording the\n   * end of the selection and refreshing the selection.\n   * @param event The mousemove event.\n   */\n  private _onMouseMove(event: MouseEvent): void {\n    // If the mousemove listener is active it means that a selection is\n    // currently being made, we should stop propagation to prevent mouse events\n    // to be sent to the pty.\n    event.stopImmediatePropagation();\n\n    // Do nothing if there is no selection start, this can happen if the first\n    // click in the terminal is an incremental click\n    if (!this._model.selectionStart) {\n      return;\n    }\n\n    // Record the previous position so we know whether to redraw the selection\n    // at the end.\n    const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;\n\n    // Set the initial selection end based on the mouse coordinates\n    this._model.selectionEnd = this._getMouseBufferCoords(event);\n    if (!this._model.selectionEnd) {\n      this.refresh(true);\n      return;\n    }\n\n    // Select the entire line if line select mode is active.\n    if (this._activeSelectionMode === SelectionMode.LINE) {\n      if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {\n        this._model.selectionEnd[0] = 0;\n      } else {\n        this._model.selectionEnd[0] = this._bufferService.cols;\n      }\n    } else if (this._activeSelectionMode === SelectionMode.WORD) {\n      this._selectToWordAt(this._model.selectionEnd);\n    }\n\n    // Determine the amount of scrolling that will happen.\n    this._dragScrollAmount = this._getMouseEventScrollAmount(event);\n\n    // If the cursor was above or below the viewport, make sure it's at the\n    // start or end of the viewport respectively. This should only happen when\n    // NOT in column select mode.\n    if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n      if (this._dragScrollAmount > 0) {\n        this._model.selectionEnd[0] = this._bufferService.cols;\n      } else if (this._dragScrollAmount < 0) {\n        this._model.selectionEnd[0] = 0;\n      }\n    }\n\n    // If the character is a wide character include the cell to the right in the\n    // selection. Note that selections at the very end of the line will never\n    // have a character.\n    const buffer = this._bufferService.buffer;\n    if (this._model.selectionEnd[1] < buffer.lines.length) {\n      const line = buffer.lines.get(this._model.selectionEnd[1]);\n      if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {\n        this._model.selectionEnd[0]++;\n      }\n    }\n\n    // Only draw here if the selection changes.\n    if (!previousSelectionEnd ||\n      previousSelectionEnd[0] !== this._model.selectionEnd[0] ||\n      previousSelectionEnd[1] !== this._model.selectionEnd[1]) {\n      this.refresh(true);\n    }\n  }\n\n  /**\n   * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the\n   * scrolling of the viewport.\n   */\n  private _dragScroll(): void {\n    if (!this._model.selectionEnd || !this._model.selectionStart) {\n      return;\n    }\n    if (this._dragScrollAmount) {\n      this._scrollLines(this._dragScrollAmount, false);\n      // Re-evaluate selection\n      // If the cursor was above or below the viewport, make sure it's at the\n      // start or end of the viewport respectively. This should only happen when\n      // NOT in column select mode.\n      const buffer = this._bufferService.buffer;\n      if (this._dragScrollAmount > 0) {\n        if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n          this._model.selectionEnd[0] = this._bufferService.cols;\n        }\n        this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);\n      } else {\n        if (this._activeSelectionMode !== SelectionMode.COLUMN) {\n          this._model.selectionEnd[0] = 0;\n        }\n        this._model.selectionEnd[1] = buffer.ydisp;\n      }\n      this.refresh();\n    }\n  }\n\n  /**\n   * Handles the mouseup event, removing the mousedown listeners.\n   * @param event The mouseup event.\n   */\n  private _onMouseUp(event: MouseEvent): void {\n    const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;\n\n    this._removeMouseDownListeners();\n\n    if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) {\n      if (event.altKey && this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {\n        const coordinates = this._mouseService.getCoords(\n          event,\n          this._element,\n          this._bufferService.cols,\n          this._bufferService.rows,\n          false\n        );\n        if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {\n          const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);\n          this._coreService.triggerDataEvent(sequence, true);\n        }\n      }\n    } else if (this.hasSelection) {\n      this._onSelectionChange.fire();\n    }\n  }\n\n  private _onBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {\n    this.clearSelection();\n    // Only adjust the selection on trim, shiftElements is rarely used (only in\n    // reverseIndex) and delete in a splice is only ever used when the same\n    // number of elements was just added. Given this is could actually be\n    // beneficial to leave the selection as is for these cases.\n    if (this._trimListener) {\n      this._trimListener.dispose();\n    }\n    this._trimListener = e.activeBuffer.lines.onTrim(amount => this._onTrim(amount));\n  }\n\n  /**\n   * Converts a viewport column to the character index on the buffer line, the\n   * latter takes into account wide characters.\n   * @param coords The coordinates to find the 2 index for.\n   */\n  private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, coords: [number, number]): number {\n    let charIndex = coords[0];\n    for (let i = 0; coords[0] >= i; i++) {\n      const length = bufferLine.loadCell(i, this._workCell).getChars().length;\n      if (this._workCell.getWidth() === 0) {\n        // Wide characters aren't included in the line string so decrement the\n        // index so the index is back on the wide character.\n        charIndex--;\n      } else if (length > 1 && coords[0] !== i) {\n        // Emojis take up multiple characters, so adjust accordingly. For these\n        // we don't want ot include the character at the column as we're\n        // returning the start index in the string, not the end index.\n        charIndex += length - 1;\n      }\n    }\n    return charIndex;\n  }\n\n  public setSelection(col: number, row: number, length: number): void {\n    this._model.clearSelection();\n    this._removeMouseDownListeners();\n    this._model.selectionStart = [col, row];\n    this._model.selectionStartLength = length;\n    this.refresh();\n  }\n\n  /**\n   * Gets positional information for the word at the coordinated specified.\n   * @param coords The coordinates to get the word at.\n   */\n  private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {\n    // Ensure coords are within viewport (eg. not within scroll bar)\n    if (coords[0] >= this._bufferService.cols) {\n      return undefined;\n    }\n\n    const buffer = this._bufferService.buffer;\n    const bufferLine = buffer.lines.get(coords[1]);\n    if (!bufferLine) {\n      return undefined;\n    }\n\n    const line = buffer.translateBufferLineToString(coords[1], false);\n\n    // Get actual index, taking into consideration wide characters\n    let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);\n    let endIndex = startIndex;\n\n    // Record offset to be used later\n    const charOffset = coords[0] - startIndex;\n    let leftWideCharCount = 0;\n    let rightWideCharCount = 0;\n    let leftLongCharOffset = 0;\n    let rightLongCharOffset = 0;\n\n    if (line.charAt(startIndex) === ' ') {\n      // Expand until non-whitespace is hit\n      while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {\n        startIndex--;\n      }\n      while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {\n        endIndex++;\n      }\n    } else {\n      // Expand until whitespace is hit. This algorithm works by scanning left\n      // and right from the starting position, keeping both the index format\n      // (line) and the column format (bufferLine) in sync. When a wide\n      // character is hit, it is recorded and the column index is adjusted.\n      let startCol = coords[0];\n      let endCol = coords[0];\n\n      // Consider the initial position, skip it and increment the wide char\n      // variable\n      if (bufferLine.getWidth(startCol) === 0) {\n        leftWideCharCount++;\n        startCol--;\n      }\n      if (bufferLine.getWidth(endCol) === 2) {\n        rightWideCharCount++;\n        endCol++;\n      }\n\n      // Adjust the end index for characters whose length are > 1 (emojis)\n      const length = bufferLine.getString(endCol).length;\n      if (length > 1) {\n        rightLongCharOffset += length - 1;\n        endIndex += length - 1;\n      }\n\n      // Expand the string in both directions until a space is hit\n      while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {\n        bufferLine.loadCell(startCol - 1, this._workCell);\n        const length = this._workCell.getChars().length;\n        if (this._workCell.getWidth() === 0) {\n          // If the next character is a wide char, record it and skip the column\n          leftWideCharCount++;\n          startCol--;\n        } else if (length > 1) {\n          // If the next character's string is longer than 1 char (eg. emoji),\n          // adjust the index\n          leftLongCharOffset += length - 1;\n          startIndex -= length - 1;\n        }\n        startIndex--;\n        startCol--;\n      }\n      while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {\n        bufferLine.loadCell(endCol + 1, this._workCell);\n        const length = this._workCell.getChars().length;\n        if (this._workCell.getWidth() === 2) {\n          // If the next character is a wide char, record it and skip the column\n          rightWideCharCount++;\n          endCol++;\n        } else if (length > 1) {\n          // If the next character's string is longer than 1 char (eg. emoji),\n          // adjust the index\n          rightLongCharOffset += length - 1;\n          endIndex += length - 1;\n        }\n        endIndex++;\n        endCol++;\n      }\n    }\n\n    // Incremenet the end index so it is at the start of the next character\n    endIndex++;\n\n    // Calculate the start _column_, converting the the string indexes back to\n    // column coordinates.\n    let start =\n        startIndex // The index of the selection's start char in the line string\n        + charOffset // The difference between the initial char's column and index\n        - leftWideCharCount // The number of wide chars left of the initial char\n        + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n\n    // Calculate the length in _columns_, converting the the string indexes back\n    // to column coordinates.\n    let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols\n        endIndex // The index of the selection's end char in the line string\n        - startIndex // The index of the selection's start char in the line string\n        + leftWideCharCount // The number of wide chars left of the initial char\n        + rightWideCharCount // The number of wide chars right of the initial char (inclusive)\n        - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)\n        - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)\n\n    if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {\n      return undefined;\n    }\n\n    // Recurse upwards if the line is wrapped and the word wraps to the above line\n    if (followWrappedLinesAbove) {\n      if (start === 0 && bufferLine.getCodePoint(0) !== 32 /*' '*/) {\n        const previousBufferLine = buffer.lines.get(coords[1] - 1);\n        if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {\n          const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);\n          if (previousLineWordPosition) {\n            const offset = this._bufferService.cols - previousLineWordPosition.start;\n            start -= offset;\n            length += offset;\n          }\n        }\n      }\n    }\n\n    // Recurse downwards if the line is wrapped and the word wraps to the next line\n    if (followWrappedLinesBelow) {\n      if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {\n        const nextBufferLine = buffer.lines.get(coords[1] + 1);\n        if (nextBufferLine && nextBufferLine.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /*' '*/) {\n          const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);\n          if (nextLineWordPosition) {\n            length += nextLineWordPosition.length;\n          }\n        }\n      }\n    }\n\n    return { start, length };\n  }\n\n  /**\n   * Selects the word at the coordinates specified.\n   * @param coords The coordinates to get the word at.\n   * @param allowWhitespaceOnlySelection If whitespace should be selected\n   */\n  protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {\n    const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);\n    if (wordPosition) {\n      // Adjust negative start value\n      while (wordPosition.start < 0) {\n        wordPosition.start += this._bufferService.cols;\n        coords[1]--;\n      }\n      this._model.selectionStart = [wordPosition.start, coords[1]];\n      this._model.selectionStartLength = wordPosition.length;\n    }\n  }\n\n  /**\n   * Sets the selection end to the word at the coordinated specified.\n   * @param coords The coordinates to get the word at.\n   */\n  private _selectToWordAt(coords: [number, number]): void {\n    const wordPosition = this._getWordAt(coords, true);\n    if (wordPosition) {\n      let endRow = coords[1];\n\n      // Adjust negative start value\n      while (wordPosition.start < 0) {\n        wordPosition.start += this._bufferService.cols;\n        endRow--;\n      }\n\n      // Adjust wrapped length value, this only needs to happen when values are reversed as in that\n      // case we're interested in the start of the word, not the end\n      if (!this._model.areSelectionValuesReversed()) {\n        while (wordPosition.start + wordPosition.length > this._bufferService.cols) {\n          wordPosition.length -= this._bufferService.cols;\n          endRow++;\n        }\n      }\n\n      this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];\n    }\n  }\n\n  /**\n   * Gets whether the character is considered a word separator by the select\n   * word logic.\n   * @param char The character to check.\n   */\n  private _isCharWordSeparator(cell: CellData): boolean {\n    // Zero width characters are never separators as they are always to the\n    // right of wide characters\n    if (cell.getWidth() === 0) {\n      return false;\n    }\n    return this._optionsService.options.wordSeparator.indexOf(cell.getChars()) >= 0;\n  }\n\n  /**\n   * Selects the line specified.\n   * @param line The line index.\n   */\n  protected _selectLineAt(line: number): void {\n    const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);\n    this._model.selectionStart = [0, wrappedRange.first];\n    this._model.selectionEnd = [this._bufferService.cols, wrappedRange.last];\n    this._model.selectionStartLength = 0;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService } from 'common/services/Services';\n\n/**\n * Represents a selection within the buffer. This model only cares about column\n * and row coordinates, not wide characters.\n */\nexport class SelectionModel {\n  /**\n   * Whether select all is currently active.\n   */\n  public isSelectAllActive: boolean = false;\n\n  /**\n   * The minimal length of the selection from the start position. When double\n   * clicking on a word, the word will be selected which makes the selection\n   * start at the start of the word and makes this variable the length.\n   */\n  public selectionStartLength: number = 0;\n\n  /**\n   * The [x, y] position the selection starts at.\n   */\n  public selectionStart: [number, number] | undefined;\n\n  /**\n   * The [x, y] position the selection ends at.\n   */\n  public selectionEnd: [number, number] | undefined;\n\n  constructor(\n    private _bufferService: IBufferService\n  ) {\n  }\n\n  /**\n   * Clears the current selection.\n   */\n  public clearSelection(): void {\n    this.selectionStart = undefined;\n    this.selectionEnd = undefined;\n    this.isSelectAllActive = false;\n    this.selectionStartLength = 0;\n  }\n\n  /**\n   * The final selection start, taking into consideration select all.\n   */\n  public get finalSelectionStart(): [number, number] | undefined {\n    if (this.isSelectAllActive) {\n      return [0, 0];\n    }\n\n    if (!this.selectionEnd || !this.selectionStart) {\n      return this.selectionStart;\n    }\n\n    return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;\n  }\n\n  /**\n   * The final selection end, taking into consideration select all, double click\n   * word selection and triple click line selection.\n   */\n  public get finalSelectionEnd(): [number, number] | undefined {\n    if (this.isSelectAllActive) {\n      return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];\n    }\n\n    if (!this.selectionStart) {\n      return undefined;\n    }\n\n    // Use the selection start + length if the end doesn't exist or they're reversed\n    if (!this.selectionEnd || this.areSelectionValuesReversed()) {\n      const startPlusLength = this.selectionStart[0] + this.selectionStartLength;\n      if (startPlusLength > this._bufferService.cols) {\n        return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];\n      }\n      return [startPlusLength, this.selectionStart[1]];\n    }\n\n    // Ensure the the word/line is selected after a double/triple click\n    if (this.selectionStartLength) {\n      // Select the larger of the two when start and end are on the same line\n      if (this.selectionEnd[1] === this.selectionStart[1]) {\n        return [Math.max(this.selectionStart[0] + this.selectionStartLength, this.selectionEnd[0]), this.selectionEnd[1]];\n      }\n    }\n    return this.selectionEnd;\n  }\n\n  /**\n   * Returns whether the selection start and end are reversed.\n   */\n  public areSelectionValuesReversed(): boolean {\n    const start = this.selectionStart;\n    const end = this.selectionEnd;\n    if (!start || !end) {\n      return false;\n    }\n    return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);\n  }\n\n  /**\n   * Handle the buffer being trimmed, adjust the selection position.\n   * @param amount The amount the buffer is being trimmed.\n   * @return Whether a refresh is necessary.\n   */\n  public onTrim(amount: number): boolean {\n    // Adjust the selection position based on the trimmed amount.\n    if (this.selectionStart) {\n      this.selectionStart[1] -= amount;\n    }\n    if (this.selectionEnd) {\n      this.selectionEnd[1] -= amount;\n    }\n\n    // The selection has moved off the buffer, clear it.\n    if (this.selectionEnd && this.selectionEnd[1] < 0) {\n      this.clearSelection();\n      return true;\n    }\n\n    // If the selection start is trimmed, ensure the start column is 0.\n    if (this.selectionStart && this.selectionStart[1] < 0) {\n      this.selectionStart[1] = 0;\n    }\n    return false;\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { C0 } from 'common/data/EscapeSequences';\nimport { IBufferService } from 'common/services/Services';\n\nconst enum Direction {\n  UP = 'A',\n  DOWN = 'B',\n  RIGHT = 'C',\n  LEFT = 'D'\n}\n\n/**\n * Concatenates all the arrow sequences together.\n * Resets the starting row to an unwrapped row, moves to the requested row,\n * then moves to requested col.\n */\nexport function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  const startX = bufferService.buffer.x;\n  const startY = bufferService.buffer.y;\n\n  // The alt buffer should try to navigate between rows\n  if (!bufferService.buffer.hasScrollback) {\n    return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) +\n      moveToRequestedRow(startY, targetY, bufferService, applicationCursor) +\n      moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor);\n  }\n\n  // Only move horizontally for the normal buffer\n  return moveHorizontallyOnly(startX, startY, targetX, targetY, bufferService, applicationCursor);\n}\n\n/**\n * If the initial position of the cursor is on a row that is wrapped, move the\n * cursor up to the first row that is not wrapped to have accurate vertical\n * positioning.\n */\nfunction resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) {\n    return '';\n  }\n  return repeat(bufferLine(\n    startX, startY, startX,\n    startY - wrappedRowsForRow(bufferService, startY), false, bufferService\n  ).length, sequence(Direction.LEFT, applicationCursor));\n}\n\n/**\n * Using the reset starting and ending row, move to the requested row,\n * ignoring wrapped rows\n */\nfunction moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  const startRow = startY - wrappedRowsForRow(bufferService, startY);\n  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);\n\n  const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService);\n\n  return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor));\n}\n\n/**\n * Move to the requested col on the ending row\n */\nfunction moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  let startRow;\n  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) {\n    startRow = targetY - wrappedRowsForRow(bufferService, targetY);\n  } else {\n    startRow = startY;\n  }\n\n  const endRow = targetY;\n  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);\n\n  return repeat(bufferLine(\n    startX, startRow, targetX, endRow,\n    direction === Direction.RIGHT, bufferService\n  ).length, sequence(direction, applicationCursor));\n}\n\nfunction moveHorizontallyOnly(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {\n  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);\n  return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor));\n}\n\n/**\n * Utility functions\n */\n\n/**\n * Calculates the number of wrapped rows between the unwrapped starting and\n * ending rows. These rows need to ignored since the cursor skips over them.\n */\nfunction wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number {\n  let wrappedRows = 0;\n  const startRow = startY - wrappedRowsForRow(bufferService, startY);\n  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);\n\n  for (let i = 0; i < Math.abs(startRow - endRow); i++) {\n    const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1;\n    const line = bufferService.buffer.lines.get(startRow + (direction * i));\n    if (line && line.isWrapped) {\n      wrappedRows++;\n    }\n  }\n\n  return wrappedRows;\n}\n\n/**\n * Calculates the number of wrapped rows that make up a given row.\n * @param currentRow The row to determine how many wrapped rows make it up\n */\nfunction wrappedRowsForRow(bufferService: IBufferService, currentRow: number): number {\n  let rowCount = 0;\n  let line = bufferService.buffer.lines.get(currentRow);\n  let lineWraps = line && line.isWrapped;\n\n  while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) {\n    rowCount++;\n    line = bufferService.buffer.lines.get(--currentRow);\n    lineWraps = line && line.isWrapped;\n  }\n\n  return rowCount;\n}\n\n/**\n * Direction determiners\n */\n\n/**\n * Determines if the right or left arrow is needed\n */\nfunction horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction {\n  let startRow;\n  if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) {\n    startRow = targetY - wrappedRowsForRow(bufferService, targetY);\n  } else {\n    startRow = startY;\n  }\n\n  if ((startX < targetX &&\n    startRow <= targetY) || // down/right or same y/right\n    (startX >= targetX &&\n    startRow < targetY)) {  // down/left or same y/left\n    return Direction.RIGHT;\n  }\n  return Direction.LEFT;\n}\n\n/**\n * Determines if the up or down arrow is needed\n */\nfunction verticalDirection(startY: number, targetY: number): Direction {\n  return startY > targetY ? Direction.UP : Direction.DOWN;\n}\n\n/**\n * Constructs the string of chars in the buffer from a starting row and col\n * to an ending row and col\n * @param startCol The starting column position\n * @param startRow The starting row position\n * @param endCol The ending column position\n * @param endRow The ending row position\n * @param forward Direction to move\n */\nfunction bufferLine(\n  startCol: number,\n  startRow: number,\n  endCol: number,\n  endRow: number,\n  forward: boolean,\n  bufferService: IBufferService\n): string {\n  let currentCol = startCol;\n  let currentRow = startRow;\n  let bufferStr = '';\n\n  while (currentCol !== endCol || currentRow !== endRow) {\n    currentCol += forward ? 1 : -1;\n\n    if (forward && currentCol > bufferService.cols - 1) {\n      bufferStr += bufferService.buffer.translateBufferLineToString(\n        currentRow, false, startCol, currentCol\n      );\n      currentCol = 0;\n      startCol = 0;\n      currentRow++;\n    } else if (!forward && currentCol < 0) {\n      bufferStr += bufferService.buffer.translateBufferLineToString(\n        currentRow, false, 0, startCol + 1\n      );\n      currentCol = bufferService.cols - 1;\n      startCol = currentCol;\n      currentRow--;\n    }\n  }\n\n  return bufferStr + bufferService.buffer.translateBufferLineToString(\n    currentRow, false, startCol, currentCol\n  );\n}\n\n/**\n * Constructs the escape sequence for clicking an arrow\n * @param direction The direction to move\n */\nfunction sequence(direction: Direction, applicationCursor: boolean): string {\n  const mod =  applicationCursor ? 'O' : '[';\n  return C0.ESC + mod + direction;\n}\n\n/**\n * Returns a string repeated a given number of times\n * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\n * @param count The number of times to repeat the string\n * @param string The string that is to be repeated\n */\nfunction repeat(count: number, str: string): string {\n  count = Math.floor(count);\n  let rpt = '';\n  for (let i = 0; i < count; i++) {\n    rpt += str;\n  }\n  return rpt;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService } from 'common/services/Services';\nimport { ISoundService } from 'browser/services/Services';\n\nexport class SoundService implements ISoundService {\n  serviceBrand: any;\n\n  private static _audioContext: AudioContext;\n\n  static get audioContext(): AudioContext | null {\n    if (!SoundService._audioContext) {\n      const audioContextCtor: typeof AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;\n      if (!audioContextCtor) {\n        console.warn('Web Audio API is not supported by this browser. Consider upgrading to the latest version');\n        return null;\n      }\n      SoundService._audioContext = new audioContextCtor();\n    }\n    return SoundService._audioContext;\n  }\n\n  constructor(\n    @IOptionsService private _optionsService: IOptionsService\n  ) {\n  }\n\n  public playBellSound(): void {\n    const ctx = SoundService.audioContext;\n    if (!ctx) {\n      return;\n    }\n    const bellAudioSource = ctx.createBufferSource();\n    ctx.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)), (buffer) => {\n      bellAudioSource.buffer = buffer;\n      bellAudioSource.connect(ctx.destination);\n      bellAudioSource.start(0);\n    });\n  }\n\n  private _base64ToArrayBuffer(base64: string): ArrayBuffer {\n    const binaryString = window.atob(base64);\n    const len = binaryString.length;\n    const bytes = new Uint8Array(len);\n\n    for (let i = 0; i < len; i++) {\n      bytes[i] = binaryString.charCodeAt(i);\n    }\n\n    return bytes.buffer;\n  }\n\n  private _removeMimeType(dataURI: string): string {\n    // Split the input to get the mime-type and the data itself\n    const splitUri = dataURI.split(',');\n\n    // Return only the data\n    return splitUri[1];\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { Disposable } from 'common/Lifecycle';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { IMouseService, ISelectionService } from 'browser/services/Services';\nimport { IMouseZoneManager, IMouseZone } from 'browser/Types';\nimport { IBufferService } from 'common/services/Services';\n\nconst HOVER_DURATION = 500;\n\n/**\n * The MouseZoneManager allows components to register zones within the terminal\n * that trigger hover and click callbacks.\n *\n * This class was intentionally made not so robust initially as the only case it\n * needed to support was single-line links which never overlap. Improvements can\n * be made in the future.\n */\nexport class MouseZoneManager extends Disposable implements IMouseZoneManager {\n  private _zones: IMouseZone[] = [];\n\n  private _areZonesActive: boolean = false;\n  private _mouseMoveListener: (e: MouseEvent) => any;\n  private _mouseLeaveListener: (e: MouseEvent) => any;\n  private _clickListener: (e: MouseEvent) => any;\n\n  private _tooltipTimeout: number | undefined;\n  private _currentZone: IMouseZone | undefined;\n  private _lastHoverCoords: [number | undefined, number | undefined] = [undefined, undefined];\n  private _initialSelectionLength: number = 0;\n\n  constructor(\n    private readonly _element: HTMLElement,\n    private readonly _screenElement: HTMLElement,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @IMouseService private readonly _mouseService: IMouseService,\n    @ISelectionService private readonly _selectionService: ISelectionService\n  ) {\n    super();\n\n    this.register(addDisposableDomListener(this._element, 'mousedown', e => this._onMouseDown(e)));\n\n    // These events are expensive, only listen to it when mouse zones are active\n    this._mouseMoveListener = e => this._onMouseMove(e);\n    this._mouseLeaveListener = e => this._onMouseLeave(e);\n    this._clickListener = e => this._onClick(e);\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this._deactivate();\n  }\n\n  public add(zone: IMouseZone): void {\n    this._zones.push(zone);\n    if (this._zones.length === 1) {\n      this._activate();\n    }\n  }\n\n  public clearAll(start?: number, end?: number): void {\n    // Exit if there's nothing to clear\n    if (this._zones.length === 0) {\n      return;\n    }\n\n    // Clear all if start/end weren't set\n    if (!start || !end) {\n      start = 0;\n      end = this._bufferService.rows - 1;\n    }\n\n    // Iterate through zones and clear them out if they're within the range\n    for (let i = 0; i < this._zones.length; i++) {\n      const zone = this._zones[i];\n      if ((zone.y1 > start && zone.y1 <= end + 1) ||\n          (zone.y2 > start && zone.y2 <= end + 1) ||\n          (zone.y1 < start && zone.y2 > end + 1)) {\n        if (this._currentZone && this._currentZone === zone) {\n          this._currentZone.leaveCallback();\n          this._currentZone = undefined;\n        }\n        this._zones.splice(i--, 1);\n      }\n    }\n\n    // Deactivate the mouse zone manager if all the zones have been removed\n    if (this._zones.length === 0) {\n      this._deactivate();\n    }\n  }\n\n  private _activate(): void {\n    if (!this._areZonesActive) {\n      this._areZonesActive = true;\n      this._element.addEventListener('mousemove', this._mouseMoveListener);\n      this._element.addEventListener('mouseleave', this._mouseLeaveListener);\n      this._element.addEventListener('click', this._clickListener);\n    }\n  }\n\n  private _deactivate(): void {\n    if (this._areZonesActive) {\n      this._areZonesActive = false;\n      this._element.removeEventListener('mousemove', this._mouseMoveListener);\n      this._element.removeEventListener('mouseleave', this._mouseLeaveListener);\n      this._element.removeEventListener('click', this._clickListener);\n    }\n  }\n\n  private _onMouseMove(e: MouseEvent): void {\n    // TODO: Ideally this would only clear the hover state when the mouse moves\n    // outside of the mouse zone\n    if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {\n      this._onHover(e);\n      // Record the current coordinates\n      this._lastHoverCoords = [e.pageX, e.pageY];\n    }\n  }\n\n  private _onHover(e: MouseEvent): void {\n    const zone = this._findZoneEventAt(e);\n\n    // Do nothing if the zone is the same\n    if (zone === this._currentZone) {\n      return;\n    }\n\n    // Fire the hover end callback and cancel any existing timer if a new zone\n    // is being hovered\n    if (this._currentZone) {\n      this._currentZone.leaveCallback();\n      this._currentZone = undefined;\n      if (this._tooltipTimeout) {\n        clearTimeout(this._tooltipTimeout);\n      }\n    }\n\n    // Exit if there is not zone\n    if (!zone) {\n      return;\n    }\n    this._currentZone = zone;\n\n    // Trigger the hover callback\n    if (zone.hoverCallback) {\n      zone.hoverCallback(e);\n    }\n\n    // Restart the tooltip timeout\n    this._tooltipTimeout = <number><any>setTimeout(() => this._onTooltip(e), HOVER_DURATION);\n  }\n\n  private _onTooltip(e: MouseEvent): void {\n    this._tooltipTimeout = undefined;\n    const zone = this._findZoneEventAt(e);\n    if (zone && zone.tooltipCallback) {\n      zone.tooltipCallback(e);\n    }\n  }\n\n  private _onMouseDown(e: MouseEvent): void {\n    // Store current terminal selection length, to check if we're performing\n    // a selection operation\n    this._initialSelectionLength = this._getSelectionLength();\n\n    // Ignore the event if there are no zones active\n    if (!this._areZonesActive) {\n      return;\n    }\n\n    // Find the active zone, prevent event propagation if found to prevent other\n    // components from handling the mouse event.\n    const zone = this._findZoneEventAt(e);\n    if (zone) {\n      if (zone.willLinkActivate(e)) {\n        e.preventDefault();\n        e.stopImmediatePropagation();\n      }\n    }\n  }\n\n  private _onMouseLeave(e: MouseEvent): void {\n    // Fire the hover end callback and cancel any existing timer if the mouse\n    // leaves the terminal element\n    if (this._currentZone) {\n      this._currentZone.leaveCallback();\n      this._currentZone = undefined;\n      if (this._tooltipTimeout) {\n        clearTimeout(this._tooltipTimeout);\n      }\n    }\n  }\n\n  private _onClick(e: MouseEvent): void {\n    // Find the active zone and click it if found and no selection was\n    // being performed\n    const zone = this._findZoneEventAt(e);\n    const currentSelectionLength = this._getSelectionLength();\n\n    if (zone && currentSelectionLength === this._initialSelectionLength) {\n      zone.clickCallback(e);\n      e.preventDefault();\n      e.stopImmediatePropagation();\n    }\n  }\n\n  private _getSelectionLength(): number {\n    const selectionText = this._selectionService.selectionText;\n    return selectionText ? selectionText.length : 0;\n  }\n\n  private _findZoneEventAt(e: MouseEvent): IMouseZone | undefined {\n    const coords = this._mouseService.getCoords(e, this._screenElement, this._bufferService.cols, this._bufferService.rows);\n    if (!coords) {\n      return undefined;\n    }\n    const x = coords[0];\n    const y = coords[1];\n    for (let i = 0; i < this._zones.length; i++) {\n      const zone = this._zones[i];\n      if (zone.y1 === zone.y2) {\n        // Single line link\n        if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {\n          return zone;\n        }\n      } else {\n        // Multi-line link\n        if ((y === zone.y1 && x >= zone.x1) ||\n            (y === zone.y2 && x < zone.x2) ||\n            (y > zone.y1 && y < zone.y2)) {\n          return zone;\n        }\n      }\n    }\n    return undefined;\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport * as Strings from './browser/LocalizableStrings';\nimport { ITerminal } from './Types';\nimport { IBuffer } from 'common/buffer/Types';\nimport { isMac } from 'common/Platform';\nimport { RenderDebouncer } from 'browser/RenderDebouncer';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { Disposable } from 'common/Lifecycle';\nimport { ScreenDprMonitor } from 'browser/ScreenDprMonitor';\nimport { IRenderService } from 'browser/services/Services';\n\nconst MAX_ROWS_TO_READ = 20;\n\nconst enum BoundaryPosition {\n  TOP,\n  BOTTOM\n}\n\nexport class AccessibilityManager extends Disposable {\n  private _accessibilityTreeRoot: HTMLElement;\n  private _rowContainer: HTMLElement;\n  private _rowElements: HTMLElement[];\n  private _liveRegion: HTMLElement;\n  private _liveRegionLineCount: number = 0;\n\n  private _renderRowsDebouncer: RenderDebouncer;\n  private _screenDprMonitor: ScreenDprMonitor;\n\n  private _topBoundaryFocusListener: (e: FocusEvent) => void;\n  private _bottomBoundaryFocusListener: (e: FocusEvent) => void;\n\n  /**\n   * This queue has a character pushed to it for keys that are pressed, if the\n   * next character added to the terminal is equal to the key char then it is\n   * not announced (added to live region) because it has already been announced\n   * by the textarea event (which cannot be canceled). There are some race\n   * condition cases if there is typing while data is streaming, but this covers\n   * the main case of typing into the prompt and inputting the answer to a\n   * question (Y/N, etc.).\n   */\n  private _charsToConsume: string[] = [];\n\n  private _charsToAnnounce: string = '';\n\n  constructor(\n    private readonly _terminal: ITerminal,\n    private readonly _renderService: IRenderService\n  ) {\n    super();\n    this._accessibilityTreeRoot = document.createElement('div');\n    this._accessibilityTreeRoot.classList.add('xterm-accessibility');\n\n    this._rowContainer = document.createElement('div');\n    this._rowContainer.classList.add('xterm-accessibility-tree');\n    this._rowElements = [];\n    for (let i = 0; i < this._terminal.rows; i++) {\n      this._rowElements[i] = this._createAccessibilityTreeNode();\n      this._rowContainer.appendChild(this._rowElements[i]);\n    }\n\n    this._topBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.TOP);\n    this._bottomBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.BOTTOM);\n    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n    this._refreshRowsDimensions();\n    this._accessibilityTreeRoot.appendChild(this._rowContainer);\n\n    this._renderRowsDebouncer = new RenderDebouncer(this._renderRows.bind(this));\n    this._refreshRows();\n\n    this._liveRegion = document.createElement('div');\n    this._liveRegion.classList.add('live-region');\n    this._liveRegion.setAttribute('aria-live', 'assertive');\n    this._accessibilityTreeRoot.appendChild(this._liveRegion);\n\n    this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityTreeRoot);\n\n    this.register(this._renderRowsDebouncer);\n    this.register(this._terminal.onResize(e => this._onResize(e.rows)));\n    this.register(this._terminal.onRender(e => this._refreshRows(e.start, e.end)));\n    this.register(this._terminal.onScroll(() => this._refreshRows()));\n    // Line feed is an issue as the prompt won't be read out after a command is run\n    this.register(this._terminal.onA11yChar(char => this._onChar(char)));\n    this.register(this._terminal.onLineFeed(() => this._onChar('\\n')));\n    this.register(this._terminal.onA11yTab(spaceCount => this._onTab(spaceCount)));\n    this.register(this._terminal.onKey(e => this._onKey(e.key)));\n    this.register(this._terminal.onBlur(() => this._clearLiveRegion()));\n    this.register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions()));\n\n    this._screenDprMonitor = new ScreenDprMonitor();\n    this.register(this._screenDprMonitor);\n    this._screenDprMonitor.setListener(() => this._refreshRowsDimensions());\n    // This shouldn't be needed on modern browsers but is present in case the\n    // media query that drives the ScreenDprMonitor isn't supported\n    this.register(addDisposableDomListener(window, 'resize', () => this._refreshRowsDimensions()));\n  }\n\n  public dispose(): void {\n    super.dispose();\n    this._terminal.element.removeChild(this._accessibilityTreeRoot);\n    this._rowElements.length = 0;\n  }\n\n  private _onBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void {\n    const boundaryElement = <HTMLElement>e.target;\n    const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2];\n\n    // Don't scroll if the buffer top has reached the end in that direction\n    const posInSet = boundaryElement.getAttribute('aria-posinset');\n    const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`;\n    if (posInSet === lastRowPos) {\n      return;\n    }\n\n    // Don't scroll when the last focused item was not the second row (focus is going the other\n    // direction)\n    if (e.relatedTarget !== beforeBoundaryElement) {\n      return;\n    }\n\n    // Remove old boundary element from array\n    let topBoundaryElement: HTMLElement;\n    let bottomBoundaryElement: HTMLElement;\n    if (position === BoundaryPosition.TOP) {\n      topBoundaryElement = boundaryElement;\n      bottomBoundaryElement = this._rowElements.pop()!;\n      this._rowContainer.removeChild(bottomBoundaryElement);\n    } else {\n      topBoundaryElement = this._rowElements.shift()!;\n      bottomBoundaryElement = boundaryElement;\n      this._rowContainer.removeChild(topBoundaryElement);\n    }\n\n    // Remove listeners from old boundary elements\n    topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);\n    bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n    // Add new element to array/DOM\n    if (position === BoundaryPosition.TOP) {\n      const newElement = this._createAccessibilityTreeNode();\n      this._rowElements.unshift(newElement);\n      this._rowContainer.insertAdjacentElement('afterbegin', newElement);\n    } else {\n      const newElement = this._createAccessibilityTreeNode();\n      this._rowElements.push(newElement);\n      this._rowContainer.appendChild(newElement);\n    }\n\n    // Add listeners to new boundary elements\n    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);\n    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n    // Scroll up\n    this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1);\n\n    // Focus new boundary before element\n    this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus();\n\n    // Prevent the standard behavior\n    e.preventDefault();\n    e.stopImmediatePropagation();\n  }\n\n  private _onResize(rows: number): void {\n    // Remove bottom boundary listener\n    this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);\n\n    // Grow rows as required\n    for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) {\n      this._rowElements[i] = this._createAccessibilityTreeNode();\n      this._rowContainer.appendChild(this._rowElements[i]);\n    }\n    // Shrink rows as required\n    while (this._rowElements.length > rows) {\n      this._rowContainer.removeChild(this._rowElements.pop()!);\n    }\n\n    // Add bottom boundary listener\n    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);\n\n    this._refreshRowsDimensions();\n  }\n\n  private _createAccessibilityTreeNode(): HTMLElement {\n    const element = document.createElement('div');\n    element.setAttribute('role', 'listitem');\n    element.tabIndex = -1;\n    this._refreshRowDimensions(element);\n    return element;\n  }\n\n  private _onTab(spaceCount: number): void {\n    for (let i = 0; i < spaceCount; i++) {\n      this._onChar(' ');\n    }\n  }\n\n  private _onChar(char: string): void {\n    if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {\n      if (this._charsToConsume.length > 0) {\n        // Have the screen reader ignore the char if it was just input\n        const shiftedChar = this._charsToConsume.shift();\n        if (shiftedChar !== char) {\n          this._charsToAnnounce += char;\n        }\n      } else {\n        this._charsToAnnounce += char;\n      }\n\n      if (char === '\\n') {\n        this._liveRegionLineCount++;\n        if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {\n          this._liveRegion.textContent += Strings.tooMuchOutput;\n        }\n      }\n\n      // Only detach/attach on mac as otherwise messages can go unaccounced\n      if (isMac) {\n        if (this._liveRegion.textContent && this._liveRegion.textContent.length > 0 && !this._liveRegion.parentNode) {\n          setTimeout(() => {\n            this._accessibilityTreeRoot.appendChild(this._liveRegion);\n          }, 0);\n        }\n      }\n    }\n  }\n\n  private _clearLiveRegion(): void {\n    this._liveRegion.textContent = '';\n    this._liveRegionLineCount = 0;\n\n    // Only detach/attach on mac as otherwise messages can go unaccounced\n    if (isMac) {\n      if (this._liveRegion.parentNode) {\n        this._accessibilityTreeRoot.removeChild(this._liveRegion);\n      }\n    }\n  }\n\n  private _onKey(keyChar: string): void {\n    this._clearLiveRegion();\n    this._charsToConsume.push(keyChar);\n  }\n\n  private _refreshRows(start?: number, end?: number): void {\n    this._renderRowsDebouncer.refresh(start, end, this._terminal.rows);\n  }\n\n  private _renderRows(start: number, end: number): void {\n    const buffer: IBuffer = this._terminal.buffer;\n    const setSize = buffer.lines.length.toString();\n    for (let i = start; i <= end; i++) {\n      const lineData = buffer.translateBufferLineToString(buffer.ydisp + i, true);\n      const posInSet = (buffer.ydisp + i + 1).toString();\n      const element = this._rowElements[i];\n      if (element) {\n        if (lineData.length === 0) {\n          element.innerHTML = '&nbsp;';\n        } else {\n          element.textContent = lineData;\n        }\n        element.setAttribute('aria-posinset', posInSet);\n        element.setAttribute('aria-setsize', setSize);\n      }\n    }\n    this._announceCharacters();\n  }\n\n  private _refreshRowsDimensions(): void {\n    if (!this._renderService.dimensions.actualCellHeight) {\n      return;\n    }\n    if (this._rowElements.length !== this._terminal.rows) {\n      this._onResize(this._terminal.rows);\n    }\n    for (let i = 0; i < this._terminal.rows; i++) {\n      this._refreshRowDimensions(this._rowElements[i]);\n    }\n  }\n\n  private _refreshRowDimensions(element: HTMLElement): void {\n    element.style.height = `${this._renderService.dimensions.actualCellHeight}px`;\n  }\n\n  private _announceCharacters(): void {\n    if (this._charsToAnnounce.length === 0) {\n      return;\n    }\n    this._liveRegion.textContent += this._charsToAnnounce;\n    this._charsToAnnounce = '';\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { ITerminal } from '../../Types';\nimport { BOLD_CLASS, ITALIC_CLASS, CURSOR_CLASS, CURSOR_STYLE_BLOCK_CLASS, CURSOR_BLINK_CLASS, CURSOR_STYLE_BAR_CLASS, CURSOR_STYLE_UNDERLINE_CLASS, DomRendererRowFactory } from 'browser/renderer/dom/DomRendererRowFactory';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { Disposable } from 'common/Lifecycle';\nimport { IColorSet, ILinkifierEvent } from 'browser/Types';\nimport { ICharSizeService } from 'browser/services/Services';\nimport { IOptionsService } from 'common/services/Services';\n\nconst TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';\nconst ROW_CONTAINER_CLASS = 'xterm-rows';\nconst FG_CLASS_PREFIX = 'xterm-fg-';\nconst BG_CLASS_PREFIX = 'xterm-bg-';\nconst FOCUS_CLASS = 'xterm-focus';\nconst SELECTION_CLASS = 'xterm-selection';\n\nlet nextTerminalId = 1;\n\n/**\n * A fallback renderer for when canvas is slow. This is not meant to be\n * particularly fast or feature complete, more just stable and usable for when\n * canvas is not an option.\n */\nexport class DomRenderer extends Disposable implements IRenderer {\n  private _rowFactory: DomRendererRowFactory;\n  private _terminalClass: number = nextTerminalId++;\n\n  private _themeStyleElement: HTMLStyleElement;\n  private _dimensionsStyleElement: HTMLStyleElement;\n  private _rowContainer: HTMLElement;\n  private _rowElements: HTMLElement[] = [];\n  private _selectionContainer: HTMLElement;\n\n  public dimensions: IRenderDimensions;\n\n  constructor(\n    private _terminal: ITerminal,\n    private _colors: IColorSet,\n    private _charSizeService: ICharSizeService,\n    private _optionsService: IOptionsService\n  ) {\n    super();\n\n    this._rowContainer = document.createElement('div');\n    this._rowContainer.classList.add(ROW_CONTAINER_CLASS);\n    this._rowContainer.style.lineHeight = 'normal';\n    this._rowContainer.setAttribute('aria-hidden', 'true');\n    this._refreshRowElements(this._terminal.cols, this._terminal.rows);\n    this._selectionContainer = document.createElement('div');\n    this._selectionContainer.classList.add(SELECTION_CLASS);\n    this._selectionContainer.setAttribute('aria-hidden', 'true');\n\n    this.dimensions = {\n      scaledCharWidth: null,\n      scaledCharHeight: null,\n      scaledCellWidth: null,\n      scaledCellHeight: null,\n      scaledCharLeft: null,\n      scaledCharTop: null,\n      scaledCanvasWidth: null,\n      scaledCanvasHeight: null,\n      canvasWidth: null,\n      canvasHeight: null,\n      actualCellWidth: null,\n      actualCellHeight: null\n    };\n    this._updateDimensions();\n    this._injectCss();\n\n    this._rowFactory = new DomRendererRowFactory(document, this._optionsService);\n\n    this._terminal.element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass);\n    this._terminal.screenElement.appendChild(this._rowContainer);\n    this._terminal.screenElement.appendChild(this._selectionContainer);\n\n    this._terminal.linkifier.onLinkHover(e => this._onLinkHover(e));\n    this._terminal.linkifier.onLinkLeave(e => this._onLinkLeave(e));\n  }\n\n  public dispose(): void {\n    this._terminal.element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);\n    this._terminal.screenElement.removeChild(this._rowContainer);\n    this._terminal.screenElement.removeChild(this._selectionContainer);\n    this._terminal.screenElement.removeChild(this._themeStyleElement);\n    this._terminal.screenElement.removeChild(this._dimensionsStyleElement);\n    super.dispose();\n  }\n\n  private _updateDimensions(): void {\n    this.dimensions.scaledCharWidth = this._charSizeService.width * window.devicePixelRatio;\n    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);\n    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);\n    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);\n    this.dimensions.scaledCharLeft = 0;\n    this.dimensions.scaledCharTop = 0;\n    this.dimensions.scaledCanvasWidth = this.dimensions.scaledCellWidth * this._terminal.cols;\n    this.dimensions.scaledCanvasHeight = this.dimensions.scaledCellHeight * this._terminal.rows;\n    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);\n    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);\n    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;\n    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;\n\n    this._rowElements.forEach(element => {\n      element.style.width = `${this.dimensions.canvasWidth}px`;\n      element.style.height = `${this.dimensions.actualCellHeight}px`;\n      element.style.lineHeight = `${this.dimensions.actualCellHeight}px`;\n      // Make sure rows don't overflow onto following row\n      element.style.overflow = 'hidden';\n    });\n\n    if (!this._dimensionsStyleElement) {\n      this._dimensionsStyleElement = document.createElement('style');\n      this._terminal.screenElement.appendChild(this._dimensionsStyleElement);\n    }\n\n    const styles =\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` +\n        ` display: inline-block;` +\n        ` height: 100%;` +\n        ` vertical-align: top;` +\n        ` width: ${this.dimensions.actualCellWidth}px` +\n        `}`;\n\n    this._dimensionsStyleElement.innerHTML = styles;\n\n    this._selectionContainer.style.height = (<any>this._terminal)._viewportElement.style.height;\n    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;\n    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;\n  }\n\n  public setColors(colors: IColorSet): void {\n    this._colors = colors;\n    this._injectCss();\n  }\n\n  private _injectCss(): void {\n    if (!this._themeStyleElement) {\n      this._themeStyleElement = document.createElement('style');\n      this._terminal.screenElement.appendChild(this._themeStyleElement);\n    }\n\n    // Base CSS\n    let styles =\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` +\n        ` color: ${this._colors.foreground.css};` +\n        ` background-color: ${this._colors.background.css};` +\n        ` font-family: ${this._terminal.options.fontFamily};` +\n        ` font-size: ${this._terminal.options.fontSize}px;` +\n        `}`;\n    // Text styles\n    styles +=\n        `${this._terminalSelector} span:not(.${BOLD_CLASS}) {` +\n        ` font-weight: ${this._terminal.options.fontWeight};` +\n        `}` +\n        `${this._terminalSelector} span.${BOLD_CLASS} {` +\n        ` font-weight: ${this._terminal.options.fontWeightBold};` +\n        `}` +\n        `${this._terminalSelector} span.${ITALIC_CLASS} {` +\n        ` font-style: italic;` +\n        `}`;\n    // Blink animation\n    styles +=\n        `@keyframes blink_box_shadow {` +\n        ` 50% {` +\n        `  box-shadow: none;` +\n        ` }` +\n        `}`;\n    styles +=\n        `@keyframes blink_block {` +\n        ` 0% {` +\n        `  background-color: ${this._colors.cursor.css};` +\n        `  color: ${this._colors.cursorAccent.css};` +\n        ` }` +\n        ` 50% {` +\n        `  background-color: ${this._colors.cursorAccent.css};` +\n        `  color: ${this._colors.cursor.css};` +\n        ` }` +\n        `}`;\n    // Cursor\n    styles +=\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}:not(.${FOCUS_CLASS}) .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +\n        ` outline: 1px solid ${this._colors.cursor.css};` +\n        ` outline-offset: -1px;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}:not(.${CURSOR_STYLE_BLOCK_CLASS}) {` +\n        ` animation: blink_box_shadow 1s step-end infinite;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +\n        ` animation: blink_block 1s step-end infinite;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +\n        ` background-color: ${this._colors.cursor.css};` +\n        ` color: ${this._colors.cursorAccent.css};` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BAR_CLASS} {` +\n        ` box-shadow: 1px 0 0 ${this._colors.cursor.css} inset;` +\n        `}` +\n        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_UNDERLINE_CLASS} {` +\n        ` box-shadow: 0 -1px 0 ${this._colors.cursor.css} inset;` +\n        `}`;\n    // Selection\n    styles +=\n        `${this._terminalSelector} .${SELECTION_CLASS} {` +\n        ` position: absolute;` +\n        ` top: 0;` +\n        ` left: 0;` +\n        ` z-index: 1;` +\n        ` pointer-events: none;` +\n        `}` +\n        `${this._terminalSelector} .${SELECTION_CLASS} div {` +\n        ` position: absolute;` +\n        ` background-color: ${this._colors.selection.css};` +\n        `}`;\n    // Colors\n    this._colors.ansi.forEach((c, i) => {\n      styles +=\n          `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` +\n          `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`;\n    });\n    styles +=\n        `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${this._colors.background.css}; }` +\n        `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${this._colors.foreground.css}; }`;\n\n    this._themeStyleElement.innerHTML = styles;\n  }\n\n  public onDevicePixelRatioChange(): void {\n    this._updateDimensions();\n  }\n\n  private _refreshRowElements(cols: number, rows: number): void {\n    // Add missing elements\n    for (let i = this._rowElements.length; i <= rows; i++) {\n      const row = document.createElement('div');\n      this._rowContainer.appendChild(row);\n      this._rowElements.push(row);\n    }\n    // Remove excess elements\n    while (this._rowElements.length > rows) {\n      this._rowContainer.removeChild(this._rowElements.pop());\n    }\n  }\n\n  public onResize(cols: number, rows: number): void {\n    this._refreshRowElements(cols, rows);\n    this._updateDimensions();\n  }\n\n  public onCharSizeChanged(): void {\n    this._updateDimensions();\n  }\n\n  public onBlur(): void {\n    this._rowContainer.classList.remove(FOCUS_CLASS);\n  }\n\n  public onFocus(): void {\n    this._rowContainer.classList.add(FOCUS_CLASS);\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {\n    // Remove all selections\n    while (this._selectionContainer.children.length) {\n      this._selectionContainer.removeChild(this._selectionContainer.children[0]);\n    }\n\n    // Selection does not exist\n    if (!start || !end) {\n      return;\n    }\n\n    // Translate from buffer position to viewport position\n    const viewportStartRow = start[1] - this._terminal.buffer.ydisp;\n    const viewportEndRow = end[1] - this._terminal.buffer.ydisp;\n    const viewportCappedStartRow = Math.max(viewportStartRow, 0);\n    const viewportCappedEndRow = Math.min(viewportEndRow, this._terminal.rows - 1);\n\n    // No need to draw the selection\n    if (viewportCappedStartRow >= this._terminal.rows || viewportCappedEndRow < 0) {\n      return;\n    }\n\n    // Create the selections\n    const documentFragment = document.createDocumentFragment();\n\n    if (columnSelectMode) {\n      documentFragment.appendChild(\n        this._createSelectionElement(viewportCappedStartRow, start[0], end[0], viewportCappedEndRow - viewportCappedStartRow + 1)\n      );\n    } else {\n      // Draw first row\n      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;\n      const endCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._terminal.cols;\n      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol));\n      // Draw middle rows\n      const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1;\n      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._terminal.cols, middleRowsCount));\n      // Draw final row\n      if (viewportCappedStartRow !== viewportCappedEndRow) {\n        // Only draw viewportEndRow if it's not the same as viewporttartRow\n        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._terminal.cols;\n        documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol));\n      }\n    }\n    this._selectionContainer.appendChild(documentFragment);\n  }\n\n  /**\n   * Creates a selection element at the specified position.\n   * @param row The row of the selection.\n   * @param colStart The start column.\n   * @param colEnd The end columns.\n   */\n  private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement {\n    const element = document.createElement('div');\n    element.style.height = `${rowCount * this.dimensions.actualCellHeight}px`;\n    element.style.top = `${row * this.dimensions.actualCellHeight}px`;\n    element.style.left = `${colStart * this.dimensions.actualCellWidth}px`;\n    element.style.width = `${this.dimensions.actualCellWidth * (colEnd - colStart)}px`;\n    return element;\n  }\n\n  public onCursorMove(): void {\n    // No-op, the cursor is drawn when rows are drawn\n  }\n\n  public onOptionsChanged(): void {\n    // Force a refresh\n    this._updateDimensions();\n    this._injectCss();\n    this._terminal.refresh(0, this._terminal.rows - 1);\n  }\n\n  public clear(): void {\n    this._rowElements.forEach(e => e.innerHTML = '');\n  }\n\n  public renderRows(start: number, end: number): void {\n    const terminal = this._terminal;\n\n    const cursorAbsoluteY = terminal.buffer.ybase + terminal.buffer.y;\n    const cursorX = this._terminal.buffer.x;\n    const cursorBlink = this._terminal.options.cursorBlink;\n\n    for (let y = start; y <= end; y++) {\n      const rowElement = this._rowElements[y];\n      rowElement.innerHTML = '';\n\n      const row = y + terminal.buffer.ydisp;\n      const lineData = terminal.buffer.lines.get(row);\n      const cursorStyle = terminal.options.cursorStyle;\n      rowElement.appendChild(this._rowFactory.createRow(lineData, row === cursorAbsoluteY, cursorStyle, cursorX, cursorBlink, this.dimensions.actualCellWidth, terminal.cols));\n    }\n  }\n\n  private get _terminalSelector(): string {\n    return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`;\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number { return -1; }\n  public deregisterCharacterJoiner(joinerId: number): boolean { return false; }\n\n  private _onLinkHover(e: ILinkifierEvent): void {\n    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true);\n  }\n\n  private _onLinkLeave(e: ILinkifierEvent): void {\n    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false);\n  }\n\n  private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void {\n    while (x !== x2 || y !== y2) {\n      const row = this._rowElements[y];\n      if (!row) {\n        return;\n      }\n      const span = <HTMLElement>row.children[x];\n      if (span) {\n        span.style.textDecoration = enabled ? 'underline' : 'none';\n      }\n      if (++x >= cols) {\n        x = 0;\n        y++;\n      }\n    }\n  }\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferLine } from 'common/Types';\nimport { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';\nimport { AttributeData } from 'common/buffer/AttributeData';\nimport { NULL_CELL_CODE, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';\nimport { CellData } from 'common/buffer/CellData';\nimport { IOptionsService } from 'common/services/Services';\n\nexport const BOLD_CLASS = 'xterm-bold';\nexport const DIM_CLASS = 'xterm-dim';\nexport const ITALIC_CLASS = 'xterm-italic';\nexport const UNDERLINE_CLASS = 'xterm-underline';\nexport const CURSOR_CLASS = 'xterm-cursor';\nexport const CURSOR_BLINK_CLASS = 'xterm-cursor-blink';\nexport const CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block';\nexport const CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar';\nexport const CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline';\n\nexport class DomRendererRowFactory {\n  private _workCell: CellData = new CellData();\n\n  constructor(\n    private _document: Document,\n    private _optionsService: IOptionsService\n  ) {\n  }\n\n  public createRow(lineData: IBufferLine, isCursorRow: boolean, cursorStyle: string | undefined, cursorX: number, cursorBlink: boolean, cellWidth: number, cols: number): DocumentFragment {\n    const fragment = this._document.createDocumentFragment();\n\n    // Find the line length first, this prevents the need to output a bunch of\n    // empty cells at the end. This cannot easily be integrated into the main\n    // loop below because of the colCount feature (which can be removed after we\n    // properly support reflow and disallow data to go beyond the right-side of\n    // the viewport).\n    let lineLength = 0;\n    for (let x = Math.min(lineData.length, cols) - 1; x >= 0; x--) {\n      if (lineData.loadCell(x, this._workCell).getCode() !== NULL_CELL_CODE || (isCursorRow && x === cursorX)) {\n        lineLength = x + 1;\n        break;\n      }\n    }\n\n    for (let x = 0; x < lineLength; x++) {\n      lineData.loadCell(x, this._workCell);\n      const width = this._workCell.getWidth();\n\n      // The character to the left is a wide character, drawing is owned by the char at x-1\n      if (width === 0) {\n        continue;\n      }\n\n      const charElement = this._document.createElement('span');\n      if (width > 1) {\n        charElement.style.width = `${cellWidth * width}px`;\n      }\n\n      if (isCursorRow && x === cursorX) {\n        charElement.classList.add(CURSOR_CLASS);\n\n        if (cursorBlink) {\n          charElement.classList.add(CURSOR_BLINK_CLASS);\n        }\n\n        switch (cursorStyle) {\n          case 'bar':\n            charElement.classList.add(CURSOR_STYLE_BAR_CLASS);\n            break;\n          case 'underline':\n            charElement.classList.add(CURSOR_STYLE_UNDERLINE_CLASS);\n            break;\n          default:\n            charElement.classList.add(CURSOR_STYLE_BLOCK_CLASS);\n            break;\n        }\n      }\n\n      if (this._workCell.isBold()) {\n        charElement.classList.add(BOLD_CLASS);\n      }\n\n      if (this._workCell.isItalic()) {\n        charElement.classList.add(ITALIC_CLASS);\n      }\n\n      if (this._workCell.isDim()) {\n        charElement.classList.add(DIM_CLASS);\n      }\n\n      if (this._workCell.isUnderline()) {\n        charElement.classList.add(UNDERLINE_CLASS);\n      }\n\n      charElement.textContent = this._workCell.getChars() || WHITESPACE_CELL_CHAR;\n\n      const swapColor = this._workCell.isInverse();\n\n      // fg\n      if (this._workCell.isFgRGB()) {\n        let style = charElement.getAttribute('style') || '';\n        style += `${swapColor ? 'background-' : ''}color:rgb(${(AttributeData.toColorRGB(this._workCell.getFgColor())).join(',')});`;\n        charElement.setAttribute('style', style);\n      } else if (this._workCell.isFgPalette()) {\n        let fg = this._workCell.getFgColor();\n        if (this._workCell.isBold() && fg < 8 && !swapColor && this._optionsService.options.drawBoldTextInBrightColors) {\n          fg += 8;\n        }\n        charElement.classList.add(`xterm-${swapColor ? 'b' : 'f'}g-${fg}`);\n      } else if (swapColor) {\n        charElement.classList.add(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);\n      }\n\n      // bg\n      if (this._workCell.isBgRGB()) {\n        let style = charElement.getAttribute('style') || '';\n        style += `${swapColor ? '' : 'background-'}color:rgb(${(AttributeData.toColorRGB(this._workCell.getBgColor())).join(',')});`;\n        charElement.setAttribute('style', style);\n      } else if (this._workCell.isBgPalette()) {\n        charElement.classList.add(`xterm-${swapColor ? 'f' : 'b'}g-${this._workCell.getBgColor()}`);\n      } else if (swapColor) {\n        charElement.classList.add(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);\n      }\n\n      fragment.appendChild(charElement);\n    }\n    return fragment;\n  }\n}\n","/**\n * Copyright (c) 2014 The xterm.js authors. All rights reserved.\n * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)\n * @license MIT\n */\n\nimport { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';\nimport { C0 } from 'common/data/EscapeSequences';\n\n// reg + shift key mappings for digits and special chars\nconst KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {\n  // digits 0-9\n  48: ['0', ')'],\n  49: ['1', '!'],\n  50: ['2', '@'],\n  51: ['3', '#'],\n  52: ['4', '$'],\n  53: ['5', '%'],\n  54: ['6', '^'],\n  55: ['7', '&'],\n  56: ['8', '*'],\n  57: ['9', '('],\n\n  // special chars\n  186: [';', ':'],\n  187: ['=', '+'],\n  188: [',', '<'],\n  189: ['-', '_'],\n  190: ['.', '>'],\n  191: ['/', '?'],\n  192: ['`', '~'],\n  219: ['[', '{'],\n  220: ['\\\\', '|'],\n  221: [']', '}'],\n  222: ['\\'', '\"']\n};\n\nexport function evaluateKeyboardEvent(\n  ev: IKeyboardEvent,\n  applicationCursorMode: boolean,\n  isMac: boolean,\n  macOptionIsMeta: boolean\n): IKeyboardResult {\n  const result: IKeyboardResult = {\n    type: KeyboardResultType.SEND_KEY,\n    // Whether to cancel event propagation (NOTE: this may not be needed since the event is\n    // canceled at the end of keyDown\n    cancel: false,\n    // The new key even to emit\n    key: undefined\n  };\n  const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);\n  switch (ev.keyCode) {\n    case 0:\n      if (ev.key === 'UIKeyInputUpArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OA';\n        } else {\n          result.key = C0.ESC + '[A';\n        }\n      }\n      else if (ev.key === 'UIKeyInputLeftArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OD';\n        } else {\n          result.key = C0.ESC + '[D';\n        }\n      }\n      else if (ev.key === 'UIKeyInputRightArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OC';\n        } else {\n          result.key = C0.ESC + '[C';\n        }\n      }\n      else if (ev.key === 'UIKeyInputDownArrow') {\n        if (applicationCursorMode) {\n          result.key = C0.ESC + 'OB';\n        } else {\n          result.key = C0.ESC + '[B';\n        }\n      }\n      break;\n    case 8:\n      // backspace\n      if (ev.shiftKey) {\n        result.key = C0.BS; // ^H\n        break;\n      } else if (ev.altKey) {\n        result.key = C0.ESC + C0.DEL; // \\e ^?\n        break;\n      }\n      result.key = C0.DEL; // ^?\n      break;\n    case 9:\n      // tab\n      if (ev.shiftKey) {\n        result.key = C0.ESC + '[Z';\n        break;\n      }\n      result.key = C0.HT;\n      result.cancel = true;\n      break;\n    case 13:\n      // return/enter\n      result.key = C0.CR;\n      result.cancel = true;\n      break;\n    case 27:\n      // escape\n      result.key = C0.ESC;\n      result.cancel = true;\n      break;\n    case 37:\n      // left-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';\n        // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (result.key === C0.ESC + '[1;3D') {\n          result.key = C0.ESC + (isMac ? 'b' : '[1;5D');\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OD';\n      } else {\n        result.key = C0.ESC + '[D';\n      }\n      break;\n    case 39:\n      // right-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';\n        // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (result.key === C0.ESC + '[1;3C') {\n          result.key = C0.ESC + (isMac ? 'f' : '[1;5C');\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OC';\n      } else {\n        result.key = C0.ESC + '[C';\n      }\n      break;\n    case 38:\n      // up-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';\n        // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (!isMac && result.key === C0.ESC + '[1;3A') {\n          result.key = C0.ESC + '[1;5A';\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OA';\n      } else {\n        result.key = C0.ESC + '[A';\n      }\n      break;\n    case 40:\n      // down-arrow\n      if (ev.metaKey) {\n        break;\n      }\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';\n        // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow\n        // http://unix.stackexchange.com/a/108106\n        // macOS uses different escape sequences than linux\n        if (!isMac && result.key === C0.ESC + '[1;3B') {\n          result.key = C0.ESC + '[1;5B';\n        }\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OB';\n      } else {\n        result.key = C0.ESC + '[B';\n      }\n      break;\n    case 45:\n      // insert\n      if (!ev.shiftKey && !ev.ctrlKey) {\n        // <Ctrl> or <Shift> + <Insert> are used to\n        // copy-paste on some systems.\n        result.key = C0.ESC + '[2~';\n      }\n      break;\n    case 46:\n      // delete\n      if (modifiers) {\n        result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[3~';\n      }\n      break;\n    case 36:\n      // home\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OH';\n      } else {\n        result.key = C0.ESC + '[H';\n      }\n      break;\n    case 35:\n      // end\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';\n      } else if (applicationCursorMode) {\n        result.key = C0.ESC + 'OF';\n      } else {\n        result.key = C0.ESC + '[F';\n      }\n      break;\n    case 33:\n      // page up\n      if (ev.shiftKey) {\n        result.type = KeyboardResultType.PAGE_UP;\n      } else {\n        result.key = C0.ESC + '[5~';\n      }\n      break;\n    case 34:\n      // page down\n      if (ev.shiftKey) {\n        result.type = KeyboardResultType.PAGE_DOWN;\n      } else {\n        result.key = C0.ESC + '[6~';\n      }\n      break;\n    case 112:\n      // F1-F12\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';\n      } else {\n        result.key = C0.ESC + 'OP';\n      }\n      break;\n    case 113:\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';\n      } else {\n        result.key = C0.ESC + 'OQ';\n      }\n      break;\n    case 114:\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';\n      } else {\n        result.key = C0.ESC + 'OR';\n      }\n      break;\n    case 115:\n      if (modifiers) {\n        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';\n      } else {\n        result.key = C0.ESC + 'OS';\n      }\n      break;\n    case 116:\n      if (modifiers) {\n        result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[15~';\n      }\n      break;\n    case 117:\n      if (modifiers) {\n        result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[17~';\n      }\n      break;\n    case 118:\n      if (modifiers) {\n        result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[18~';\n      }\n      break;\n    case 119:\n      if (modifiers) {\n        result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[19~';\n      }\n      break;\n    case 120:\n      if (modifiers) {\n        result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[20~';\n      }\n      break;\n    case 121:\n      if (modifiers) {\n        result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[21~';\n      }\n      break;\n    case 122:\n      if (modifiers) {\n        result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[23~';\n      }\n      break;\n    case 123:\n      if (modifiers) {\n        result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';\n      } else {\n        result.key = C0.ESC + '[24~';\n      }\n      break;\n    default:\n      // a-z and space\n      if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {\n        if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n          result.key = String.fromCharCode(ev.keyCode - 64);\n        } else if (ev.keyCode === 32) {\n          result.key = C0.NUL;\n        } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {\n          // escape, file sep, group sep, record sep, unit sep\n          result.key = String.fromCharCode(ev.keyCode - 51 + 27);\n        } else if (ev.keyCode === 56) {\n          result.key = C0.DEL;\n        } else if (ev.keyCode === 219) {\n          result.key = C0.ESC;\n        } else if (ev.keyCode === 220) {\n          result.key = C0.FS;\n        } else if (ev.keyCode === 221) {\n          result.key = C0.GS;\n        }\n      } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {\n        // On macOS this is a third level shift when !macOptionIsMeta. Use <Esc> instead.\n        const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];\n        const key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1];\n        if (key) {\n          result.key = C0.ESC + key;\n        } else if (ev.keyCode >= 65 && ev.keyCode <= 90) {\n          const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;\n          result.key = C0.ESC + String.fromCharCode(keyCode);\n        }\n      } else if (isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {\n        if (ev.keyCode === 65) { // cmd + a\n          result.type = KeyboardResultType.SELECT_ALL;\n        }\n      } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {\n        // Include only keys that that result in a _single_ character; don't include num lock, volume up, etc.\n        result.key = ev.key;\n      } else if (ev.key && ev.ctrlKey) {\n        if (ev.key === '_') { // ^_\n          result.key = C0.US;\n        }\n      }\n      break;\n  }\n\n  return result;\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from 'xterm';\nimport { ITerminal } from './Types';\nimport { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';\n\nexport function applyWindowsMode(terminal: ITerminal): IDisposable {\n  // Winpty does not support wraparound mode which means that lines will never\n  // be marked as wrapped. This causes issues for things like copying a line\n  // retaining the wrapped new line characters or if consumers are listening\n  // in on the data stream.\n  //\n  // The workaround for this is to listen to every incoming line feed and mark\n  // the line as wrapped if the last character in the previous line is not a\n  // space. This is certainly not without its problems, but generally on\n  // Windows when text reaches the end of the terminal it's likely going to be\n  // wrapped.\n  return terminal.onLineFeed(() => {\n    const line = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y - 1);\n    const lastChar = line.get(terminal.cols - 1);\n\n    const nextLine = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y);\n    nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE);\n  });\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';\nimport { RenderDebouncer } from 'browser/RenderDebouncer';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { Disposable } from 'common/Lifecycle';\nimport { ScreenDprMonitor } from 'browser/ScreenDprMonitor';\nimport { addDisposableDomListener } from 'browser/Lifecycle';\nimport { IColorSet } from 'browser/Types';\nimport { IOptionsService } from 'common/services/Services';\nimport { ICharSizeService, IRenderService } from 'browser/services/Services';\n\nexport class RenderService extends Disposable implements IRenderService {\n  serviceBrand: any;\n\n  private _renderDebouncer: RenderDebouncer;\n  private _screenDprMonitor: ScreenDprMonitor;\n\n  private _isPaused: boolean = false;\n  private _needsFullRefresh: boolean = false;\n  private _canvasWidth: number = 0;\n  private _canvasHeight: number = 0;\n\n  private _onDimensionsChange = new EventEmitter<IRenderDimensions>();\n  public get onDimensionsChange(): IEvent<IRenderDimensions> { return this._onDimensionsChange.event; }\n  private _onRender = new EventEmitter<{ start: number, end: number }>();\n  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }\n  private _onRefreshRequest = new EventEmitter<{ start: number, end: number }>();\n  public get onRefreshRequest(): IEvent<{ start: number, end: number }> { return this._onRefreshRequest.event; }\n\n  public get dimensions(): IRenderDimensions { return this._renderer.dimensions; }\n\n  constructor(\n    private _renderer: IRenderer,\n    private _rowCount: number,\n    readonly screenElement: HTMLElement,\n    @IOptionsService readonly optionsService: IOptionsService,\n    @ICharSizeService readonly charSizeService: ICharSizeService\n  ) {\n    super();\n    this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end));\n    this.register(this._renderDebouncer);\n\n    this._screenDprMonitor = new ScreenDprMonitor();\n    this._screenDprMonitor.setListener(() => this.onDevicePixelRatioChange());\n    this.register(this._screenDprMonitor);\n\n    this.register(optionsService.onOptionChange(() => this._renderer.onOptionsChanged()));\n    this.register(charSizeService.onCharSizeChange(() => this.onCharSizeChanged()));\n\n    // dprchange should handle this case, we need this as well for browsers that don't support the\n    // matchMedia query.\n    this.register(addDisposableDomListener(window, 'resize', () => this.onDevicePixelRatioChange()));\n\n    // Detect whether IntersectionObserver is detected and enable renderer pause\n    // and resume based on terminal visibility if so\n    if ('IntersectionObserver' in window) {\n      const observer = new IntersectionObserver(e => this._onIntersectionChange(e[e.length - 1]), { threshold: 0 });\n      observer.observe(screenElement);\n      this.register({ dispose: () => observer.disconnect() });\n    }\n  }\n\n  private _onIntersectionChange(entry: IntersectionObserverEntry): void {\n    this._isPaused = entry.intersectionRatio === 0;\n    if (!this._isPaused && this._needsFullRefresh) {\n      this.refreshRows(0, this._rowCount - 1);\n      this._needsFullRefresh = false;\n    }\n  }\n\n  public refreshRows(start: number, end: number): void {\n    if (this._isPaused) {\n      this._needsFullRefresh = true;\n      return;\n    }\n    this._renderDebouncer.refresh(start, end, this._rowCount);\n  }\n\n  private _renderRows(start: number, end: number): void {\n    this._renderer.renderRows(start, end);\n    this._onRender.fire({ start, end });\n  }\n\n  public resize(cols: number, rows: number): void {\n    this._rowCount = rows;\n    this._fireOnCanvasResize();\n  }\n\n  public changeOptions(): void {\n    this._renderer.onOptionsChanged();\n    this._fireOnCanvasResize();\n  }\n\n  private _fireOnCanvasResize(): void {\n    // Don't fire the event if the dimensions haven't changed\n    if (this._renderer.dimensions.canvasWidth === this._canvasWidth && this._renderer.dimensions.canvasHeight === this._canvasHeight) {\n      return;\n    }\n    this._onDimensionsChange.fire(this._renderer.dimensions);\n  }\n\n  public dispose(): void {\n    this._renderer.dispose();\n  }\n\n  public setRenderer(renderer: IRenderer): void {\n    // TODO: RenderService should be the only one to dispose the renderer\n    this._renderer.dispose();\n    this._renderer = renderer;\n    this.refreshRows(0, this._rowCount - 1);\n  }\n\n  private _fullRefresh(): void {\n    if (this._isPaused) {\n      this._needsFullRefresh = true;\n    } else {\n      this.refreshRows(0, this._rowCount - 1);\n    }\n  }\n\n  public setColors(colors: IColorSet): void {\n    this._renderer.setColors(colors);\n    this._fullRefresh();\n  }\n\n  public onDevicePixelRatioChange(): void {\n    this._renderer.onDevicePixelRatioChange();\n    this.refreshRows(0, this._rowCount - 1);\n  }\n\n  public onResize(cols: number, rows: number): void {\n    this._renderer.onResize(cols, rows);\n    this._fullRefresh();\n  }\n\n  // TODO: Is this useful when we have onResize?\n  public onCharSizeChanged(): void {\n    this._renderer.onCharSizeChanged();\n  }\n\n  public onBlur(): void {\n    this._renderer.onBlur();\n  }\n\n  public onFocus(): void {\n    this._renderer.onFocus();\n  }\n\n  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {\n    this._renderer.onSelectionChanged(start, end, columnSelectMode);\n  }\n\n  public onCursorMove(): void {\n    this._renderer.onCursorMove();\n  }\n\n  public clear(): void {\n    this._renderer.clear();\n  }\n\n  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {\n    return this._renderer.registerCharacterJoiner(handler);\n  }\n\n  public deregisterCharacterJoiner(joinerId: number): boolean {\n    return this._renderer.deregisterCharacterJoiner(joinerId);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService, ITerminalOptions, IPartialTerminalOptions } from 'common/services/Services';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { isMac } from 'common/Platform';\nimport { clone } from 'common/Clone';\n\n// Source: https://freesound.org/people/altemark/sounds/45759/\n// This sound is released under the Creative Commons Attribution 3.0 Unported\n// (CC BY 3.0) license. It was created by 'altemark'. No modifications have been\n// made, apart from the conversion to base64.\nexport const DEFAULT_BELL_SOUND = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';\n\n// TODO: Freeze?\nexport const DEFAULT_OPTIONS: ITerminalOptions = Object.freeze({\n  cols: 80,\n  rows: 24,\n  cursorBlink: false,\n  cursorStyle: 'block',\n  bellSound:  DEFAULT_BELL_SOUND,\n  bellStyle: 'none',\n  drawBoldTextInBrightColors: true,\n  fastScrollModifier: 'alt',\n  fastScrollSensitivity: 5,\n  fontFamily: 'courier-new, courier, monospace',\n  fontSize: 15,\n  fontWeight: 'normal',\n  fontWeightBold: 'bold',\n  lineHeight: 1.0,\n  letterSpacing: 0,\n  logLevel: 'info',\n  scrollback: 1000,\n  scrollSensitivity: 1,\n  screenReaderMode: false,\n  macOptionIsMeta: false,\n  macOptionClickForcesSelection: false,\n  disableStdin: false,\n  allowTransparency: false,\n  tabStopWidth: 8,\n  theme: {},\n  rightClickSelectsWord: isMac,\n  rendererType: 'canvas',\n  windowsMode: false,\n\n  convertEol: false,\n  termName: 'xterm',\n  screenKeys: false,\n  cancelEvents: false,\n  useFlowControl: false,\n  wordSeparator: ' ()[]{}\\',:;\"'\n});\n\n/**\n * The set of options that only have an effect when set in the Terminal constructor.\n */\nconst CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows'];\n\nexport class OptionsService implements IOptionsService {\n  serviceBrand: any;\n\n  public options: ITerminalOptions;\n\n  private _onOptionChange = new EventEmitter<string>();\n  public get onOptionChange(): IEvent<string> { return this._onOptionChange.event; }\n\n  constructor(options: IPartialTerminalOptions) {\n    this.options = clone(DEFAULT_OPTIONS);\n    Object.keys(options).forEach(k => {\n      if (k in this.options) {\n        const newValue = options[k as keyof IPartialTerminalOptions] as any;\n        this.options[k] = newValue;\n      }\n    });\n  }\n\n  public setOption(key: string, value: any): void {\n    if (!(key in DEFAULT_OPTIONS)) {\n      throw new Error('No option with key \"' + key + '\"');\n    }\n    if (CONSTRUCTOR_ONLY_OPTIONS.indexOf(key) !== -1) {\n      throw new Error(`Option \"${key}\" can only be set in the constructor`);\n    }\n    if (this.options[key] === value) {\n      return;\n    }\n\n    value = this._sanitizeAndValidateOption(key, value);\n\n    // Don't fire an option change event if they didn't change\n    if (this.options[key] === value) {\n      return;\n    }\n\n    this.options[key] = value;\n    this._onOptionChange.fire(key);\n  }\n\n  private _sanitizeAndValidateOption(key: string, value: any): any {\n    switch (key) {\n      case 'bellStyle':\n      case 'cursorStyle':\n      case 'fontWeight':\n      case 'fontWeightBold':\n      case 'rendererType':\n      case 'wordSeparator':\n        if (!value) {\n          value = DEFAULT_OPTIONS[key];\n        }\n        break;\n      case 'lineHeight':\n      case 'tabStopWidth':\n        if (value < 1) {\n          throw new Error(`${key} cannot be less than 1, value: ${value}`);\n        }\n        break;\n      case 'scrollback':\n        value = Math.min(value, 4294967295);\n        if (value < 0) {\n          throw new Error(`${key} cannot be less than 0, value: ${value}`);\n        }\n        break;\n      case 'fastScrollSensitivity':\n      case 'scrollSensitivity':\n        if (value <= 0) {\n          throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);\n        }\n        break;\n    }\n    return value;\n  }\n\n  public getOption(key: string): any {\n    if (!(key in DEFAULT_OPTIONS)) {\n      throw new Error(`No option with key \"${key}\"`);\n    }\n    return this.options[key];\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IOptionsService } from 'common/services/Services';\nimport { IEvent, EventEmitter } from 'common/EventEmitter';\nimport { ICharSizeService } from 'browser/services/Services';\n\nexport class CharSizeService implements ICharSizeService {\n  serviceBrand: any;\n\n  public width: number = 0;\n  public height: number = 0;\n  private _measureStrategy: IMeasureStrategy;\n\n  public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }\n\n  private _onCharSizeChange = new EventEmitter<void>();\n  public get onCharSizeChange(): IEvent<void> { return this._onCharSizeChange.event; }\n\n  constructor(\n    readonly document: Document,\n    readonly parentElement: HTMLElement,\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    this._measureStrategy = new DomMeasureStrategy(document, parentElement, this._optionsService);\n  }\n\n  public measure(): void {\n    const result = this._measureStrategy.measure();\n    if (result.width !== this.width || result.height !== this.height) {\n      this.width = result.width;\n      this.height = result.height;\n      this._onCharSizeChange.fire();\n    }\n  }\n}\n\ninterface IMeasureStrategy {\n  measure(): IReadonlyMeasureResult;\n}\n\ninterface IReadonlyMeasureResult {\n  readonly width: number;\n  readonly height: number;\n}\n\ninterface IMeasureResult {\n  width: number;\n  height: number;\n}\n\n// TODO: For supporting browsers we should also provide a CanvasCharDimensionsProvider that uses ctx.measureText\nclass DomMeasureStrategy implements IMeasureStrategy {\n  private _result: IMeasureResult = { width: 0, height: 0 };\n  private _measureElement: HTMLElement;\n\n  constructor(\n    private _document: Document,\n    private _parentElement: HTMLElement,\n    private _optionsService: IOptionsService\n  ) {\n    this._measureElement = this._document.createElement('span');\n    this._measureElement.classList.add('xterm-char-measure-element');\n    this._measureElement.textContent = 'W';\n    this._measureElement.setAttribute('aria-hidden', 'true');\n    this._parentElement.appendChild(this._measureElement);\n  }\n\n  public measure(): IReadonlyMeasureResult {\n    this._measureElement.style.fontFamily = this._optionsService.options.fontFamily;\n    this._measureElement.style.fontSize = `${this._optionsService.options.fontSize}px`;\n\n    // Note that this triggers a synchronous layout\n    const geometry = this._measureElement.getBoundingClientRect();\n\n    // If values are 0 then the element is likely currently display:none, in which case we should\n    // retain the previous value.\n    if (geometry.width !== 0 && geometry.height !== 0) {\n      this._result.width = geometry.width;\n      this._result.height = Math.ceil(geometry.height);\n    }\n\n    return this._result;\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService, IOptionsService } from 'common/services/Services';\nimport { BufferSet } from 'common/buffer/BufferSet';\nimport { IBufferSet, IBuffer } from 'common/buffer/Types';\n\nexport const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars\nexport const MINIMUM_ROWS = 1;\n\nexport class BufferService implements IBufferService {\n  serviceBrand: any;\n\n  public cols: number;\n  public rows: number;\n  public buffers: IBufferSet;\n\n  public get buffer(): IBuffer { return this.buffers.active; }\n\n  constructor(\n    @IOptionsService private _optionsService: IOptionsService\n  ) {\n    this.cols = Math.max(_optionsService.options.cols, MINIMUM_COLS);\n    this.rows = Math.max(_optionsService.options.rows, MINIMUM_ROWS);\n    this.buffers = new BufferSet(_optionsService, this);\n  }\n\n  public resize(cols: number, rows: number): void {\n    this.cols = cols;\n    this.rows = rows;\n  }\n\n  public reset(): void {\n    this.buffers = new BufferSet(this._optionsService, this);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBuffer, IBufferSet } from 'common/buffer/Types';\nimport { IAttributeData } from 'common/Types';\nimport { Buffer } from 'common/buffer/Buffer';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { IOptionsService, IBufferService } from 'common/services/Services';\n\n/**\n * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and\n * provides also utilities for working with them.\n */\nexport class BufferSet implements IBufferSet {\n  private _normal: Buffer;\n  private _alt: Buffer;\n  private _activeBuffer: Buffer;\n\n\n  private _onBufferActivate = new EventEmitter<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}>();\n  public get onBufferActivate(): IEvent<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}> { return this._onBufferActivate.event; }\n\n  /**\n   * Create a new BufferSet for the given terminal.\n   * @param _terminal - The terminal the BufferSet will belong to\n   */\n  constructor(\n    readonly optionsService: IOptionsService,\n    readonly bufferService: IBufferService\n  ) {\n    this._normal = new Buffer(true, optionsService, bufferService);\n    this._normal.fillViewportRows();\n\n    // The alt buffer should never have scrollback.\n    // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer\n    this._alt = new Buffer(false, optionsService, bufferService);\n    this._activeBuffer = this._normal;\n\n    this.setupTabStops();\n  }\n\n  /**\n   * Returns the alt Buffer of the BufferSet\n   */\n  public get alt(): Buffer {\n    return this._alt;\n  }\n\n  /**\n   * Returns the normal Buffer of the BufferSet\n   */\n  public get active(): Buffer {\n    return this._activeBuffer;\n  }\n\n  /**\n   * Returns the currently active Buffer of the BufferSet\n   */\n  public get normal(): Buffer {\n    return this._normal;\n  }\n\n  /**\n   * Sets the normal Buffer of the BufferSet as its currently active Buffer\n   */\n  public activateNormalBuffer(): void {\n    if (this._activeBuffer === this._normal) {\n      return;\n    }\n    this._normal.x = this._alt.x;\n    this._normal.y = this._alt.y;\n    // The alt buffer should always be cleared when we switch to the normal\n    // buffer. This frees up memory since the alt buffer should always be new\n    // when activated.\n    this._alt.clear();\n    this._activeBuffer = this._normal;\n    this._onBufferActivate.fire({\n      activeBuffer: this._normal,\n      inactiveBuffer: this._alt\n    });\n  }\n\n  /**\n   * Sets the alt Buffer of the BufferSet as its currently active Buffer\n   */\n  public activateAltBuffer(fillAttr?: IAttributeData): void {\n    if (this._activeBuffer === this._alt) {\n      return;\n    }\n    // Since the alt buffer is always cleared when the normal buffer is\n    // activated, we want to fill it when switching to it.\n    this._alt.fillViewportRows(fillAttr);\n    this._alt.x = this._normal.x;\n    this._alt.y = this._normal.y;\n    this._activeBuffer = this._alt;\n    this._onBufferActivate.fire({\n      activeBuffer: this._alt,\n      inactiveBuffer: this._normal\n    });\n  }\n\n  /**\n   * Resizes both normal and alt buffers, adjusting their data accordingly.\n   * @param newCols The new number of columns.\n   * @param newRows The new number of rows.\n   */\n  public resize(newCols: number, newRows: number): void {\n    this._normal.resize(newCols, newRows);\n    this._alt.resize(newCols, newRows);\n  }\n\n  /**\n   * Setup the tab stops.\n   * @param i The index to start setting up tab stops from.\n   */\n  public setupTabStops(i?: number): void {\n    this._normal.setupTabStops(i);\n    this._alt.setupTabStops(i);\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { CircularList, IInsertEvent } from 'common/CircularList';\nimport { IBuffer, BufferIndex, IBufferStringIterator, IBufferStringIteratorResult } from 'common/buffer/Types';\nimport { IBufferLine, ICellData, IAttributeData, ICharset } from 'common/Types';\nimport { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';\nimport { CellData } from 'common/buffer/CellData';\nimport { NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_CHAR_INDEX } from 'common/buffer/Constants';\nimport { reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths, getWrappedLineTrimmedLength } from 'common/buffer/BufferReflow';\nimport { Marker } from 'common/buffer/Marker';\nimport { IOptionsService, IBufferService } from 'common/services/Services';\nimport { DEFAULT_CHARSET } from 'common/data/Charsets';\n\nexport const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1\n\n/**\n * This class represents a terminal buffer (an internal state of the terminal), where the\n * following information is stored (in high-level):\n *   - text content of this particular buffer\n *   - cursor position\n *   - scroll position\n */\nexport class Buffer implements IBuffer {\n  public lines: CircularList<IBufferLine>;\n  public ydisp: number = 0;\n  public ybase: number = 0;\n  public y: number = 0;\n  public x: number = 0;\n  public scrollBottom: number;\n  public scrollTop: number;\n  // TODO: Type me\n  public tabs: any;\n  public savedY: number = 0;\n  public savedX: number = 0;\n  public savedCurAttrData = DEFAULT_ATTR_DATA.clone();\n  public savedCharset: ICharset | null = DEFAULT_CHARSET;\n  public markers: Marker[] = [];\n  private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);\n  private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]);\n  private _cols: number;\n  private _rows: number;\n\n  constructor(\n    private _hasScrollback: boolean,\n    private _optionsService: IOptionsService,\n    private _bufferService: IBufferService\n  ) {\n    this._cols = this._bufferService.cols;\n    this._rows = this._bufferService.rows;\n    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));\n    this.scrollTop = 0;\n    this.scrollBottom = this._rows - 1;\n    this.setupTabStops();\n  }\n\n  public getNullCell(attr?: IAttributeData): ICellData {\n    if (attr) {\n      this._nullCell.fg = attr.fg;\n      this._nullCell.bg = attr.bg;\n    } else {\n      this._nullCell.fg = 0;\n      this._nullCell.bg = 0;\n    }\n    return this._nullCell;\n  }\n\n  public getWhitespaceCell(attr?: IAttributeData): ICellData {\n    if (attr) {\n      this._whitespaceCell.fg = attr.fg;\n      this._whitespaceCell.bg = attr.bg;\n    } else {\n      this._whitespaceCell.fg = 0;\n      this._whitespaceCell.bg = 0;\n    }\n    return this._whitespaceCell;\n  }\n\n  public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine {\n    return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped);\n  }\n\n  public get hasScrollback(): boolean {\n    return this._hasScrollback && this.lines.maxLength > this._rows;\n  }\n\n  public get isCursorInViewport(): boolean {\n    const absoluteY = this.ybase + this.y;\n    const relativeY = absoluteY - this.ydisp;\n    return (relativeY >= 0 && relativeY < this._rows);\n  }\n\n  /**\n   * Gets the correct buffer length based on the rows provided, the terminal's\n   * scrollback and whether this buffer is flagged to have scrollback or not.\n   * @param rows The terminal rows to use in the calculation.\n   */\n  private _getCorrectBufferLength(rows: number): number {\n    if (!this._hasScrollback) {\n      return rows;\n    }\n\n    const correctBufferLength = rows + this._optionsService.options.scrollback;\n\n    return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength;\n  }\n\n  /**\n   * Fills the buffer's viewport with blank lines.\n   */\n  public fillViewportRows(fillAttr?: IAttributeData): void {\n    if (this.lines.length === 0) {\n      if (fillAttr === undefined) {\n        fillAttr = DEFAULT_ATTR_DATA;\n      }\n      let i = this._rows;\n      while (i--) {\n        this.lines.push(this.getBlankLine(fillAttr));\n      }\n    }\n  }\n\n  /**\n   * Clears the buffer to it's initial state, discarding all previous data.\n   */\n  public clear(): void {\n    this.ydisp = 0;\n    this.ybase = 0;\n    this.y = 0;\n    this.x = 0;\n    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));\n    this.scrollTop = 0;\n    this.scrollBottom = this._rows - 1;\n    this.setupTabStops();\n  }\n\n  /**\n   * Resizes the buffer, adjusting its data accordingly.\n   * @param newCols The new number of columns.\n   * @param newRows The new number of rows.\n   */\n  public resize(newCols: number, newRows: number): void {\n    // store reference to null cell with default attrs\n    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n\n    // Increase max length if needed before adjustments to allow space to fill\n    // as required.\n    const newMaxLength = this._getCorrectBufferLength(newRows);\n    if (newMaxLength > this.lines.maxLength) {\n      this.lines.maxLength = newMaxLength;\n    }\n\n    // The following adjustments should only happen if the buffer has been\n    // initialized/filled.\n    if (this.lines.length > 0) {\n      // Deal with columns increasing (reducing needs to happen after reflow)\n      if (this._cols < newCols) {\n        for (let i = 0; i < this.lines.length; i++) {\n          this.lines.get(i)!.resize(newCols, nullCell);\n        }\n      }\n\n      // Resize rows in both directions as needed\n      let addToY = 0;\n      if (this._rows < newRows) {\n        for (let y = this._rows; y < newRows; y++) {\n          if (this.lines.length < newRows + this.ybase) {\n            if (this._optionsService.options.windowsMode) {\n              // Just add the new missing rows on Windows as conpty reprints the screen with it's\n              // view of the world. Once a line enters scrollback for conpty it remains there\n              this.lines.push(new BufferLine(newCols, nullCell));\n            } else {\n              if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {\n                // There is room above the buffer and there are no empty elements below the line,\n                // scroll up\n                this.ybase--;\n                addToY++;\n                if (this.ydisp > 0) {\n                  // Viewport is at the top of the buffer, must increase downwards\n                  this.ydisp--;\n                }\n              } else {\n                // Add a blank line if there is no buffer left at the top to scroll to, or if there\n                // are blank lines after the cursor\n                this.lines.push(new BufferLine(newCols, nullCell));\n              }\n            }\n          }\n        }\n      } else { // (this._rows >= newRows)\n        for (let y = this._rows; y > newRows; y--) {\n          if (this.lines.length > newRows + this.ybase) {\n            if (this.lines.length > this.ybase + this.y + 1) {\n              // The line is a blank line below the cursor, remove it\n              this.lines.pop();\n            } else {\n              // The line is the cursor, scroll down\n              this.ybase++;\n              this.ydisp++;\n            }\n          }\n        }\n      }\n\n      // Reduce max length if needed after adjustments, this is done after as it\n      // would otherwise cut data from the bottom of the buffer.\n      if (newMaxLength < this.lines.maxLength) {\n        // Trim from the top of the buffer and adjust ybase and ydisp.\n        const amountToTrim = this.lines.length - newMaxLength;\n        if (amountToTrim > 0) {\n          this.lines.trimStart(amountToTrim);\n          this.ybase = Math.max(this.ybase - amountToTrim, 0);\n          this.ydisp = Math.max(this.ydisp - amountToTrim, 0);\n          this.savedY = Math.max(this.savedY - amountToTrim, 0);\n        }\n        this.lines.maxLength = newMaxLength;\n      }\n\n      // Make sure that the cursor stays on screen\n      this.x = Math.min(this.x, newCols - 1);\n      this.y = Math.min(this.y, newRows - 1);\n      if (addToY) {\n        this.y += addToY;\n      }\n      this.savedX = Math.min(this.savedX, newCols - 1);\n\n      this.scrollTop = 0;\n    }\n\n    this.scrollBottom = newRows - 1;\n\n    if (this._isReflowEnabled) {\n      this._reflow(newCols, newRows);\n\n      // Trim the end of the line off if cols shrunk\n      if (this._cols > newCols) {\n        for (let i = 0; i < this.lines.length; i++) {\n          this.lines.get(i)!.resize(newCols, nullCell);\n        }\n      }\n    }\n\n    this._cols = newCols;\n    this._rows = newRows;\n  }\n\n  private get _isReflowEnabled(): boolean {\n    return this._hasScrollback && !this._optionsService.options.windowsMode;\n  }\n\n  private _reflow(newCols: number, newRows: number): void {\n    if (this._cols === newCols) {\n      return;\n    }\n\n    // Iterate through rows, ignore the last one as it cannot be wrapped\n    if (newCols > this._cols) {\n      this._reflowLarger(newCols, newRows);\n    } else {\n      this._reflowSmaller(newCols, newRows);\n    }\n  }\n\n  private _reflowLarger(newCols: number, newRows: number): void {\n    const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA));\n    if (toRemove.length > 0) {\n      const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove);\n      reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout);\n      this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved);\n    }\n  }\n\n  private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void {\n    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n    // Adjust viewport based on number of items removed\n    let viewportAdjustments = countRemoved;\n    while (viewportAdjustments-- > 0) {\n      if (this.ybase === 0) {\n        if (this.y > 0) {\n          this.y--;\n        }\n        if (this.lines.length < newRows) {\n          // Add an extra row at the bottom of the viewport\n          this.lines.push(new BufferLine(newCols, nullCell));\n        }\n      } else {\n        if (this.ydisp === this.ybase) {\n          this.ydisp--;\n        }\n        this.ybase--;\n      }\n    }\n    this.savedY = Math.max(this.savedY - countRemoved, 0);\n  }\n\n  private _reflowSmaller(newCols: number, newRows: number): void {\n    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);\n    // Gather all BufferLines that need to be inserted into the Buffer here so that they can be\n    // batched up and only committed once\n    const toInsert = [];\n    let countToInsert = 0;\n    // Go backwards as many lines may be trimmed and this will avoid considering them\n    for (let y = this.lines.length - 1; y >= 0; y--) {\n      // Check whether this line is a problem\n      let nextLine = this.lines.get(y) as BufferLine;\n      if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) {\n        continue;\n      }\n\n      // Gather wrapped lines and adjust y to be the starting line\n      const wrappedLines: BufferLine[] = [nextLine];\n      while (nextLine.isWrapped && y > 0) {\n        nextLine = this.lines.get(--y) as BufferLine;\n        wrappedLines.unshift(nextLine);\n      }\n\n      // If these lines contain the cursor don't touch them, the program will handle fixing up\n      // wrapped lines with the cursor\n      const absoluteY = this.ybase + this.y;\n      if (absoluteY >= y && absoluteY < y + wrappedLines.length) {\n        continue;\n      }\n\n      const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength();\n      const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols);\n      const linesToAdd = destLineLengths.length - wrappedLines.length;\n      let trimmedLines: number;\n      if (this.ybase === 0 && this.y !== this.lines.length - 1) {\n        // If the top section of the buffer is not yet filled\n        trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd);\n      } else {\n        trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd);\n      }\n\n      // Add the new lines\n      const newLines: BufferLine[] = [];\n      for (let i = 0; i < linesToAdd; i++) {\n        const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine;\n        newLines.push(newLine);\n      }\n      if (newLines.length > 0) {\n        toInsert.push({\n          // countToInsert here gets the actual index, taking into account other inserted items.\n          // using this we can iterate through the list forwards\n          start: y + wrappedLines.length + countToInsert,\n          newLines\n        });\n        countToInsert += newLines.length;\n      }\n      wrappedLines.push(...newLines);\n\n      // Copy buffer data to new locations, this needs to happen backwards to do in-place\n      let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);\n      let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;\n      if (destCol === 0) {\n        destLineIndex--;\n        destCol = destLineLengths[destLineIndex];\n      }\n      let srcLineIndex = wrappedLines.length - linesToAdd - 1;\n      let srcCol = lastLineLength;\n      while (srcLineIndex >= 0) {\n        const cellsToCopy = Math.min(srcCol, destCol);\n        wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);\n        destCol -= cellsToCopy;\n        if (destCol === 0) {\n          destLineIndex--;\n          destCol = destLineLengths[destLineIndex];\n        }\n        srcCol -= cellsToCopy;\n        if (srcCol === 0) {\n          srcLineIndex--;\n          const wrappedLinesIndex = Math.max(srcLineIndex, 0);\n          srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols);\n        }\n      }\n\n      // Null out the end of the line ends if a wide character wrapped to the following line\n      for (let i = 0; i < wrappedLines.length; i++) {\n        if (destLineLengths[i] < newCols) {\n          wrappedLines[i].setCell(destLineLengths[i], nullCell);\n        }\n      }\n\n      // Adjust viewport as needed\n      let viewportAdjustments = linesToAdd - trimmedLines;\n      while (viewportAdjustments-- > 0) {\n        if (this.ybase === 0) {\n          if (this.y < newRows - 1) {\n            this.y++;\n            this.lines.pop();\n          } else {\n            this.ybase++;\n            this.ydisp++;\n          }\n        } else {\n          // Ensure ybase does not exceed its maximum value\n          if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) {\n            if (this.ybase === this.ydisp) {\n              this.ydisp++;\n            }\n            this.ybase++;\n          }\n        }\n      }\n      this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1);\n    }\n\n    // Rearrange lines in the buffer if there are any insertions, this is done at the end rather\n    // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many\n    // costly calls to CircularList.splice.\n    if (toInsert.length > 0) {\n      // Record buffer insert events and then play them back backwards so that the indexes are\n      // correct\n      const insertEvents: IInsertEvent[] = [];\n\n      // Record original lines so they don't get overridden when we rearrange the list\n      const originalLines: BufferLine[] = [];\n      for (let i = 0; i < this.lines.length; i++) {\n        originalLines.push(this.lines.get(i) as BufferLine);\n      }\n      const originalLinesLength = this.lines.length;\n\n      let originalLineIndex = originalLinesLength - 1;\n      let nextToInsertIndex = 0;\n      let nextToInsert = toInsert[nextToInsertIndex];\n      this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert);\n      let countInsertedSoFar = 0;\n      for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) {\n        if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) {\n          // Insert extra lines here, adjusting i as needed\n          for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) {\n            this.lines.set(i--, nextToInsert.newLines[nextI]);\n          }\n          i++;\n\n          // Create insert events for later\n          insertEvents.push({\n            index: originalLineIndex + 1,\n            amount: nextToInsert.newLines.length\n          });\n\n          countInsertedSoFar += nextToInsert.newLines.length;\n          nextToInsert = toInsert[++nextToInsertIndex];\n        } else {\n          this.lines.set(i, originalLines[originalLineIndex--]);\n        }\n      }\n\n      // Update markers\n      let insertCountEmitted = 0;\n      for (let i = insertEvents.length - 1; i >= 0; i--) {\n        insertEvents[i].index += insertCountEmitted;\n        this.lines.onInsertEmitter.fire(insertEvents[i]);\n        insertCountEmitted += insertEvents[i].amount;\n      }\n      const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength);\n      if (amountToTrim > 0) {\n        this.lines.onTrimEmitter.fire(amountToTrim);\n      }\n    }\n  }\n\n  // private _reflowSmallerGetLinesNeeded()\n\n  /**\n   * Translates a string index back to a BufferIndex.\n   * To get the correct buffer position the string must start at `startCol` 0\n   * (default in translateBufferLineToString).\n   * The method also works on wrapped line strings given rows were not trimmed.\n   * The method operates on the CharData string length, there are no\n   * additional content or boundary checks. Therefore the string and the buffer\n   * should not be altered in between.\n   * TODO: respect trim flag after fixing #1685\n   * @param lineIndex line index the string was retrieved from\n   * @param stringIndex index within the string\n   * @param startCol column offset the string was retrieved from\n   */\n  public stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight: boolean = false): BufferIndex {\n    while (stringIndex) {\n      const line = this.lines.get(lineIndex);\n      if (!line) {\n        return [-1, -1];\n      }\n      const length = (trimRight) ? line.getTrimmedLength() : line.length;\n      for (let i = 0; i < length; ++i) {\n        if (line.get(i)[CHAR_DATA_WIDTH_INDEX]) {\n          // empty cells report a string length of 0, but get replaced\n          // with a whitespace in translateToString, thus replace with 1\n          stringIndex -= line.get(i)[CHAR_DATA_CHAR_INDEX].length || 1;\n        }\n        if (stringIndex < 0) {\n          return [lineIndex, i];\n        }\n      }\n      lineIndex++;\n    }\n    return [lineIndex, 0];\n  }\n\n  /**\n   * Translates a buffer line to a string, with optional start and end columns.\n   * Wide characters will count as two columns in the resulting string. This\n   * function is useful for getting the actual text underneath the raw selection\n   * position.\n   * @param line The line being translated.\n   * @param trimRight Whether to trim whitespace to the right.\n   * @param startCol The column to start at.\n   * @param endCol The column to end at.\n   */\n  public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string {\n    const line = this.lines.get(lineIndex);\n    if (!line) {\n      return '';\n    }\n    return line.translateToString(trimRight, startCol, endCol);\n  }\n\n  public getWrappedRangeForLine(y: number): { first: number, last: number } {\n    let first = y;\n    let last = y;\n    // Scan upwards for wrapped lines\n    while (first > 0 && this.lines.get(first)!.isWrapped) {\n      first--;\n    }\n    // Scan downwards for wrapped lines\n    while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) {\n      last++;\n    }\n    return { first, last };\n  }\n\n  /**\n   * Setup the tab stops.\n   * @param i The index to start setting up tab stops from.\n   */\n  public setupTabStops(i?: number): void {\n    if (i !== null && i !== undefined) {\n      if (!this.tabs[i]) {\n        i = this.prevStop(i);\n      }\n    } else {\n      this.tabs = {};\n      i = 0;\n    }\n\n    for (; i < this._cols; i += this._optionsService.options.tabStopWidth) {\n      this.tabs[i] = true;\n    }\n  }\n\n  /**\n   * Move the cursor to the previous tab stop from the given position (default is current).\n   * @param x The position to move the cursor to the previous tab stop.\n   */\n  public prevStop(x?: number): number {\n    if (x === null || x === undefined) {\n      x = this.x;\n    }\n    while (!this.tabs[--x] && x > 0);\n    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n  }\n\n  /**\n   * Move the cursor one tab stop forward from the given position (default is current).\n   * @param x The position to move the cursor one tab stop forward.\n   */\n  public nextStop(x?: number): number {\n    if (x === null || x === undefined) {\n      x = this.x;\n    }\n    while (!this.tabs[++x] && x < this._cols);\n    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;\n  }\n\n  public addMarker(y: number): Marker {\n    const marker = new Marker(y);\n    this.markers.push(marker);\n    marker.register(this.lines.onTrim(amount => {\n      marker.line -= amount;\n      // The marker should be disposed when the line is trimmed from the buffer\n      if (marker.line < 0) {\n        marker.dispose();\n      }\n    }));\n    marker.register(this.lines.onInsert(event => {\n      if (marker.line >= event.index) {\n        marker.line += event.amount;\n      }\n    }));\n    marker.register(this.lines.onDelete(event => {\n      // Delete the marker if it's within the range\n      if (marker.line >= event.index && marker.line < event.index + event.amount) {\n        marker.dispose();\n      }\n\n      // Shift the marker if it's after the deleted range\n      if (marker.line > event.index) {\n        marker.line -= event.amount;\n      }\n    }));\n    marker.register(marker.onDispose(() => this._removeMarker(marker)));\n    return marker;\n  }\n\n  private _removeMarker(marker: Marker): void {\n    this.markers.splice(this.markers.indexOf(marker), 1);\n  }\n\n  public iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator {\n    return new BufferStringIterator(this, trimRight, startIndex, endIndex, startOverscan, endOverscan);\n  }\n}\n\n/**\n * Iterator to get unwrapped content strings from the buffer.\n * The iterator returns at least the string data between the borders\n * `startIndex` and `endIndex` (exclusive) and will expand the lines\n * by `startOverscan` to the top and by `endOverscan` to the bottom,\n * if no new line was found in between.\n * It will never read/return string data beyond `startIndex - startOverscan`\n * or `endIndex + endOverscan`. Therefore the first and last line might be truncated.\n * It is possible to always get the full string for the first and last line as well\n * by setting the overscan values to the actual buffer length. This not recommended\n * since it might return the whole buffer within a single string in a worst case scenario.\n */\nexport class BufferStringIterator implements IBufferStringIterator {\n  private _current: number;\n\n  constructor (\n    private _buffer: IBuffer,\n    private _trimRight: boolean,\n    private _startIndex: number = 0,\n    private _endIndex: number = _buffer.lines.length,\n    private _startOverscan: number = 0,\n    private _endOverscan: number = 0\n  ) {\n    if (this._startIndex < 0) {\n      this._startIndex = 0;\n    }\n    if (this._endIndex > this._buffer.lines.length) {\n      this._endIndex = this._buffer.lines.length;\n    }\n    this._current = this._startIndex;\n  }\n\n  public hasNext(): boolean {\n    return this._current < this._endIndex;\n  }\n\n  public next(): IBufferStringIteratorResult {\n    const range = this._buffer.getWrappedRangeForLine(this._current);\n    // limit search window to overscan value at both borders\n    if (range.first < this._startIndex - this._startOverscan) {\n      range.first = this._startIndex - this._startOverscan;\n    }\n    if (range.last > this._endIndex + this._endOverscan) {\n      range.last = this._endIndex + this._endOverscan;\n    }\n    // limit to current buffer length\n    range.first = Math.max(range.first, 0);\n    range.last = Math.min(range.last, this._buffer.lines.length);\n    let result = '';\n    for (let i = range.first; i <= range.last; ++i) {\n      result += this._buffer.translateBufferLineToString(i, this._trimRight);\n    }\n    this._current = range.last + 1;\n    return {range: range, content: result};\n  }\n}\n","/**\n * Copyright (c) 2016 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICircularList } from 'common/Types';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\n\nexport interface IInsertEvent {\n  index: number;\n  amount: number;\n}\n\nexport interface IDeleteEvent {\n  index: number;\n  amount: number;\n}\n\n/**\n * Represents a circular list; a list with a maximum size that wraps around when push is called,\n * overriding values at the start of the list.\n */\nexport class CircularList<T> implements ICircularList<T> {\n  protected _array: (T | undefined)[];\n  private _startIndex: number;\n  private _length: number;\n\n  public onDeleteEmitter = new EventEmitter<IDeleteEvent>();\n  public get onDelete(): IEvent<IDeleteEvent> { return this.onDeleteEmitter.event; }\n  public onInsertEmitter = new EventEmitter<IInsertEvent>();\n  public get onInsert(): IEvent<IInsertEvent> { return this.onInsertEmitter.event; }\n  public onTrimEmitter = new EventEmitter<number>();\n  public get onTrim(): IEvent<number> { return this.onTrimEmitter.event; }\n\n  constructor(\n    private _maxLength: number\n  ) {\n    this._array = new Array<T>(this._maxLength);\n    this._startIndex = 0;\n    this._length = 0;\n  }\n\n  public get maxLength(): number {\n    return this._maxLength;\n  }\n\n  public set maxLength(newMaxLength: number) {\n    // There was no change in maxLength, return early.\n    if (this._maxLength === newMaxLength) {\n      return;\n    }\n\n    // Reconstruct array, starting at index 0. Only transfer values from the\n    // indexes 0 to length.\n    const newArray = new Array<T | undefined>(newMaxLength);\n    for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {\n      newArray[i] = this._array[this._getCyclicIndex(i)];\n    }\n    this._array = newArray;\n    this._maxLength = newMaxLength;\n    this._startIndex = 0;\n  }\n\n  public get length(): number {\n    return this._length;\n  }\n\n  public set length(newLength: number) {\n    if (newLength > this._length) {\n      for (let i = this._length; i < newLength; i++) {\n        this._array[i] = undefined;\n      }\n    }\n    this._length = newLength;\n  }\n\n  /**\n   * Gets the value at an index.\n   *\n   * Note that for performance reasons there is no bounds checking here, the index reference is\n   * circular so this should always return a value and never throw.\n   * @param index The index of the value to get.\n   * @return The value corresponding to the index.\n   */\n  public get(index: number): T | undefined {\n    return this._array[this._getCyclicIndex(index)];\n  }\n\n  /**\n   * Sets the value at an index.\n   *\n   * Note that for performance reasons there is no bounds checking here, the index reference is\n   * circular so this should always return a value and never throw.\n   * @param index The index to set.\n   * @param value The value to set.\n   */\n  public set(index: number, value: T | undefined): void {\n    this._array[this._getCyclicIndex(index)] = value;\n  }\n\n  /**\n   * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0\n   * if the maximum length is reached.\n   * @param value The value to push onto the list.\n   */\n  public push(value: T): void {\n    this._array[this._getCyclicIndex(this._length)] = value;\n    if (this._length === this._maxLength) {\n      this._startIndex = ++this._startIndex % this._maxLength;\n      this.onTrimEmitter.fire(1);\n    } else {\n      this._length++;\n    }\n  }\n\n  /**\n   * Advance ringbuffer index and return current element for recycling.\n   * Note: The buffer must be full for this method to work.\n   * @throws When the buffer is not full.\n   */\n  public recycle(): T {\n    if (this._length !== this._maxLength) {\n      throw new Error('Can only recycle when the buffer is full');\n    }\n    this._startIndex = ++this._startIndex % this._maxLength;\n    this.onTrimEmitter.fire(1);\n    return this._array[this._getCyclicIndex(this._length - 1)]!;\n  }\n\n  /**\n   * Ringbuffer is at max length.\n   */\n  public get isFull(): boolean {\n    return this._length === this._maxLength;\n  }\n\n  /**\n   * Removes and returns the last value on the list.\n   * @return The popped value.\n   */\n  public pop(): T | undefined {\n    return this._array[this._getCyclicIndex(this._length-- - 1)];\n  }\n\n  /**\n   * Deletes and/or inserts items at a particular index (in that order). Unlike\n   * Array.prototype.splice, this operation does not return the deleted items as a new array in\n   * order to save creating a new array. Note that this operation may shift all values in the list\n   * in the worst case.\n   * @param start The index to delete and/or insert.\n   * @param deleteCount The number of elements to delete.\n   * @param items The items to insert.\n   */\n  public splice(start: number, deleteCount: number, ...items: T[]): void {\n    // Delete items\n    if (deleteCount) {\n      for (let i = start; i < this._length - deleteCount; i++) {\n        this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];\n      }\n      this._length -= deleteCount;\n    }\n\n    // Add items\n    for (let i = this._length - 1; i >= start; i--) {\n      this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];\n    }\n    for (let i = 0; i < items.length; i++) {\n      this._array[this._getCyclicIndex(start + i)] = items[i];\n    }\n\n    // Adjust length as needed\n    if (this._length + items.length > this._maxLength) {\n      const countToTrim = (this._length + items.length) - this._maxLength;\n      this._startIndex += countToTrim;\n      this._length = this._maxLength;\n      this.onTrimEmitter.fire(countToTrim);\n    } else {\n      this._length += items.length;\n    }\n  }\n\n  /**\n   * Trims a number of items from the start of the list.\n   * @param count The number of items to remove.\n   */\n  public trimStart(count: number): void {\n    if (count > this._length) {\n      count = this._length;\n    }\n    this._startIndex += count;\n    this._length -= count;\n    this.onTrimEmitter.fire(count);\n  }\n\n  public shiftElements(start: number, count: number, offset: number): void {\n    if (count <= 0) {\n      return;\n    }\n    if (start < 0 || start >= this._length) {\n      throw new Error('start argument out of range');\n    }\n    if (start + offset < 0) {\n      throw new Error('Cannot shift elements in list beyond index 0');\n    }\n\n    if (offset > 0) {\n      for (let i = count - 1; i >= 0; i--) {\n        this.set(start + i + offset, this.get(start + i));\n      }\n      const expandListBy = (start + count + offset) - this._length;\n      if (expandListBy > 0) {\n        this._length += expandListBy;\n        while (this._length > this._maxLength) {\n          this._length--;\n          this._startIndex++;\n          this.onTrimEmitter.fire(1);\n        }\n      }\n    } else {\n      for (let i = 0; i < count; i++) {\n        this.set(start + i + offset, this.get(start + i));\n      }\n    }\n  }\n\n  /**\n   * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the\n   * backing array to get the element associated with the regular index.\n   * @param index The regular index.\n   * @returns The cyclic index.\n   */\n  private _getCyclicIndex(index: number): number {\n    return (this._startIndex + index) % this._maxLength;\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { BufferLine } from 'common/buffer/BufferLine';\nimport { CircularList } from 'common/CircularList';\nimport { IBufferLine, ICellData } from 'common/Types';\n\nexport interface INewLayoutResult {\n  layout: number[];\n  countRemoved: number;\n}\n\n/**\n * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed\n * when a wrapped line unwraps.\n * @param lines The buffer lines.\n * @param newCols The columns after resize.\n */\nexport function reflowLargerGetLinesToRemove(lines: CircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData): number[] {\n  // Gather all BufferLines that need to be removed from the Buffer here so that they can be\n  // batched up and only committed once\n  const toRemove: number[] = [];\n\n  for (let y = 0; y < lines.length - 1; y++) {\n    // Check if this row is wrapped\n    let i = y;\n    let nextLine = lines.get(++i) as BufferLine;\n    if (!nextLine.isWrapped) {\n      continue;\n    }\n\n    // Check how many lines it's wrapped for\n    const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];\n    while (i < lines.length && nextLine.isWrapped) {\n      wrappedLines.push(nextLine);\n      nextLine = lines.get(++i) as BufferLine;\n    }\n\n    // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped\n    // lines with the cursor\n    if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {\n      y += wrappedLines.length - 1;\n      continue;\n    }\n\n    // Copy buffer data to new locations\n    let destLineIndex = 0;\n    let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols);\n    let srcLineIndex = 1;\n    let srcCol = 0;\n    while (srcLineIndex < wrappedLines.length) {\n      const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols);\n      const srcRemainingCells = srcTrimmedTineLength - srcCol;\n      const destRemainingCells = newCols - destCol;\n      const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);\n\n      wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);\n\n      destCol += cellsToCopy;\n      if (destCol === newCols) {\n        destLineIndex++;\n        destCol = 0;\n      }\n      srcCol += cellsToCopy;\n      if (srcCol === srcTrimmedTineLength) {\n        srcLineIndex++;\n        srcCol = 0;\n      }\n\n      // Make sure the last cell isn't wide, if it is copy it to the current dest\n      if (destCol === 0 && destLineIndex !== 0) {\n        if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {\n          wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);\n          // Null out the end of the last row\n          wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);\n        }\n      }\n    }\n\n    // Clear out remaining cells or fragments could remain;\n    wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell);\n\n    // Work backwards and remove any rows at the end that only contain null cells\n    let countToRemove = 0;\n    for (let i = wrappedLines.length - 1; i > 0; i--) {\n      if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) {\n        countToRemove++;\n      } else {\n        break;\n      }\n    }\n\n    if (countToRemove > 0) {\n      toRemove.push(y + wrappedLines.length - countToRemove); // index\n      toRemove.push(countToRemove);\n    }\n\n    y += wrappedLines.length - 1;\n  }\n  return toRemove;\n}\n\n/**\n * Creates and return the new layout for lines given an array of indexes to be removed.\n * @param lines The buffer lines.\n * @param toRemove The indexes to remove.\n */\nexport function reflowLargerCreateNewLayout(lines: CircularList<IBufferLine>, toRemove: number[]): INewLayoutResult {\n  const layout: number[] = [];\n  // First iterate through the list and get the actual indexes to use for rows\n  let nextToRemoveIndex = 0;\n  let nextToRemoveStart = toRemove[nextToRemoveIndex];\n  let countRemovedSoFar = 0;\n  for (let i = 0; i < lines.length; i++) {\n    if (nextToRemoveStart === i) {\n      const countToRemove = toRemove[++nextToRemoveIndex];\n\n      // Tell markers that there was a deletion\n      lines.onDeleteEmitter.fire({\n        index: i - countRemovedSoFar,\n        amount: countToRemove\n      });\n\n      i += countToRemove - 1;\n      countRemovedSoFar += countToRemove;\n      nextToRemoveStart = toRemove[++nextToRemoveIndex];\n    } else {\n      layout.push(i);\n    }\n  }\n  return {\n    layout,\n    countRemoved: countRemovedSoFar\n  };\n}\n\n/**\n * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's\n * done all at once in a single iteration through the list since splice is very expensive.\n * @param lines The buffer lines.\n * @param newLayout The new layout to apply.\n */\nexport function reflowLargerApplyNewLayout(lines: CircularList<IBufferLine>, newLayout: number[]): void {\n  // Record original lines so they don't get overridden when we rearrange the list\n  const newLayoutLines: BufferLine[] = [];\n  for (let i = 0; i < newLayout.length; i++) {\n    newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);\n  }\n\n  // Rearrange the list\n  for (let i = 0; i < newLayoutLines.length; i++) {\n    lines.set(i, newLayoutLines[i]);\n  }\n  lines.length = newLayout.length;\n}\n\n/**\n * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-\n * compute the wrapping points since wide characters may need to be wrapped onto the following line.\n * This function will return an array of numbers of where each line wraps to, the resulting array\n * will only contain the values `newCols` (when the line does not end with a wide character) and\n * `newCols - 1` (when the line does end with a wide character), except for the last value which\n * will contain the remaining items to fill the line.\n *\n * Calling this with a `newCols` value of `1` will lock up.\n *\n * @param wrappedLines The wrapped lines to evaluate.\n * @param oldCols The columns before resize.\n * @param newCols The columns after resize.\n */\nexport function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {\n  const newLineLengths: number[] = [];\n  const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);\n\n  // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and\n  // linesNeeded\n  let srcCol = 0;\n  let srcLine = 0;\n  let cellsAvailable = 0;\n  while (cellsAvailable < cellsNeeded) {\n    if (cellsNeeded - cellsAvailable < newCols) {\n      // Add the final line and exit the loop\n      newLineLengths.push(cellsNeeded - cellsAvailable);\n      break;\n    }\n    srcCol += newCols;\n    const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols);\n    if (srcCol > oldTrimmedLength) {\n      srcCol -= oldTrimmedLength;\n      srcLine++;\n    }\n    const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2;\n    if (endsWithWide) {\n      srcCol--;\n    }\n    const lineLength = endsWithWide ? newCols - 1 : newCols;\n    newLineLengths.push(lineLength);\n    cellsAvailable += lineLength;\n  }\n\n  return newLineLengths;\n}\n\nexport function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {\n  // If this is the last row in the wrapped line, get the actual trimmed length\n  if (i === lines.length - 1) {\n    return lines[i].getTrimmedLength();\n  }\n  // Detect whether the following line starts with a wide character and the end of the current line\n  // is null, if so then we can be pretty sure the null character should be excluded from the line\n  // length]\n  const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1;\n  const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2;\n  if (endsInNull && followingLineStartsWithWide) {\n    return cols - 1;\n  }\n  return cols;\n}\n","/**\n * Copyright (c) 2018 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { Disposable } from 'common/Lifecycle';\nimport { IMarker } from 'common/Types';\n\nexport class Marker extends Disposable implements IMarker {\n  private static _nextId = 1;\n\n  private _id: number = Marker._nextId++;\n  public isDisposed: boolean = false;\n\n  public get id(): number { return this._id; }\n\n  private _onDispose = new EventEmitter<void>();\n  public get onDispose(): IEvent<void> { return this._onDispose.event; }\n\n  constructor(\n    public line: number\n  ) {\n    super();\n  }\n\n  public dispose(): void {\n    if (this.isDisposed) {\n      return;\n    }\n    this.isDisposed = true;\n    this.line = -1;\n    // Emit before super.dispose such that dispose listeners get a change to react\n    this._onDispose.fire();\n  }\n}\n","/**\n * Copyright (c) 2017 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICharSizeService, IRenderService, IMouseService } from './Services';\nimport { getCoords, getRawByteCoords } from 'browser/input/Mouse';\n\nexport class MouseService implements IMouseService {\n  serviceBrand: any;\n\n  constructor(\n    @IRenderService private readonly _renderService: IRenderService,\n    @ICharSizeService private readonly _charSizeService: ICharSizeService\n  ) {\n  }\n\n  public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined {\n    return getCoords(\n      event,\n      element,\n      colCount,\n      rowCount,\n      this._charSizeService.hasValidSize,\n      this._renderService.dimensions.actualCellWidth,\n      this._renderService.dimensions.actualCellHeight,\n      isSelection\n    );\n  }\n\n  public getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined {\n    const coords = this.getCoords(event, element, colCount, rowCount);\n    return getRawByteCoords(coords);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ICoreService, ILogService, IOptionsService, IBufferService } from 'common/services/Services';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { IDecPrivateModes } from 'common/Types';\nimport { clone } from 'common/Clone';\n\nconst DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({\n  applicationCursorKeys: false\n});\n\nexport class CoreService implements ICoreService {\n  serviceBrand: any;\n\n  public decPrivateModes: IDecPrivateModes;\n\n  private _onData = new EventEmitter<string>();\n  public get onData(): IEvent<string> { return this._onData.event; }\n  private _onUserInput = new EventEmitter<void>();\n  public get onUserInput(): IEvent<void> { return this._onUserInput.event; }\n\n  constructor(\n    // TODO: Move this into a service\n    private readonly _scrollToBottom: () => void,\n    @IBufferService private readonly _bufferService: IBufferService,\n    @ILogService private readonly _logService: ILogService,\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n  }\n\n  public reset(): void {\n    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);\n  }\n\n  public triggerDataEvent(data: string, wasUserInput: boolean = false): void {\n    // Prevents all events to pty process if stdin is disabled\n    if (this._optionsService.options.disableStdin) {\n      return;\n    }\n\n    // Input is being sent to the terminal, the terminal should focus the prompt.\n    const buffer = this._bufferService.buffer;\n    if (buffer.ybase !== buffer.ydisp) {\n      this._scrollToBottom();\n    }\n\n    // Fire onUserInput so listeners can react as well (eg. clear selection)\n    if (wasUserInput) {\n      this._onUserInput.fire();\n    }\n\n    // Fire onData API\n    this._logService.debug(`sending data \"${data}\"`, () => data.split('').map(e => e.charCodeAt(0)));\n    this._onData.fire(data);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ILogService, IOptionsService } from 'common/services/Services';\n\ntype LogType = (message?: any, ...optionalParams: any[]) => void;\n\ninterface IConsole {\n  log: LogType;\n  error: LogType;\n  info: LogType;\n  trace: LogType;\n  warn: LogType;\n}\n\n// console is available on both node.js and browser contexts but the common\n// module doesn't depend on them so we need to explicitly declare it.\ndeclare const console: IConsole;\n\n\nexport enum LogLevel {\n  DEBUG = 0,\n  INFO = 1,\n  WARN = 2,\n  ERROR = 3,\n  OFF = 4\n}\n\nconst optionsKeyToLogLevel: { [key: string]: LogLevel } = {\n  debug: LogLevel.DEBUG,\n  info: LogLevel.INFO,\n  warn: LogLevel.WARN,\n  error: LogLevel.ERROR,\n  off: LogLevel.OFF\n};\n\nconst LOG_PREFIX = 'xterm.js: ';\n\nexport class LogService implements ILogService {\n  serviceBrand: any;\n\n  private _logLevel!: LogLevel;\n\n  constructor(\n    @IOptionsService private readonly _optionsService: IOptionsService\n  ) {\n    this._updateLogLevel();\n    this._optionsService.onOptionChange(key => {\n      if (key === 'logLevel') {\n        this._updateLogLevel();\n      }\n    });\n  }\n\n  private _updateLogLevel(): void {\n    this._logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel];\n  }\n\n  private _evalLazyOptionalParams(optionalParams: any[]): void {\n    for (let i = 0; i < optionalParams.length; i++) {\n      if (typeof optionalParams[i] === 'function') {\n        optionalParams[i] = optionalParams[i]();\n      }\n    }\n  }\n\n  private _log(type: LogType, message: string, optionalParams: any[]): void {\n    this._evalLazyOptionalParams(optionalParams);\n    type.call(console, LOG_PREFIX + message, ...optionalParams);\n  }\n\n  debug(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.DEBUG) {\n      this._log(console.log, message, optionalParams);\n    }\n  }\n\n  info(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.INFO) {\n      this._log(console.info, message, optionalParams);\n    }\n  }\n\n  warn(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.WARN) {\n      this._log(console.warn, message, optionalParams);\n    }\n  }\n\n  error(message: string, ...optionalParams: any[]): void {\n    if (this._logLevel <= LogLevel.ERROR) {\n      this._log(console.error, message, optionalParams);\n    }\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IBufferService, IDirtyRowService } from 'common/services/Services';\n\nexport class DirtyRowService implements IDirtyRowService {\n  serviceBrand: any;\n\n  private _start!: number;\n  private _end!: number;\n\n  public get start(): number { return this._start; }\n  public get end(): number { return this._end; }\n\n  constructor(\n    @IBufferService private readonly _bufferService: IBufferService\n  ) {\n    this.clearRange();\n  }\n\n  public clearRange(): void {\n    this._start = this._bufferService.buffer.y;\n    this._end = this._bufferService.buffer.y;\n  }\n\n  public markDirty(y: number): void {\n    if (y < this._start) {\n      this._start = y;\n    } else if (y > this._end) {\n      this._end = y;\n    }\n  }\n\n  public markRangeDirty(y1: number, y2: number): void {\n    if (y1 > y2) {\n      const temp = y1;\n      y1 = y2;\n      y2 = temp;\n    }\n    if (y1 < this._start) {\n      this._start = y1;\n    }\n    if (y2 > this._end) {\n      this._end = y2;\n    }\n  }\n\n  public markAllDirty(): void {\n    this.markRangeDirty(0, this._bufferService.rows - 1);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).\n */\n/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\nimport { IInstantiationService, IServiceIdentifier } from 'common/services/Services';\nimport { getServiceDependencies } from 'common/services/ServiceRegistry';\n\nexport class ServiceCollection {\n\n  private _entries = new Map<IServiceIdentifier<any>, any>();\n\n  constructor(...entries: [IServiceIdentifier<any>, any][]) {\n    for (const [id, service] of entries) {\n      this.set(id, service);\n    }\n  }\n\n  set<T>(id: IServiceIdentifier<T>, instance: T): T {\n    const result = this._entries.get(id);\n    this._entries.set(id, instance);\n    return result;\n  }\n\n  forEach(callback: (id: IServiceIdentifier<any>, instance: any) => any): void {\n    this._entries.forEach((value, key) => callback(key, value));\n  }\n\n  has(id: IServiceIdentifier<any>): boolean {\n    return this._entries.has(id);\n  }\n\n  get<T>(id: IServiceIdentifier<T>): T {\n    return this._entries.get(id);\n  }\n}\n\nexport class InstantiationService implements IInstantiationService {\n  private readonly _services: ServiceCollection = new ServiceCollection();\n\n  constructor() {\n    this._services.set(IInstantiationService, this);\n  }\n\n  public setService<T>(id: IServiceIdentifier<T>, instance: T): void {\n    this._services.set(id, instance);\n  }\n\n  public createInstance<T>(ctor: any, ...args: any[]): any {\n    const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index);\n\n    const serviceArgs: any[] = [];\n    for (const dependency of serviceDependencies) {\n      const service = this._services.get(dependency.id);\n      if (!service) {\n        throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);\n      }\n      serviceArgs.push(service);\n    }\n\n    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;\n\n    // check for argument mismatches, adjust static args if needed\n    if (args.length !== firstServiceArgPos) {\n      throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);\n    }\n\n    // now create the instance\n    return <T>new ctor(...[...args, ...serviceArgs]);\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IBufferService, ICoreService, ICoreMouseService } from 'common/services/Services';\nimport { EventEmitter, IEvent } from 'common/EventEmitter';\nimport { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';\n\n/**\n * Supported default protocols.\n */\nconst DEFAULT_PROTOCOLS: {[key: string]: ICoreMouseProtocol} = {\n  /**\n   * NONE\n   * Events: none\n   * Modifiers: none\n   */\n  NONE: {\n    events: CoreMouseEventType.NONE,\n    restrict: () => false\n  },\n  /**\n   * X10\n   * Events: mousedown\n   * Modifiers: none\n   */\n  X10: {\n    events: CoreMouseEventType.DOWN,\n    restrict: (e: ICoreMouseEvent) => {\n      // no wheel, no move, no up\n      if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) {\n        return false;\n      }\n      // no modifiers\n      e.ctrl = false;\n      e.alt = false;\n      e.shift = false;\n      return true;\n    }\n  },\n  /**\n   * VT200\n   * Events: mousedown / mouseup / wheel\n   * Modifiers: all\n   */\n  VT200: {\n    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL,\n    restrict: (e: ICoreMouseEvent) => {\n      // no move\n      if (e.action === CoreMouseAction.MOVE) {\n        return false;\n      }\n      return true;\n    }\n  },\n  /**\n   * DRAG\n   * Events: mousedown / mouseup / wheel / mousedrag\n   * Modifiers: all\n   */\n  DRAG: {\n    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG,\n    restrict: (e: ICoreMouseEvent) => {\n      // no move without button\n      if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) {\n        return false;\n      }\n      return true;\n    }\n  },\n  /**\n   * ANY\n   * Events: all mouse related events\n   * Modifiers: all\n   */\n  ANY: {\n    events:\n      CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL\n      | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE,\n    restrict: (e: ICoreMouseEvent) => true\n  }\n};\n\nconst enum Modifiers {\n  SHIFT = 4,\n  ALT = 8,\n  CTRL = 16\n}\n\n// helper for default encoders to generate the event code.\nfunction eventCode(e: ICoreMouseEvent, isSGR: boolean): number {\n  let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0);\n  if (e.button === CoreMouseButton.WHEEL) {\n    code |= 64;\n    code |= e.action;\n  } else {\n    code |= e.button & 3;\n    if (e.button & 4) {\n      code |= 64;\n    }\n    if (e.button & 8) {\n      code |= 128;\n    }\n    if (e.action === CoreMouseAction.MOVE) {\n      code |= CoreMouseAction.MOVE;\n    } else if (e.action === CoreMouseAction.UP && !isSGR) {\n      // special case - only SGR can report button on release\n      // all others have to go with NONE\n      code |= CoreMouseButton.NONE;\n    }\n  }\n  return code;\n}\n\nconst S = String.fromCharCode;\n\n/**\n * Supported default encodings.\n */\nconst DEFAULT_ENCODINGS: {[key: string]: CoreMouseEncoding} = {\n  /**\n   * DEFAULT - CSI M Pb Px Py\n   * Single byte encoding for coords and event code.\n   * Can encode values up to 223. The Encoding of higher\n   * values is not UTF-8 compatible (and currently limited\n   * to 95 in xterm.js).\n   */\n  DEFAULT: (e: ICoreMouseEvent) => {\n    let params = [eventCode(e, false) + 32, e.col + 32, e.row + 32];\n    // FIXME: we are currently limited to ASCII range\n    params = params.map(v => (v > 127) ? 127 : v);\n    // FIXED: params = params.map(v => (v > 255) ? 0 : value);\n    return `\\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`;\n  },\n  /**\n   * SGR - CSI < Pb ; Px ; Py M|m\n   * No encoding limitation.\n   * Can report button on release and works with a well formed sequence.\n   */\n  SGR: (e: ICoreMouseEvent) => {\n    const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';\n    return `\\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`;\n  }\n};\n\n/**\n * CoreMouseService\n *\n * Provides mouse tracking reports with different protocols and encodings.\n *  - protocols: NONE (default), X10, VT200, DRAG, ANY\n *  - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507)\n *\n * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`.\n * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`.\n * Switching a protocol will send a notification event `onProtocolChange`\n * with a list of needed events to track.\n *\n * The service handles the mouse tracking state and decides whether to send\n * a tracking report to the backend based on protocol and encoding limitations.\n * To send a mouse event call `triggerMouseEvent`.\n */\nexport class CoreMouseService implements ICoreMouseService {\n  private _protocols: {[name: string]: ICoreMouseProtocol} = {};\n  private _encodings: {[name: string]: CoreMouseEncoding} = {};\n  private _activeProtocol: string = '';\n  private _activeEncoding: string = '';\n  private _onProtocolChange = new EventEmitter<CoreMouseEventType>();\n  private _lastEvent: ICoreMouseEvent | null = null;\n\n  constructor(\n    @IBufferService private readonly _bufferService: IBufferService,\n    @ICoreService private readonly _coreService: ICoreService\n  ) {\n    // register default protocols and encodings\n    Object.keys(DEFAULT_PROTOCOLS).forEach(name => this.addProtocol(name, DEFAULT_PROTOCOLS[name]));\n    Object.keys(DEFAULT_ENCODINGS).forEach(name => this.addEncoding(name, DEFAULT_ENCODINGS[name]));\n    // call reset to set defaults\n    this.reset();\n  }\n\n  public addProtocol(name: string, protocol: ICoreMouseProtocol): void {\n    this._protocols[name] = protocol;\n  }\n\n  public addEncoding(name: string, encoding: CoreMouseEncoding): void {\n    this._encodings[name] = encoding;\n  }\n\n  public get activeProtocol(): string {\n    return this._activeProtocol;\n  }\n\n  public set activeProtocol(name: string) {\n    if (!this._protocols[name]) {\n      throw new Error(`unknown protocol \"${name}\"`);\n    }\n    this._activeProtocol = name;\n    this._onProtocolChange.fire(this._protocols[name].events);\n  }\n\n  public get activeEncoding(): string {\n    return this._activeEncoding;\n  }\n\n  public set activeEncoding(name: string) {\n    if (!this._encodings[name]) {\n      throw new Error(`unknown encoding \"${name}\"`);\n    }\n    this._activeEncoding = name;\n  }\n\n  public reset(): void {\n    this.activeProtocol = 'NONE';\n    this.activeEncoding = 'DEFAULT';\n    this._lastEvent = null;\n  }\n\n  /**\n   * Event to announce changes in mouse tracking.\n   */\n  public get onProtocolChange(): IEvent<CoreMouseEventType> {\n    return this._onProtocolChange.event;\n  }\n\n  /**\n   * Triggers a mouse event to be sent.\n   *\n   * Returns true if the event passed all protocol restrictions and a report\n   * was sent, otherwise false. The return value may be used to decide whether\n   * the default event action in the bowser component should be omitted.\n   *\n   * Note: The method will change values of the given event object\n   * to fullfill protocol and encoding restrictions.\n   */\n  public triggerMouseEvent(e: ICoreMouseEvent): boolean {\n    // range check for col/row\n    if (e.col < 0 || e.col >= this._bufferService.cols\n        || e.row < 0 || e.row >= this._bufferService.rows) {\n      return false;\n    }\n\n    // filter nonsense combinations of button + action\n    if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) {\n      return false;\n    }\n    if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) {\n      return false;\n    }\n    if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) {\n      return false;\n    }\n\n    // report 1-based coords\n    e.col++;\n    e.row++;\n\n    // debounce move at grid level\n    if (e.action === CoreMouseAction.MOVE && this._lastEvent && this._compareEvents(this._lastEvent, e)) {\n      return false;\n    }\n\n    // apply protocol restrictions\n    if (!this._protocols[this._activeProtocol].restrict(e)) {\n      return false;\n    }\n\n    // encode report and send\n    const report = this._encodings[this._activeEncoding](e);\n    this._coreService.triggerDataEvent(report, true);\n\n    this._lastEvent = e;\n\n    return true;\n  }\n\n  public explainEvents(events: CoreMouseEventType): {[event: string]: boolean} {\n    return {\n      DOWN: !!(events & CoreMouseEventType.DOWN),\n      UP: !!(events & CoreMouseEventType.UP),\n      DRAG: !!(events & CoreMouseEventType.DRAG),\n      MOVE: !!(events & CoreMouseEventType.MOVE),\n      WHEEL: !!(events & CoreMouseEventType.WHEEL)\n    };\n  }\n\n  private _compareEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent): boolean {\n    if (e1.col !== e2.col) return false;\n    if (e1.row !== e2.row) return false;\n    if (e1.button !== e2.button) return false;\n    if (e1.action !== e2.action) return false;\n    if (e1.ctrl !== e2.ctrl) return false;\n    if (e1.alt !== e2.alt) return false;\n    if (e1.shift !== e2.shift) return false;\n    return true;\n  }\n}\n","\n/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\ndeclare const setTimeout: (handler: () => void, timeout?: number) => void;\n\n/**\n * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.\n * Enable flow control to avoid this limit and make sure that your backend correctly\n * propagates this to the underlying pty. (see docs for further instructions)\n * Since this limit is meant as a safety parachute to prevent browser crashs,\n * it is set to a very high number. Typically xterm.js gets unresponsive with\n * a 100 times lower number (>500 kB).\n */\nconst DISCARD_WATERMARK = 50000000; // ~50 MB\n\n/**\n * The max number of ms to spend on writes before allowing the renderer to\n * catch up with a 0ms setTimeout. A value of < 33 to keep us close to\n * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS\n * depends on the time it takes for the renderer to draw the frame.\n */\nconst WRITE_TIMEOUT_MS = 12;\n\n/**\n * Threshold of max held chunks in the write buffer, that were already processed.\n * This is a tradeoff between extensive write buffer shifts (bad runtime) and high\n * memory consumption by data thats not used anymore.\n */\nconst WRITE_BUFFER_LENGTH_THRESHOLD = 50;\n\nexport class WriteBuffer {\n  private _writeBuffer: (string | Uint8Array)[] = [];\n  private _callbacks: ((() => void) | undefined)[] = [];\n  private _pendingData = 0;\n  private _bufferOffset = 0;\n\n  constructor(private _action: (data: string | Uint8Array) => void) { }\n\n  public writeSync(data: string | Uint8Array): void {\n    // force sync processing on pending data chunks to avoid in-band data scrambling\n    // does the same as innerWrite but without event loop\n    if (this._writeBuffer.length) {\n      for (let i = this._bufferOffset; i < this._writeBuffer.length; ++i) {\n        const data = this._writeBuffer[i];\n        const cb = this._callbacks[i];\n        this._action(data);\n        if (cb) cb();\n      }\n      // reset all to avoid reprocessing of chunks with scheduled innerWrite call\n      this._writeBuffer = [];\n      this._callbacks = [];\n      this._pendingData = 0;\n      // stop scheduled innerWrite by offset > length condition\n      this._bufferOffset = 0x7FFFFFFF;\n    }\n    // handle current data chunk\n    this._action(data);\n  }\n\n  public write(data: string | Uint8Array, callback?: () => void): void {\n    if (this._pendingData > DISCARD_WATERMARK) {\n      throw new Error('write data discarded, use flow control to avoid losing data');\n    }\n\n    // schedule chunk processing for next event loop run\n    if (!this._writeBuffer.length) {\n      this._bufferOffset = 0;\n      setTimeout(() => this._innerWrite());\n    }\n\n    this._pendingData += data.length;\n    this._writeBuffer.push(data);\n    this._callbacks.push(callback);\n  }\n\n  protected _innerWrite(): void {\n    const startTime = Date.now();\n    while (this._writeBuffer.length > this._bufferOffset) {\n      const data = this._writeBuffer[this._bufferOffset];\n      const cb = this._callbacks[this._bufferOffset];\n      this._bufferOffset++;\n\n      this._action(data);\n      this._pendingData -= data.length;\n      if (cb) cb();\n\n      if (Date.now() - startTime >= WRITE_TIMEOUT_MS) {\n        break;\n      }\n    }\n    if (this._writeBuffer.length > this._bufferOffset) {\n      // Allow renderer to catch up before processing the next batch\n      // trim already processed chunks if we are above threshold\n      if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {\n        this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);\n        this._callbacks = this._callbacks.slice(this._bufferOffset);\n        this._bufferOffset = 0;\n      }\n      setTimeout(() => this._innerWrite(), 0);\n    } else {\n      this._writeBuffer = [];\n      this._callbacks = [];\n      this._pendingData = 0;\n      this._bufferOffset = 0;\n    }\n  }\n}\n","/**\n * Copyright (c) 2019 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ITerminalAddon, IDisposable, Terminal } from 'xterm';\n\nexport interface ILoadedAddon {\n  instance: ITerminalAddon;\n  dispose: () => void;\n  isDisposed: boolean;\n}\n\nexport class AddonManager implements IDisposable {\n  protected _addons: ILoadedAddon[] = [];\n\n  constructor() {\n  }\n\n  public dispose(): void {\n    for (let i = this._addons.length - 1; i >= 0; i--) {\n      this._addons[i].instance.dispose();\n    }\n  }\n\n  public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {\n    const loadedAddon: ILoadedAddon = {\n      instance,\n      dispose: instance.dispose,\n      isDisposed: false\n    };\n    this._addons.push(loadedAddon);\n    instance.dispose = () => this._wrappedAddonDispose(loadedAddon);\n    instance.activate(<any>terminal);\n  }\n\n  private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {\n    if (loadedAddon.isDisposed) {\n      // Do nothing if already disposed\n      return;\n    }\n    let index = -1;\n    for (let i = 0; i < this._addons.length; i++) {\n      if (this._addons[i] === loadedAddon) {\n        index = i;\n        break;\n      }\n    }\n    if (index === -1) {\n      throw new Error('Could not dispose an addon that has not been loaded');\n    }\n    loadedAddon.isDisposed = true;\n    loadedAddon.dispose.apply(loadedAddon.instance);\n    this._addons.splice(index, 1);\n  }\n}\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/node_modules/xterm/package.json b/node_modules/xterm/package.json
new file mode 100644 (file)
index 0000000..1a629e7
--- /dev/null
@@ -0,0 +1,99 @@
+{
+  "name": "xterm",
+  "description": "Full xterm terminal, in your browser",
+  "version": "4.2.0",
+  "main": "lib/xterm.js",
+  "style": "css/xterm.css",
+  "types": "typings/xterm.d.ts",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/xtermjs/xterm.js.git"
+  },
+  "license": "MIT",
+  "scripts": {
+    "prepackage": "npm run build",
+    "package": "webpack",
+    "start": "node demo/start",
+    "lint": "tslint 'src/**/*.ts' 'addons/**/*.ts'",
+    "test": "npm run test-unit",
+    "posttest": "npm run lint",
+    "test-api": "mocha \"**/*.api.js\"",
+    "test-unit": "node ./bin/test.js",
+    "build": "tsc -b ./tsconfig.all.json",
+    "prepare": "npm run build",
+    "prepublishOnly": "npm run package",
+    "watch": "tsc -b -w ./tsconfig.all.json --preserveWatchOutput",
+    "benchmark": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json",
+    "benchmark-baseline": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --baseline out-test/benchmark/test/benchmark/*benchmark.js",
+    "benchmark-eval": "NODE_PATH=./out xterm-benchmark -r 5 -c test/benchmark/benchmark.json --eval out-test/benchmark/test/benchmark/*benchmark.js",
+    "clean": "rm -rf lib out addons/*/lib addons/*/out"
+  },
+  "devDependencies": {
+    "@types/chai": "^3.4.34",
+    "@types/glob": "^5.0.35",
+    "@types/jsdom": "11.0.1",
+    "@types/mocha": "^2.2.33",
+    "@types/node": "6.0.108",
+    "@types/puppeteer": "^1.12.4",
+    "@types/utf8": "^2.1.6",
+    "@types/webpack": "^4.4.11",
+    "@types/ws": "^6.0.1",
+    "chai": "3.5.0",
+    "express": "^4.17.1",
+    "express-ws": "^4.0.0",
+    "glob": "^7.0.5",
+    "jsdom": "^11.11.0",
+    "mocha": "^6.1.4",
+    "node-pty": "0.7.6",
+    "puppeteer": "^1.15.0",
+    "source-map-loader": "^0.2.4",
+    "ts-loader": "^6.0.4",
+    "tslint": "^5.18.0",
+    "tslint-consistent-codestyle": "^1.13.0",
+    "typescript": "3.6",
+    "utf8": "^3.0.0",
+    "webpack": "^4.35.3",
+    "webpack-cli": "^3.1.0",
+    "ws": "^7.0.0",
+    "xterm-benchmark": "^0.1.3"
+  },
+  "gitHead": "f30c38f7735c37dc13faed52e8423d71014d922c",
+  "bugs": {
+    "url": "https://github.com/xtermjs/xterm.js/issues"
+  },
+  "homepage": "https://github.com/xtermjs/xterm.js#readme",
+  "_id": "xterm@4.2.0",
+  "_npmVersion": "6.4.1",
+  "_nodeVersion": "8.16.2",
+  "_npmUser": {
+    "name": "tyriar",
+    "email": "tyriar@tyriar.com"
+  },
+  "dist": {
+    "integrity": "sha512-oNfLqt+LmghLPOt5UcskP5Km1fXpTBHsTZ99nxJKY2N0MNFXBKIVXUcNNhHCa74JGZFMGhLT58A/UN3HcPXSfg==",
+    "shasum": "b9980b2ae18c64ed31bcc95eace3bcecffebbbd9",
+    "tarball": "https://registry.npmjs.org/xterm/-/xterm-4.2.0.tgz",
+    "fileCount": 97,
+    "unpackedSize": 1815805,
+    "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdsvJCCRA9TVsSAnZWagAAx38P/RnG2mtxLM6oTPHg95Ee\nbqGn0x/Ja/q27lOgD+hL9q1kNvDDkDTI46LFNIo+ExFTluU6CDszD3trFelc\nZb4SNrptgpLmjBpSfzfs1TYu8Je1rDwgeemXRFyA+8gJd1vOZIn3reH9G81U\nVfpE70Zt4MFzzZ+pzyTWpbFionCnpfB9ml9/hRonnhlLn3WITZMzoCuojV+y\nBfFkP/scTZPiR6F3DVpAKPYaK4qWdqQm2Ht/CfpM3ik+hjjJRUEWp0qZhBS6\nE/CnyuRQtbNO8nwqIUNJU0V7kBP06JmjZ4KFxS833Pc1UJ2g900XhOQuu1Qj\nDj3Qu3Wb25pDH+fX4xFwQEo19A/DJPvznmPTF4YtUgDKX9Foi5Yqt8eiFdVP\nQxgZ+3QRva7XwCL45UG1s8fL2BBmFDSvGHXnBtjAOB/V1DqgA2xYYQ8XCcS1\nOcIgRXqusALMjw/eyJr28fqG8gTtvbU3w+DJc+OI/FTxIL/4hUYFmc/+L8S7\nrtxczBh8dOv6OSLfDVE9hkKnFQH1wAcKMfDwXIEbyPIJpry7jdzxXWdve2t7\nrw7wct6NIIygLW2rjjBiUSgAEFoJzfn+rGexw0Vh/ZiKHBdp84KOFyLmIity\nJmZ4kmW5EZbd+4XpiljlT+ISOExxkCAnFZSe7RYSP7l9ZxmvXMPwNee3Qow1\nT4Cl\r\n=mf2Q\r\n-----END PGP SIGNATURE-----\r\n"
+  },
+  "maintainers": [
+    {
+      "name": "paris",
+      "email": "pariskasidiaris@gmail.com"
+    },
+    {
+      "name": "tyriar",
+      "email": "tyriar@tyriar.com"
+    }
+  ],
+  "directories": {},
+  "_npmOperationalInternal": {
+    "host": "s3://npm-registry-packages",
+    "tmp": "tmp/xterm_4.2.0_1572008514012_0.1190934233728087"
+  },
+  "_hasShrinkwrap": false,
+  "_shasum": "b9980b2ae18c64ed31bcc95eace3bcecffebbbd9",
+  "_from": "xterm@",
+  "_resolved": "https://registry.npmjs.org/xterm/-/xterm-4.2.0.tgz"
+}
diff --git a/node_modules/xterm/src/AccessibilityManager.ts b/node_modules/xterm/src/AccessibilityManager.ts
new file mode 100644 (file)
index 0000000..75393ea
--- /dev/null
@@ -0,0 +1,297 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import * as Strings from './browser/LocalizableStrings';
+import { ITerminal } from './Types';
+import { IBuffer } from 'common/buffer/Types';
+import { isMac } from 'common/Platform';
+import { RenderDebouncer } from 'browser/RenderDebouncer';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { Disposable } from 'common/Lifecycle';
+import { ScreenDprMonitor } from 'browser/ScreenDprMonitor';
+import { IRenderService } from 'browser/services/Services';
+
+const MAX_ROWS_TO_READ = 20;
+
+const enum BoundaryPosition {
+  TOP,
+  BOTTOM
+}
+
+export class AccessibilityManager extends Disposable {
+  private _accessibilityTreeRoot: HTMLElement;
+  private _rowContainer: HTMLElement;
+  private _rowElements: HTMLElement[];
+  private _liveRegion: HTMLElement;
+  private _liveRegionLineCount: number = 0;
+
+  private _renderRowsDebouncer: RenderDebouncer;
+  private _screenDprMonitor: ScreenDprMonitor;
+
+  private _topBoundaryFocusListener: (e: FocusEvent) => void;
+  private _bottomBoundaryFocusListener: (e: FocusEvent) => void;
+
+  /**
+   * This queue has a character pushed to it for keys that are pressed, if the
+   * next character added to the terminal is equal to the key char then it is
+   * not announced (added to live region) because it has already been announced
+   * by the textarea event (which cannot be canceled). There are some race
+   * condition cases if there is typing while data is streaming, but this covers
+   * the main case of typing into the prompt and inputting the answer to a
+   * question (Y/N, etc.).
+   */
+  private _charsToConsume: string[] = [];
+
+  private _charsToAnnounce: string = '';
+
+  constructor(
+    private readonly _terminal: ITerminal,
+    private readonly _renderService: IRenderService
+  ) {
+    super();
+    this._accessibilityTreeRoot = document.createElement('div');
+    this._accessibilityTreeRoot.classList.add('xterm-accessibility');
+
+    this._rowContainer = document.createElement('div');
+    this._rowContainer.classList.add('xterm-accessibility-tree');
+    this._rowElements = [];
+    for (let i = 0; i < this._terminal.rows; i++) {
+      this._rowElements[i] = this._createAccessibilityTreeNode();
+      this._rowContainer.appendChild(this._rowElements[i]);
+    }
+
+    this._topBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.TOP);
+    this._bottomBoundaryFocusListener = e => this._onBoundaryFocus(e, BoundaryPosition.BOTTOM);
+    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);
+    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
+
+    this._refreshRowsDimensions();
+    this._accessibilityTreeRoot.appendChild(this._rowContainer);
+
+    this._renderRowsDebouncer = new RenderDebouncer(this._renderRows.bind(this));
+    this._refreshRows();
+
+    this._liveRegion = document.createElement('div');
+    this._liveRegion.classList.add('live-region');
+    this._liveRegion.setAttribute('aria-live', 'assertive');
+    this._accessibilityTreeRoot.appendChild(this._liveRegion);
+
+    this._terminal.element.insertAdjacentElement('afterbegin', this._accessibilityTreeRoot);
+
+    this.register(this._renderRowsDebouncer);
+    this.register(this._terminal.onResize(e => this._onResize(e.rows)));
+    this.register(this._terminal.onRender(e => this._refreshRows(e.start, e.end)));
+    this.register(this._terminal.onScroll(() => this._refreshRows()));
+    // Line feed is an issue as the prompt won't be read out after a command is run
+    this.register(this._terminal.onA11yChar(char => this._onChar(char)));
+    this.register(this._terminal.onLineFeed(() => this._onChar('\n')));
+    this.register(this._terminal.onA11yTab(spaceCount => this._onTab(spaceCount)));
+    this.register(this._terminal.onKey(e => this._onKey(e.key)));
+    this.register(this._terminal.onBlur(() => this._clearLiveRegion()));
+    this.register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions()));
+
+    this._screenDprMonitor = new ScreenDprMonitor();
+    this.register(this._screenDprMonitor);
+    this._screenDprMonitor.setListener(() => this._refreshRowsDimensions());
+    // This shouldn't be needed on modern browsers but is present in case the
+    // media query that drives the ScreenDprMonitor isn't supported
+    this.register(addDisposableDomListener(window, 'resize', () => this._refreshRowsDimensions()));
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this._terminal.element.removeChild(this._accessibilityTreeRoot);
+    this._rowElements.length = 0;
+  }
+
+  private _onBoundaryFocus(e: FocusEvent, position: BoundaryPosition): void {
+    const boundaryElement = <HTMLElement>e.target;
+    const beforeBoundaryElement = this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2];
+
+    // Don't scroll if the buffer top has reached the end in that direction
+    const posInSet = boundaryElement.getAttribute('aria-posinset');
+    const lastRowPos = position === BoundaryPosition.TOP ? '1' : `${this._terminal.buffer.lines.length}`;
+    if (posInSet === lastRowPos) {
+      return;
+    }
+
+    // Don't scroll when the last focused item was not the second row (focus is going the other
+    // direction)
+    if (e.relatedTarget !== beforeBoundaryElement) {
+      return;
+    }
+
+    // Remove old boundary element from array
+    let topBoundaryElement: HTMLElement;
+    let bottomBoundaryElement: HTMLElement;
+    if (position === BoundaryPosition.TOP) {
+      topBoundaryElement = boundaryElement;
+      bottomBoundaryElement = this._rowElements.pop()!;
+      this._rowContainer.removeChild(bottomBoundaryElement);
+    } else {
+      topBoundaryElement = this._rowElements.shift()!;
+      bottomBoundaryElement = boundaryElement;
+      this._rowContainer.removeChild(topBoundaryElement);
+    }
+
+    // Remove listeners from old boundary elements
+    topBoundaryElement.removeEventListener('focus', this._topBoundaryFocusListener);
+    bottomBoundaryElement.removeEventListener('focus', this._bottomBoundaryFocusListener);
+
+    // Add new element to array/DOM
+    if (position === BoundaryPosition.TOP) {
+      const newElement = this._createAccessibilityTreeNode();
+      this._rowElements.unshift(newElement);
+      this._rowContainer.insertAdjacentElement('afterbegin', newElement);
+    } else {
+      const newElement = this._createAccessibilityTreeNode();
+      this._rowElements.push(newElement);
+      this._rowContainer.appendChild(newElement);
+    }
+
+    // Add listeners to new boundary elements
+    this._rowElements[0].addEventListener('focus', this._topBoundaryFocusListener);
+    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
+
+    // Scroll up
+    this._terminal.scrollLines(position === BoundaryPosition.TOP ? -1 : 1);
+
+    // Focus new boundary before element
+    this._rowElements[position === BoundaryPosition.TOP ? 1 : this._rowElements.length - 2].focus();
+
+    // Prevent the standard behavior
+    e.preventDefault();
+    e.stopImmediatePropagation();
+  }
+
+  private _onResize(rows: number): void {
+    // Remove bottom boundary listener
+    this._rowElements[this._rowElements.length - 1].removeEventListener('focus', this._bottomBoundaryFocusListener);
+
+    // Grow rows as required
+    for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) {
+      this._rowElements[i] = this._createAccessibilityTreeNode();
+      this._rowContainer.appendChild(this._rowElements[i]);
+    }
+    // Shrink rows as required
+    while (this._rowElements.length > rows) {
+      this._rowContainer.removeChild(this._rowElements.pop()!);
+    }
+
+    // Add bottom boundary listener
+    this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener);
+
+    this._refreshRowsDimensions();
+  }
+
+  private _createAccessibilityTreeNode(): HTMLElement {
+    const element = document.createElement('div');
+    element.setAttribute('role', 'listitem');
+    element.tabIndex = -1;
+    this._refreshRowDimensions(element);
+    return element;
+  }
+
+  private _onTab(spaceCount: number): void {
+    for (let i = 0; i < spaceCount; i++) {
+      this._onChar(' ');
+    }
+  }
+
+  private _onChar(char: string): void {
+    if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) {
+      if (this._charsToConsume.length > 0) {
+        // Have the screen reader ignore the char if it was just input
+        const shiftedChar = this._charsToConsume.shift();
+        if (shiftedChar !== char) {
+          this._charsToAnnounce += char;
+        }
+      } else {
+        this._charsToAnnounce += char;
+      }
+
+      if (char === '\n') {
+        this._liveRegionLineCount++;
+        if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) {
+          this._liveRegion.textContent += Strings.tooMuchOutput;
+        }
+      }
+
+      // Only detach/attach on mac as otherwise messages can go unaccounced
+      if (isMac) {
+        if (this._liveRegion.textContent && this._liveRegion.textContent.length > 0 && !this._liveRegion.parentNode) {
+          setTimeout(() => {
+            this._accessibilityTreeRoot.appendChild(this._liveRegion);
+          }, 0);
+        }
+      }
+    }
+  }
+
+  private _clearLiveRegion(): void {
+    this._liveRegion.textContent = '';
+    this._liveRegionLineCount = 0;
+
+    // Only detach/attach on mac as otherwise messages can go unaccounced
+    if (isMac) {
+      if (this._liveRegion.parentNode) {
+        this._accessibilityTreeRoot.removeChild(this._liveRegion);
+      }
+    }
+  }
+
+  private _onKey(keyChar: string): void {
+    this._clearLiveRegion();
+    this._charsToConsume.push(keyChar);
+  }
+
+  private _refreshRows(start?: number, end?: number): void {
+    this._renderRowsDebouncer.refresh(start, end, this._terminal.rows);
+  }
+
+  private _renderRows(start: number, end: number): void {
+    const buffer: IBuffer = this._terminal.buffer;
+    const setSize = buffer.lines.length.toString();
+    for (let i = start; i <= end; i++) {
+      const lineData = buffer.translateBufferLineToString(buffer.ydisp + i, true);
+      const posInSet = (buffer.ydisp + i + 1).toString();
+      const element = this._rowElements[i];
+      if (element) {
+        if (lineData.length === 0) {
+          element.innerHTML = '&nbsp;';
+        } else {
+          element.textContent = lineData;
+        }
+        element.setAttribute('aria-posinset', posInSet);
+        element.setAttribute('aria-setsize', setSize);
+      }
+    }
+    this._announceCharacters();
+  }
+
+  private _refreshRowsDimensions(): void {
+    if (!this._renderService.dimensions.actualCellHeight) {
+      return;
+    }
+    if (this._rowElements.length !== this._terminal.rows) {
+      this._onResize(this._terminal.rows);
+    }
+    for (let i = 0; i < this._terminal.rows; i++) {
+      this._refreshRowDimensions(this._rowElements[i]);
+    }
+  }
+
+  private _refreshRowDimensions(element: HTMLElement): void {
+    element.style.height = `${this._renderService.dimensions.actualCellHeight}px`;
+  }
+
+  private _announceCharacters(): void {
+    if (this._charsToAnnounce.length === 0) {
+      return;
+    }
+    this._liveRegion.textContent += this._charsToAnnounce;
+    this._charsToAnnounce = '';
+  }
+}
diff --git a/node_modules/xterm/src/InputHandler.ts b/node_modules/xterm/src/InputHandler.ts
new file mode 100644 (file)
index 0000000..7b6ea1f
--- /dev/null
@@ -0,0 +1,2242 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * @license MIT
+ */
+
+import { IInputHandler, IInputHandlingTerminal } from './Types';
+import { C0, C1 } from 'common/data/EscapeSequences';
+import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';
+import { wcwidth } from 'common/CharWidth';
+import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';
+import { Disposable } from 'common/Lifecycle';
+import { concat } from 'common/TypedArrayUtils';
+import { StringToUtf32, stringFromCodePoint, utf32ToString, Utf8ToUtf32 } from 'common/input/TextDecoder';
+import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';
+import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { IAttributeData, IDisposable } from 'common/Types';
+import { ICoreService, IBufferService, IOptionsService, ILogService, IDirtyRowService, ICoreMouseService } from 'common/services/Services';
+import { OscHandler } from 'common/parser/OscParser';
+import { DcsHandler } from 'common/parser/DcsParser';
+
+/**
+ * Map collect to glevel. Used in `selectCharset`.
+ */
+const GLEVEL: {[key: string]: number} = {'(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2};
+
+/**
+ * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.
+ */
+const MAX_PARSEBUFFER_LENGTH = 131072;
+
+
+/**
+ * DCS subparser implementations
+ */
+
+/**
+ * DCS $ q Pt ST
+ *   DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)
+ *   Request Status String (DECRQSS), VT420 and up.
+ *   Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)
+ */
+class DECRQSS implements IDcsHandler {
+  private _data: Uint32Array = new Uint32Array(0);
+
+  constructor(
+    private _bufferService: IBufferService,
+    private _coreService: ICoreService,
+    private _logService: ILogService,
+    private _optionsService: IOptionsService
+  ) { }
+
+  hook(params: IParams): void {
+    this._data = new Uint32Array(0);
+  }
+
+  put(data: Uint32Array, start: number, end: number): void {
+    this._data = concat(this._data, data.subarray(start, end));
+  }
+
+  unhook(success: boolean): void {
+    if (!success) {
+      this._data = new Uint32Array(0);
+      return;
+    }
+    const data = utf32ToString(this._data);
+    this._data = new Uint32Array(0);
+    switch (data) {
+      // valid: DCS 1 $ r Pt ST (xterm)
+      case '"q': // DECSCA
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0"q${C0.ESC}\\`);
+      case '"p': // DECSCL
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r61"p${C0.ESC}\\`);
+      case 'r': // DECSTBM
+        const pt = '' + (this._bufferService.buffer.scrollTop + 1) +
+                ';' + (this._bufferService.buffer.scrollBottom + 1) + 'r';
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${pt}${C0.ESC}\\`);
+      case 'm': // SGR
+        // TODO: report real settings instead of 0m
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r0m${C0.ESC}\\`);
+      case ' q': // DECSCUSR
+        const STYLES: {[key: string]: number} = {'block': 2, 'underline': 4, 'bar': 6};
+        let style = STYLES[this._optionsService.options.cursorStyle];
+        style -= this._optionsService.options.cursorBlink ? 1 : 0;
+        return this._coreService.triggerDataEvent(`${C0.ESC}P1$r${style} q${C0.ESC}\\`);
+      default:
+        // invalid: DCS 0 $ r Pt ST (xterm)
+        this._logService.debug('Unknown DCS $q %s', data);
+        this._coreService.triggerDataEvent(`${C0.ESC}P0$r${C0.ESC}\\`);
+    }
+  }
+}
+
+/**
+ * DCS Ps; Ps| Pt ST
+ *   DECUDK (https://vt100.net/docs/vt510-rm/DECUDK.html)
+ *   not supported
+ */
+
+/**
+ * DCS + q Pt ST (xterm)
+ *   Request Terminfo String
+ *   not implemented
+ */
+
+/**
+ * DCS + p Pt ST (xterm)
+ *   Set Terminfo Data
+ *   not supported
+ */
+
+
+
+/**
+ * The terminal's standard implementation of IInputHandler, this handles all
+ * input from the Parser.
+ *
+ * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand
+ * each function's header comment.
+ */
+export class InputHandler extends Disposable implements IInputHandler {
+  private _parseBuffer: Uint32Array = new Uint32Array(4096);
+  private _stringDecoder: StringToUtf32 = new StringToUtf32();
+  private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();
+  private _workCell: CellData = new CellData();
+
+  private _onCursorMove = new EventEmitter<void>();
+  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }
+  private _onLineFeed = new EventEmitter<void>();
+  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }
+  private _onScroll = new EventEmitter<number>();
+  public get onScroll(): IEvent<number> { return this._onScroll.event; }
+
+  constructor(
+    protected _terminal: IInputHandlingTerminal,
+    private readonly _bufferService: IBufferService,
+    private readonly _coreService: ICoreService,
+    private readonly _dirtyRowService: IDirtyRowService,
+    private readonly _logService: ILogService,
+    private readonly _optionsService: IOptionsService,
+    private readonly _coreMouseService: ICoreMouseService,
+    private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser())
+  {
+    super();
+
+    this.register(this._parser);
+
+    /**
+     * custom fallback handlers
+     */
+    this._parser.setCsiHandlerFallback((ident, params) => {
+      this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });
+    });
+    this._parser.setEscHandlerFallback(ident => {
+      this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });
+    });
+    this._parser.setExecuteHandlerFallback(code => {
+      this._logService.debug('Unknown EXECUTE code: ', { code });
+    });
+    this._parser.setOscHandlerFallback((identifier, action, data) => {
+      this._logService.debug('Unknown OSC code: ', { identifier, action, data });
+    });
+    this._parser.setDcsHandlerFallback((ident, action, payload) => {
+      if (action === 'HOOK') {
+        payload = payload.toArray();
+      }
+      this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });
+    });
+
+    /**
+     * print handler
+     */
+    this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));
+
+    /**
+     * CSI handler
+     */
+    this._parser.setCsiHandler({final: '@'}, params => this.insertChars(params));
+    this._parser.setCsiHandler({intermediates: ' ', final: '@'}, params => this.scrollLeft(params));
+    this._parser.setCsiHandler({final: 'A'}, params => this.cursorUp(params));
+    this._parser.setCsiHandler({intermediates: ' ', final: 'A'}, params => this.scrollRight(params));
+    this._parser.setCsiHandler({final: 'B'}, params => this.cursorDown(params));
+    this._parser.setCsiHandler({final: 'C'}, params => this.cursorForward(params));
+    this._parser.setCsiHandler({final: 'D'}, params => this.cursorBackward(params));
+    this._parser.setCsiHandler({final: 'E'}, params => this.cursorNextLine(params));
+    this._parser.setCsiHandler({final: 'F'}, params => this.cursorPrecedingLine(params));
+    this._parser.setCsiHandler({final: 'G'}, params => this.cursorCharAbsolute(params));
+    this._parser.setCsiHandler({final: 'H'}, params => this.cursorPosition(params));
+    this._parser.setCsiHandler({final: 'I'}, params => this.cursorForwardTab(params));
+    this._parser.setCsiHandler({final: 'J'}, params => this.eraseInDisplay(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'J'}, params => this.eraseInDisplay(params));
+    this._parser.setCsiHandler({final: 'K'}, params => this.eraseInLine(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'K'}, params => this.eraseInLine(params));
+    this._parser.setCsiHandler({final: 'L'}, params => this.insertLines(params));
+    this._parser.setCsiHandler({final: 'M'}, params => this.deleteLines(params));
+    this._parser.setCsiHandler({final: 'P'}, params => this.deleteChars(params));
+    this._parser.setCsiHandler({final: 'S'}, params => this.scrollUp(params));
+    this._parser.setCsiHandler({final: 'T'}, params => this.scrollDown(params));
+    this._parser.setCsiHandler({final: 'X'}, params => this.eraseChars(params));
+    this._parser.setCsiHandler({final: 'Z'}, params => this.cursorBackwardTab(params));
+    this._parser.setCsiHandler({final: '`'}, params => this.charPosAbsolute(params));
+    this._parser.setCsiHandler({final: 'a'}, params => this.hPositionRelative(params));
+    this._parser.setCsiHandler({final: 'b'}, params => this.repeatPrecedingCharacter(params));
+    this._parser.setCsiHandler({final: 'c'}, params => this.sendDeviceAttributesPrimary(params));
+    this._parser.setCsiHandler({prefix: '>', final: 'c'}, params => this.sendDeviceAttributesSecondary(params));
+    this._parser.setCsiHandler({final: 'd'}, params => this.linePosAbsolute(params));
+    this._parser.setCsiHandler({final: 'e'}, params => this.vPositionRelative(params));
+    this._parser.setCsiHandler({final: 'f'}, params => this.hVPosition(params));
+    this._parser.setCsiHandler({final: 'g'}, params => this.tabClear(params));
+    this._parser.setCsiHandler({final: 'h'}, params => this.setMode(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'h'}, params => this.setModePrivate(params));
+    this._parser.setCsiHandler({final: 'l'}, params => this.resetMode(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'l'}, params => this.resetModePrivate(params));
+    this._parser.setCsiHandler({final: 'm'}, params => this.charAttributes(params));
+    this._parser.setCsiHandler({final: 'n'}, params => this.deviceStatus(params));
+    this._parser.setCsiHandler({prefix: '?', final: 'n'}, params => this.deviceStatusPrivate(params));
+    this._parser.setCsiHandler({intermediates: '!', final: 'p'}, params => this.softReset(params));
+    this._parser.setCsiHandler({intermediates: ' ', final: 'q'}, params => this.setCursorStyle(params));
+    this._parser.setCsiHandler({final: 'r'}, params => this.setScrollRegion(params));
+    this._parser.setCsiHandler({final: 's'}, params => this.saveCursor(params));
+    this._parser.setCsiHandler({final: 'u'}, params => this.restoreCursor(params));
+    this._parser.setCsiHandler({intermediates: '\'', final: '}'}, params => this.insertColumns(params));
+    this._parser.setCsiHandler({intermediates: '\'', final: '~'}, params => this.deleteColumns(params));
+
+    /**
+     * execute handler
+     */
+    this._parser.setExecuteHandler(C0.BEL, () => this.bell());
+    this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());
+    this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());
+    this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());
+    this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());
+    this._parser.setExecuteHandler(C0.BS, () => this.backspace());
+    this._parser.setExecuteHandler(C0.HT, () => this.tab());
+    this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());
+    this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());
+    // FIXME:   What do to with missing? Old code just added those to print.
+
+    this._parser.setExecuteHandler(C1.IND, () => this.index());
+    this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());
+    this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());
+
+    /**
+     * OSC handler
+     */
+    //   0 - icon name + title
+    this._parser.setOscHandler(0, new OscHandler((data: string) => this.setTitle(data)));
+    //   1 - icon name
+    //   2 - title
+    this._parser.setOscHandler(2, new OscHandler((data: string) => this.setTitle(data)));
+    //   3 - set property X in the form "prop=value"
+    //   4 - Change Color Number
+    //   5 - Change Special Color Number
+    //   6 - Enable/disable Special Color Number c
+    //   7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)
+    //  10 - Change VT100 text foreground color to Pt.
+    //  11 - Change VT100 text background color to Pt.
+    //  12 - Change text cursor color to Pt.
+    //  13 - Change mouse foreground color to Pt.
+    //  14 - Change mouse background color to Pt.
+    //  15 - Change Tektronix foreground color to Pt.
+    //  16 - Change Tektronix background color to Pt.
+    //  17 - Change highlight background color to Pt.
+    //  18 - Change Tektronix cursor color to Pt.
+    //  19 - Change highlight foreground color to Pt.
+    //  46 - Change Log File to Pt.
+    //  50 - Set Font to Pt.
+    //  51 - reserved for Emacs shell.
+    //  52 - Manipulate Selection Data.
+    // 104 ; c - Reset Color Number c.
+    // 105 ; c - Reset Special Color Number c.
+    // 106 ; c; f - Enable/disable Special Color Number c.
+    // 110 - Reset VT100 text foreground color.
+    // 111 - Reset VT100 text background color.
+    // 112 - Reset text cursor color.
+    // 113 - Reset mouse foreground color.
+    // 114 - Reset mouse background color.
+    // 115 - Reset Tektronix foreground color.
+    // 116 - Reset Tektronix background color.
+    // 117 - Reset highlight color.
+    // 118 - Reset Tektronix cursor color.
+    // 119 - Reset highlight foreground color.
+
+    /**
+     * ESC handlers
+     */
+    this._parser.setEscHandler({final: '7'}, () => this.saveCursor());
+    this._parser.setEscHandler({final: '8'}, () => this.restoreCursor());
+    this._parser.setEscHandler({final: 'D'}, () => this.index());
+    this._parser.setEscHandler({final: 'E'}, () => this.nextLine());
+    this._parser.setEscHandler({final: 'H'}, () => this.tabSet());
+    this._parser.setEscHandler({final: 'M'}, () => this.reverseIndex());
+    this._parser.setEscHandler({final: '='}, () => this.keypadApplicationMode());
+    this._parser.setEscHandler({final: '>'}, () => this.keypadNumericMode());
+    this._parser.setEscHandler({final: 'c'}, () => this.reset());
+    this._parser.setEscHandler({final: 'n'}, () => this.setgLevel(2));
+    this._parser.setEscHandler({final: 'o'}, () => this.setgLevel(3));
+    this._parser.setEscHandler({final: '|'}, () => this.setgLevel(3));
+    this._parser.setEscHandler({final: '}'}, () => this.setgLevel(2));
+    this._parser.setEscHandler({final: '~'}, () => this.setgLevel(1));
+    this._parser.setEscHandler({intermediates: '%', final: '@'}, () => this.selectDefaultCharset());
+    this._parser.setEscHandler({intermediates: '%', final: 'G'}, () => this.selectDefaultCharset());
+    for (const flag in CHARSETS) {
+      this._parser.setEscHandler({intermediates: '(', final: flag}, () => this.selectCharset('(' + flag));
+      this._parser.setEscHandler({intermediates: ')', final: flag}, () => this.selectCharset(')' + flag));
+      this._parser.setEscHandler({intermediates: '*', final: flag}, () => this.selectCharset('*' + flag));
+      this._parser.setEscHandler({intermediates: '+', final: flag}, () => this.selectCharset('+' + flag));
+      this._parser.setEscHandler({intermediates: '-', final: flag}, () => this.selectCharset('-' + flag));
+      this._parser.setEscHandler({intermediates: '.', final: flag}, () => this.selectCharset('.' + flag));
+      this._parser.setEscHandler({intermediates: '/', final: flag}, () => this.selectCharset('/' + flag)); // TODO: supported?
+    }
+    this._parser.setEscHandler({intermediates: '#', final: '8'}, () => this.screenAlignmentPattern());
+
+    /**
+     * error handler
+     */
+    this._parser.setErrorHandler((state: IParsingState) => {
+      this._logService.error('Parsing error: ', state);
+      return state;
+    });
+
+    /**
+     * DCS handler
+     */
+    this._parser.setDcsHandler({intermediates: '$', final: 'q'}, new DECRQSS(this._bufferService, this._coreService, this._logService, this._optionsService));
+  }
+
+  public dispose(): void {
+    super.dispose();
+  }
+
+  public parse(data: string | Uint8Array): void {
+    let buffer = this._bufferService.buffer;
+    const cursorStartX = buffer.x;
+    const cursorStartY = buffer.y;
+
+    this._logService.debug('parsing data', data);
+
+    // resize input buffer if needed
+    if (this._parseBuffer.length < data.length) {
+      if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {
+        this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));
+      }
+    }
+
+    // process big data in smaller chunks
+    if (data.length > MAX_PARSEBUFFER_LENGTH) {
+      for (let i = 0; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {
+        const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;
+        const len = (typeof data === 'string')
+          ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)
+          : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);
+        this._parser.parse(this._parseBuffer, len);
+      }
+    } else {
+      const len = (typeof data === 'string')
+        ? this._stringDecoder.decode(data, this._parseBuffer)
+        : this._utf8Decoder.decode(data, this._parseBuffer);
+      this._parser.parse(this._parseBuffer, len);
+    }
+
+    buffer = this._bufferService.buffer;
+    if (buffer.x !== cursorStartX || buffer.y !== cursorStartY) {
+      this._onCursorMove.fire();
+    }
+    this._terminal.refresh(this._dirtyRowService.start, this._dirtyRowService.end);
+  }
+
+  public print(data: Uint32Array, start: number, end: number): void {
+    let code: number;
+    let chWidth: number;
+    const buffer = this._bufferService.buffer;
+    const charset = this._terminal.charset;
+    const screenReaderMode = this._optionsService.options.screenReaderMode;
+    const cols = this._bufferService.cols;
+    const wraparoundMode = this._terminal.wraparoundMode;
+    const insertMode = this._terminal.insertMode;
+    const curAttr = this._terminal.curAttrData;
+    let bufferRow = buffer.lines.get(buffer.y + buffer.ybase);
+
+    this._dirtyRowService.markDirty(buffer.y);
+    for (let pos = start; pos < end; ++pos) {
+      code = data[pos];
+
+      // calculate print space
+      // expensive call, therefore we save width in line buffer
+      chWidth = wcwidth(code);
+
+      // get charset replacement character
+      // charset is only defined for ASCII, therefore we only
+      // search for an replacement char if code < 127
+      if (code < 127 && charset) {
+        const ch = charset[String.fromCharCode(code)];
+        if (ch) {
+          code = ch.charCodeAt(0);
+        }
+      }
+
+      if (screenReaderMode) {
+        this._terminal.onA11yCharEmitter.fire(stringFromCodePoint(code));
+      }
+
+      // insert combining char at last cursor position
+      // FIXME: needs handling after cursor jumps
+      // buffer.x should never be 0 for a combining char
+      // since they always follow a cell consuming char
+      // therefore we can test for buffer.x to avoid overflow left
+      if (!chWidth && buffer.x) {
+        if (!bufferRow.getWidth(buffer.x - 1)) {
+          // found empty cell after fullwidth, need to go 2 cells back
+          // it is save to step 2 cells back here
+          // since an empty cell is only set by fullwidth chars
+          bufferRow.addCodepointToCell(buffer.x - 2, code);
+        } else {
+          bufferRow.addCodepointToCell(buffer.x - 1, code);
+        }
+        continue;
+      }
+
+      // goto next line if ch would overflow
+      // TODO: needs a global min terminal width of 2
+      // FIXME: additionally ensure chWidth fits into a line
+      //   -->  maybe forbid cols<xy at higher level as it would
+      //        introduce a bad runtime penalty here
+      if (buffer.x + chWidth - 1 >= cols) {
+        // autowrap - DECAWM
+        // automatically wraps to the beginning of the next line
+        if (wraparoundMode) {
+          buffer.x = 0;
+          buffer.y++;
+          if (buffer.y === buffer.scrollBottom + 1) {
+            buffer.y--;
+            this._terminal.scroll(true);
+          } else {
+            if (buffer.y >= this._bufferService.rows) {
+              buffer.y = this._bufferService.rows - 1;
+            }
+            // The line already exists (eg. the initial viewport), mark it as a
+            // wrapped line
+            buffer.lines.get(buffer.y).isWrapped = true;
+          }
+          // row changed, get it again
+          bufferRow = buffer.lines.get(buffer.y + buffer.ybase);
+        } else {
+          buffer.x = cols - 1;
+          if (chWidth === 2) {
+            // FIXME: check for xterm behavior
+            // What to do here? We got a wide char that does not fit into last cell
+            continue;
+          }
+        }
+      }
+
+      // insert mode: move characters to right
+      if (insertMode) {
+        // right shift cells according to the width
+        bufferRow.insertCells(buffer.x, chWidth, buffer.getNullCell(curAttr));
+        // test last cell - since the last cell has only room for
+        // a halfwidth char any fullwidth shifted there is lost
+        // and will be set to empty cell
+        if (bufferRow.getWidth(cols - 1) === 2) {
+          bufferRow.setCellFromCodePoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr.fg, curAttr.bg);
+        }
+      }
+
+      // write current char to buffer and advance cursor
+      bufferRow.setCellFromCodePoint(buffer.x++, code, chWidth, curAttr.fg, curAttr.bg);
+
+      // fullwidth char - also set next cell to placeholder stub and advance cursor
+      // for graphemes bigger than fullwidth we can simply loop to zero
+      // we already made sure above, that buffer.x + chWidth will not overflow right
+      if (chWidth > 0) {
+        while (--chWidth) {
+          // other than a regular empty cell a cell following a wide char has no width
+          bufferRow.setCellFromCodePoint(buffer.x++, 0, 0, curAttr.fg, curAttr.bg);
+        }
+      }
+    }
+    // store last char in Parser.precedingCodepoint for REP to work correctly
+    // This needs to check whether:
+    //  - fullwidth + surrogates: reset
+    //  - combining: only base char gets carried on (bug in xterm?)
+    if (end) {
+      bufferRow.loadCell(buffer.x - 1, this._workCell);
+      if (this._workCell.getWidth() === 2 || this._workCell.getCode() > 0xFFFF) {
+        this._parser.precedingCodepoint = 0;
+      } else if (this._workCell.isCombined()) {
+        this._parser.precedingCodepoint = this._workCell.getChars().charCodeAt(0);
+      } else {
+        this._parser.precedingCodepoint = this._workCell.content;
+      }
+    }
+    this._dirtyRowService.markDirty(buffer.y);
+  }
+
+  /**
+   * Forward addCsiHandler from parser.
+   */
+  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {
+    return this._parser.addCsiHandler(id, callback);
+  }
+
+  /**
+   * Forward addDcsHandler from parser.
+   */
+  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {
+    return this._parser.addDcsHandler(id, new DcsHandler(callback));
+  }
+
+  /**
+   * Forward addEscHandler from parser.
+   */
+  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {
+    return this._parser.addEscHandler(id, callback);
+  }
+
+  /**
+   * Forward addOscHandler from parser.
+   */
+  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {
+    return this._parser.addOscHandler(ident, new OscHandler(callback));
+  }
+
+  /**
+   * BEL
+   * Bell (Ctrl-G).
+   */
+  public bell(): void {
+    this._terminal.bell();
+  }
+
+  /**
+   * LF
+   * Line Feed or New Line (NL).  (LF  is Ctrl-J).
+   */
+  public lineFeed(): void {
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    if (this._optionsService.options.convertEol) {
+      buffer.x = 0;
+    }
+    buffer.y++;
+    if (buffer.y === buffer.scrollBottom + 1) {
+      buffer.y--;
+      this._terminal.scroll();
+    } else if (buffer.y >= this._bufferService.rows) {
+      buffer.y = this._bufferService.rows - 1;
+    }
+    // If the end of the line is hit, prevent this action from wrapping around to the next line.
+    if (buffer.x >= this._bufferService.cols) {
+      buffer.x--;
+    }
+
+    this._onLineFeed.fire();
+  }
+
+  /**
+   * CR
+   * Carriage Return (Ctrl-M).
+   */
+  public carriageReturn(): void {
+    this._bufferService.buffer.x = 0;
+  }
+
+  /**
+   * BS
+   * Backspace (Ctrl-H).
+   */
+  public backspace(): void {
+    this._restrictCursor();
+    if (this._bufferService.buffer.x > 0) {
+      this._bufferService.buffer.x--;
+    }
+  }
+
+  /**
+   * TAB
+   * Horizontal Tab (HT) (Ctrl-I).
+   */
+  public tab(): void {
+    if (this._bufferService.buffer.x >= this._bufferService.cols) {
+      return;
+    }
+    const originalX = this._bufferService.buffer.x;
+    this._bufferService.buffer.x = this._bufferService.buffer.nextStop();
+    if (this._optionsService.options.screenReaderMode) {
+      this._terminal.onA11yTabEmitter.fire(this._bufferService.buffer.x - originalX);
+    }
+  }
+
+  /**
+   * SO
+   * Shift Out (Ctrl-N) -> Switch to Alternate Character Set.  This invokes the
+   * G1 character set.
+   */
+  public shiftOut(): void {
+    this._terminal.setgLevel(1);
+  }
+
+  /**
+   * SI
+   * Shift In (Ctrl-O) -> Switch to Standard Character Set.  This invokes the G0
+   * character set (the default).
+   */
+  public shiftIn(): void {
+    this._terminal.setgLevel(0);
+  }
+
+  /**
+   * Restrict cursor to viewport size / scroll margin (origin mode).
+   */
+  private _restrictCursor(): void {
+    this._bufferService.buffer.x = Math.min(this._bufferService.cols - 1, Math.max(0, this._bufferService.buffer.x));
+    this._bufferService.buffer.y = this._terminal.originMode
+      ? Math.min(this._bufferService.buffer.scrollBottom, Math.max(this._bufferService.buffer.scrollTop, this._bufferService.buffer.y))
+      : Math.min(this._bufferService.rows - 1, Math.max(0, this._bufferService.buffer.y));
+  }
+
+  /**
+   * Set absolute cursor position.
+   */
+  private _setCursor(x: number, y: number): void {
+    if (this._terminal.originMode) {
+      this._bufferService.buffer.x = x;
+      this._bufferService.buffer.y = this._bufferService.buffer.scrollTop + y;
+    } else {
+      this._bufferService.buffer.x = x;
+      this._bufferService.buffer.y = y;
+    }
+    this._restrictCursor();
+  }
+
+  /**
+   * Set relative cursor position.
+   */
+  private _moveCursor(x: number, y: number): void {
+    // for relative changes we have to make sure we are within 0 .. cols/rows - 1
+    // before calculating the new position
+    this._restrictCursor();
+    this._setCursor(this._bufferService.buffer.x + x, this._bufferService.buffer.y + y);
+  }
+
+  /**
+   * CSI Ps A
+   * Cursor Up Ps Times (default = 1) (CUU).
+   */
+  public cursorUp(params: IParams): void {
+    // stop at scrollTop
+    const diffToTop = this._bufferService.buffer.y - this._bufferService.buffer.scrollTop;
+    if (diffToTop >= 0) {
+      this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));
+    } else {
+      this._moveCursor(0, -(params.params[0] || 1));
+    }
+  }
+
+  /**
+   * CSI Ps B
+   * Cursor Down Ps Times (default = 1) (CUD).
+   */
+  public cursorDown(params: IParams): void {
+    // stop at scrollBottom
+    const diffToBottom = this._bufferService.buffer.scrollBottom - this._bufferService.buffer.y;
+    if (diffToBottom >= 0) {
+      this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));
+    } else {
+      this._moveCursor(0, params.params[0] || 1);
+    }
+  }
+
+  /**
+   * CSI Ps C
+   * Cursor Forward Ps Times (default = 1) (CUF).
+   */
+  public cursorForward(params: IParams): void {
+    this._moveCursor(params.params[0] || 1, 0);
+  }
+
+  /**
+   * CSI Ps D
+   * Cursor Backward Ps Times (default = 1) (CUB).
+   */
+  public cursorBackward(params: IParams): void {
+    this._moveCursor(-(params.params[0] || 1), 0);
+  }
+
+  /**
+   * CSI Ps E
+   * Cursor Next Line Ps Times (default = 1) (CNL).
+   * Other than cursorDown (CUD) also set the cursor to first column.
+   */
+  public cursorNextLine(params: IParams): void {
+    this.cursorDown(params);
+    this._bufferService.buffer.x = 0;
+  }
+
+  /**
+   * CSI Ps F
+   * Cursor Previous Line Ps Times (default = 1) (CPL).
+   * Other than cursorUp (CUU) also set the cursor to first column.
+   */
+  public cursorPrecedingLine(params: IParams): void {
+    this.cursorUp(params);
+    this._bufferService.buffer.x = 0;
+  }
+
+  /**
+   * CSI Ps G
+   * Cursor Character Absolute  [column] (default = [row,1]) (CHA).
+   */
+  public cursorCharAbsolute(params: IParams): void {
+    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);
+  }
+
+  /**
+   * CSI Ps ; Ps H
+   * Cursor Position [row;column] (default = [1,1]) (CUP).
+   */
+  public cursorPosition(params: IParams): void {
+    this._setCursor(
+      // col
+      (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,
+      // row
+      (params.params[0] || 1) - 1);
+  }
+
+  /**
+   * CSI Pm `  Character Position Absolute
+   *   [column] (default = [row,1]) (HPA).
+   * Currently same functionality as CHA.
+   */
+  public charPosAbsolute(params: IParams): void {
+    this._setCursor((params.params[0] || 1) - 1, this._bufferService.buffer.y);
+  }
+
+  /**
+   * CSI Pm a  Character Position Relative
+   *   [columns] (default = [row,col+1]) (HPR)
+   * Currently same functionality as CUF.
+   */
+  public hPositionRelative(params: IParams): void {
+    this._moveCursor(params.params[0] || 1, 0);
+  }
+
+  /**
+   * CSI Pm d  Vertical Position Absolute (VPA)
+   *   [row] (default = [1,column])
+   */
+  public linePosAbsolute(params: IParams): void {
+    this._setCursor(this._bufferService.buffer.x, (params.params[0] || 1) - 1);
+  }
+
+  /**
+   * CSI Pm e  Vertical Position Relative (VPR)
+   *   [rows] (default = [row+1,column])
+   * reuse CSI Ps B ?
+   */
+  public vPositionRelative(params: IParams): void {
+    this._moveCursor(0, params.params[0] || 1);
+  }
+
+  /**
+   * CSI Ps ; Ps f
+   *   Horizontal and Vertical Position [row;column] (default =
+   *   [1,1]) (HVP).
+   *   Same as CUP.
+   */
+  public hVPosition(params: IParams): void {
+    this.cursorPosition(params);
+  }
+
+  /**
+   * CSI Ps g  Tab Clear (TBC).
+   *     Ps = 0  -> Clear Current Column (default).
+   *     Ps = 3  -> Clear All.
+   * Potentially:
+   *   Ps = 2  -> Clear Stops on Line.
+   *   http://vt100.net/annarbor/aaa-ug/section6.html
+   */
+  public tabClear(params: IParams): void {
+    const param = params.params[0];
+    if (param === 0) {
+      delete this._bufferService.buffer.tabs[this._bufferService.buffer.x];
+    } else if (param === 3) {
+      this._bufferService.buffer.tabs = {};
+    }
+  }
+
+  /**
+   * CSI Ps I
+   *   Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
+   */
+  public cursorForwardTab(params: IParams): void {
+    if (this._bufferService.buffer.x >= this._bufferService.cols) {
+      return;
+    }
+    let param = params.params[0] || 1;
+    while (param--) {
+      this._bufferService.buffer.x = this._bufferService.buffer.nextStop();
+    }
+  }
+
+  /**
+   * CSI Ps Z  Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
+   */
+  public cursorBackwardTab(params: IParams): void {
+    if (this._bufferService.buffer.x >= this._bufferService.cols) {
+      return;
+    }
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    while (param--) {
+      buffer.x = buffer.prevStop();
+    }
+  }
+
+
+  /**
+   * Helper method to erase cells in a terminal row.
+   * The cell gets replaced with the eraseChar of the terminal.
+   * @param y row index
+   * @param start first cell index to be erased
+   * @param end   end - 1 is last erased cell
+   */
+  private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false): void {
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);
+    line.replaceCells(
+      start,
+      end,
+      this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+    );
+    if (clearWrap) {
+      line.isWrapped = false;
+    }
+  }
+
+  /**
+   * Helper method to reset cells in a terminal row.
+   * The cell gets replaced with the eraseChar of the terminal and the isWrapped property is set to false.
+   * @param y row index
+   */
+  private _resetBufferLine(y: number): void {
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.ybase + y);
+    line.fill(this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData()));
+    line.isWrapped = false;
+  }
+
+  /**
+   * CSI Ps J  Erase in Display (ED).
+   *     Ps = 0  -> Erase Below (default).
+   *     Ps = 1  -> Erase Above.
+   *     Ps = 2  -> Erase All.
+   *     Ps = 3  -> Erase Saved Lines (xterm).
+   * CSI ? Ps J
+   *   Erase in Display (DECSED).
+   *     Ps = 0  -> Selective Erase Below (default).
+   *     Ps = 1  -> Selective Erase Above.
+   *     Ps = 2  -> Selective Erase All.
+   */
+  public eraseInDisplay(params: IParams): void {
+    this._restrictCursor();
+    let j;
+    switch (params.params[0]) {
+      case 0:
+        j = this._bufferService.buffer.y;
+        this._dirtyRowService.markDirty(j);
+        this._eraseInBufferLine(j++, this._bufferService.buffer.x, this._bufferService.cols, this._bufferService.buffer.x === 0);
+        for (; j < this._bufferService.rows; j++) {
+          this._resetBufferLine(j);
+        }
+        this._dirtyRowService.markDirty(j);
+        break;
+      case 1:
+        j = this._bufferService.buffer.y;
+        this._dirtyRowService.markDirty(j);
+        // Deleted front part of line and everything before. This line will no longer be wrapped.
+        this._eraseInBufferLine(j, 0, this._bufferService.buffer.x + 1, true);
+        if (this._bufferService.buffer.x + 1 >= this._bufferService.cols) {
+          // Deleted entire previous line. This next line can no longer be wrapped.
+          this._bufferService.buffer.lines.get(j + 1).isWrapped = false;
+        }
+        while (j--) {
+          this._resetBufferLine(j);
+        }
+        this._dirtyRowService.markDirty(0);
+        break;
+      case 2:
+        j = this._bufferService.rows;
+        this._dirtyRowService.markDirty(j - 1);
+        while (j--) {
+          this._resetBufferLine(j);
+        }
+        this._dirtyRowService.markDirty(0);
+        break;
+      case 3:
+        // Clear scrollback (everything not in viewport)
+        const scrollBackSize = this._bufferService.buffer.lines.length - this._bufferService.rows;
+        if (scrollBackSize > 0) {
+          this._bufferService.buffer.lines.trimStart(scrollBackSize);
+          this._bufferService.buffer.ybase = Math.max(this._bufferService.buffer.ybase - scrollBackSize, 0);
+          this._bufferService.buffer.ydisp = Math.max(this._bufferService.buffer.ydisp - scrollBackSize, 0);
+          // Force a scroll event to refresh viewport
+          this._onScroll.fire(0);
+        }
+        break;
+    }
+  }
+
+  /**
+   * CSI Ps K  Erase in Line (EL).
+   *     Ps = 0  -> Erase to Right (default).
+   *     Ps = 1  -> Erase to Left.
+   *     Ps = 2  -> Erase All.
+   * CSI ? Ps K
+   *   Erase in Line (DECSEL).
+   *     Ps = 0  -> Selective Erase to Right (default).
+   *     Ps = 1  -> Selective Erase to Left.
+   *     Ps = 2  -> Selective Erase All.
+   */
+  public eraseInLine(params: IParams): void {
+    this._restrictCursor();
+    switch (params.params[0]) {
+      case 0:
+        this._eraseInBufferLine(this._bufferService.buffer.y, this._bufferService.buffer.x, this._bufferService.cols);
+        break;
+      case 1:
+        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.buffer.x + 1);
+        break;
+      case 2:
+        this._eraseInBufferLine(this._bufferService.buffer.y, 0, this._bufferService.cols);
+        break;
+    }
+    this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+  }
+
+  /**
+   * CSI Ps L
+   * Insert Ps Line(s) (default = 1) (IL).
+   */
+  public insertLines(params: IParams): void {
+    this._restrictCursor();
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+
+    const row: number = buffer.y + buffer.ybase;
+
+    const scrollBottomRowsOffset = this._bufferService.rows - 1 - buffer.scrollBottom;
+    const scrollBottomAbsolute = this._bufferService.rows - 1 + buffer.ybase - scrollBottomRowsOffset + 1;
+    while (param--) {
+      // test: echo -e '\e[44m\e[1L\e[0m'
+      // blankLine(true) - xterm/linux behavior
+      buffer.lines.splice(scrollBottomAbsolute - 1, 1);
+      buffer.lines.splice(row, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));
+    }
+
+    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);
+    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?
+  }
+
+  /**
+   * CSI Ps M
+   * Delete Ps Line(s) (default = 1) (DL).
+   */
+  public deleteLines(params: IParams): void {
+    this._restrictCursor();
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+
+    const row: number = buffer.y + buffer.ybase;
+
+    let j: number;
+    j = this._bufferService.rows - 1 - buffer.scrollBottom;
+    j = this._bufferService.rows - 1 + buffer.ybase - j;
+    while (param--) {
+      // test: echo -e '\e[44m\e[1M\e[0m'
+      // blankLine(true) - xterm/linux behavior
+      buffer.lines.splice(row, 1);
+      buffer.lines.splice(j, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));
+    }
+
+    this._dirtyRowService.markRangeDirty(buffer.y, buffer.scrollBottom);
+    buffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?
+  }
+
+  /**
+   * CSI Ps @
+   * Insert Ps (Blank) Character(s) (default = 1) (ICH).
+   */
+  public insertChars(params: IParams): void {
+    this._restrictCursor();
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);
+    if (line) {
+      line.insertCells(
+        this._bufferService.buffer.x,
+        params.params[0] || 1,
+        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+      );
+      this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+    }
+  }
+
+  /**
+   * CSI Ps P
+   * Delete Ps Character(s) (default = 1) (DCH).
+   */
+  public deleteChars(params: IParams): void {
+    this._restrictCursor();
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);
+    if (line) {
+      line.deleteCells(
+        this._bufferService.buffer.x,
+        params.params[0] || 1,
+        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+      );
+      this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+    }
+  }
+
+  /**
+   * CSI Ps S  Scroll up Ps lines (default = 1) (SU).
+   */
+  public scrollUp(params: IParams): void {
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    while (param--) {
+      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 1);
+      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(this._terminal.eraseAttrData()));
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps T  Scroll down Ps lines (default = 1) (SD).
+   */
+  public scrollDown(params: IParams): void {
+    let param = params.params[0] || 1;
+
+    // make buffer local for faster access
+    const buffer = this._bufferService.buffer;
+
+    while (param--) {
+      buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 1);
+      buffer.lines.splice(buffer.ybase + buffer.scrollTop, 0, buffer.getBlankLine(DEFAULT_ATTR_DATA));
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps SP @  Scroll left Ps columns (default = 1) (SL) ECMA-48
+   *
+   * Notation: (Pn)
+   * Representation: CSI Pn 02/00 04/00
+   * Parameter default value: Pn = 1
+   * SL causes the data in the presentation component to be moved by n character positions
+   * if the line orientation is horizontal, or by n line positions if the line orientation
+   * is vertical, such that the data appear to move to the left; where n equals the value of Pn.
+   * The active presentation position is not affected by this control function.
+   *
+   * Supported:
+   *   - always left shift (no line orientation setting respected)
+   */
+  public scrollLeft(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = buffer.lines.get(buffer.ybase + y);
+      line.deleteCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps SP A  Scroll right Ps columns (default = 1) (SR) ECMA-48
+   *
+   * Notation: (Pn)
+   * Representation: CSI Pn 02/00 04/01
+   * Parameter default value: Pn = 1
+   * SR causes the data in the presentation component to be moved by n character positions
+   * if the line orientation is horizontal, or by n line positions if the line orientation
+   * is vertical, such that the data appear to move to the right; where n equals the value of Pn.
+   * The active presentation position is not affected by this control function.
+   *
+   * Supported:
+   *   - always right shift (no line orientation setting respected)
+   */
+  public scrollRight(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = buffer.lines.get(buffer.ybase + y);
+      line.insertCells(0, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Pm ' }
+   * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.
+   */
+  public insertColumns(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = this._bufferService.buffer.lines.get(buffer.ybase + y);
+      line.insertCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Pm ' ~
+   * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.
+   */
+  public deleteColumns(params: IParams): void {
+    const buffer = this._bufferService.buffer;
+    if (buffer.y > buffer.scrollBottom || buffer.y < buffer.scrollTop) {
+      return;
+    }
+    const param = params.params[0] || 1;
+    for (let y = buffer.scrollTop; y <= buffer.scrollBottom; ++y) {
+      const line = buffer.lines.get(buffer.ybase + y);
+      line.deleteCells(buffer.x, param, buffer.getNullCell(this._terminal.eraseAttrData()));
+      line.isWrapped = false;
+    }
+    this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+  }
+
+  /**
+   * CSI Ps X
+   * Erase Ps Character(s) (default = 1) (ECH).
+   */
+  public eraseChars(params: IParams): void {
+    this._restrictCursor();
+    const line = this._bufferService.buffer.lines.get(this._bufferService.buffer.y + this._bufferService.buffer.ybase);
+    if (line) {
+      line.replaceCells(
+        this._bufferService.buffer.x,
+        this._bufferService.buffer.x + (params.params[0] || 1),
+        this._bufferService.buffer.getNullCell(this._terminal.eraseAttrData())
+      );
+      this._dirtyRowService.markDirty(this._bufferService.buffer.y);
+    }
+  }
+
+  /**
+   * CSI Ps b  Repeat the preceding graphic character Ps times (REP).
+   * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)
+   *    Notation: (Pn)
+   *    Representation: CSI Pn 06/02
+   *    Parameter default value: Pn = 1
+   *    REP is used to indicate that the preceding character in the data stream,
+   *    if it is a graphic character (represented by one or more bit combinations) including SPACE,
+   *    is to be repeated n times, where n equals the value of Pn.
+   *    If the character preceding REP is a control function or part of a control function,
+   *    the effect of REP is not defined by this Standard.
+   *
+   * Since we propagate the terminal as xterm-256color we have to follow xterm's behavior:
+   *    - fullwidth + surrogate chars are ignored
+   *    - for combining chars only the base char gets repeated
+   *    - text attrs are applied normally
+   *    - wrap around is respected
+   *    - any valid sequence resets the carried forward char
+   *
+   * Note: To get reset on a valid sequence working correctly without much runtime penalty,
+   * the preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.
+   */
+  public repeatPrecedingCharacter(params: IParams): void {
+    if (!this._parser.precedingCodepoint) {
+      return;
+    }
+    // call print to insert the chars and handle correct wrapping
+    const length = params.params[0] || 1;
+    const data = new Uint32Array(length);
+    for (let i = 0; i < length; ++i) {
+      data[i] = this._parser.precedingCodepoint;
+    }
+    this.print(data, 0, data.length);
+  }
+
+  /**
+   * CSI Ps c  Send Device Attributes (Primary DA).
+   *     Ps = 0  or omitted -> request attributes from terminal.  The
+   *     response depends on the decTerminalID resource setting.
+   *     -> CSI ? 1 ; 2 c  (``VT100 with Advanced Video Option'')
+   *     -> CSI ? 1 ; 0 c  (``VT101 with No Options'')
+   *     -> CSI ? 6 c  (``VT102'')
+   *     -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c  (``VT220'')
+   *   The VT100-style response parameters do not mean anything by
+   *   themselves.  VT220 parameters do, telling the host what fea-
+   *   tures the terminal supports:
+   *     Ps = 1  -> 132-columns.
+   *     Ps = 2  -> Printer.
+   *     Ps = 6  -> Selective erase.
+   *     Ps = 8  -> User-defined keys.
+   *     Ps = 9  -> National replacement character sets.
+   *     Ps = 1 5  -> Technical characters.
+   *     Ps = 2 2  -> ANSI color, e.g., VT525.
+   *     Ps = 2 9  -> ANSI text locator (i.e., DEC Locator mode).
+   * CSI > Ps c
+   *   Send Device Attributes (Secondary DA).
+   *     Ps = 0  or omitted -> request the terminal's identification
+   *     code.  The response depends on the decTerminalID resource set-
+   *     ting.  It should apply only to VT220 and up, but xterm extends
+   *     this to VT100.
+   *     -> CSI  > Pp ; Pv ; Pc c
+   *   where Pp denotes the terminal type
+   *     Pp = 0  -> ``VT100''.
+   *     Pp = 1  -> ``VT220''.
+   *   and Pv is the firmware version (for xterm, this was originally
+   *   the XFree86 patch number, starting with 95).  In a DEC termi-
+   *   nal, Pc indicates the ROM cartridge registration number and is
+   *   always zero.
+   * More information:
+   *   xterm/charproc.c - line 2012, for more information.
+   *   vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
+   */
+  public sendDeviceAttributesPrimary(params: IParams): void {
+    if (params.params[0] > 0) {
+      return;
+    }
+    if (this._terminal.is('xterm') || this._terminal.is('rxvt-unicode') || this._terminal.is('screen')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');
+    } else if (this._terminal.is('linux')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[?6c');
+    }
+  }
+  public sendDeviceAttributesSecondary(params: IParams): void {
+    if (params.params[0] > 0) {
+      return;
+    }
+    // xterm and urxvt
+    // seem to spit this
+    // out around ~370 times (?).
+    if (this._terminal.is('xterm')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');
+    } else if (this._terminal.is('rxvt-unicode')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');
+    } else if (this._terminal.is('linux')) {
+      // not supported by linux console.
+      // linux console echoes parameters.
+      this._coreService.triggerDataEvent(params.params[0] + 'c');
+    } else if (this._terminal.is('screen')) {
+      this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');
+    }
+  }
+
+  /**
+   * CSI Pm h  Set Mode (SM).
+   *     Ps = 2  -> Keyboard Action Mode (AM).
+   *     Ps = 4  -> Insert Mode (IRM).
+   *     Ps = 1 2  -> Send/receive (SRM).
+   *     Ps = 2 0  -> Automatic Newline (LNM).
+   * CSI ? Pm h
+   *   DEC Private Mode Set (DECSET).
+   *     Ps = 1  -> Application Cursor Keys (DECCKM).
+   *     Ps = 2  -> Designate USASCII for character sets G0-G3
+   *     (DECANM), and set VT100 mode.
+   *     Ps = 3  -> 132 Column Mode (DECCOLM).
+   *     Ps = 4  -> Smooth (Slow) Scroll (DECSCLM).
+   *     Ps = 5  -> Reverse Video (DECSCNM).
+   *     Ps = 6  -> Origin Mode (DECOM).
+   *     Ps = 7  -> Wraparound Mode (DECAWM).
+   *     Ps = 8  -> Auto-repeat Keys (DECARM).
+   *     Ps = 9  -> Send Mouse X & Y on button press.  See the sec-
+   *     tion Mouse Tracking.
+   *     Ps = 1 0  -> Show toolbar (rxvt).
+   *     Ps = 1 2  -> Start Blinking Cursor (att610).
+   *     Ps = 1 8  -> Print form feed (DECPFF).
+   *     Ps = 1 9  -> Set print extent to full screen (DECPEX).
+   *     Ps = 2 5  -> Show Cursor (DECTCEM).
+   *     Ps = 3 0  -> Show scrollbar (rxvt).
+   *     Ps = 3 5  -> Enable font-shifting functions (rxvt).
+   *     Ps = 3 8  -> Enter Tektronix Mode (DECTEK).
+   *     Ps = 4 0  -> Allow 80 -> 132 Mode.
+   *     Ps = 4 1  -> more(1) fix (see curses resource).
+   *     Ps = 4 2  -> Enable Nation Replacement Character sets (DECN-
+   *     RCM).
+   *     Ps = 4 4  -> Turn On Margin Bell.
+   *     Ps = 4 5  -> Reverse-wraparound Mode.
+   *     Ps = 4 6  -> Start Logging.  This is normally disabled by a
+   *     compile-time option.
+   *     Ps = 4 7  -> Use Alternate Screen Buffer.  (This may be dis-
+   *     abled by the titeInhibit resource).
+   *     Ps = 6 6  -> Application keypad (DECNKM).
+   *     Ps = 6 7  -> Backarrow key sends backspace (DECBKM).
+   *     Ps = 1 0 0 0  -> Send Mouse X & Y on button press and
+   *     release.  See the section Mouse Tracking.
+   *     Ps = 1 0 0 1  -> Use Hilite Mouse Tracking.
+   *     Ps = 1 0 0 2  -> Use Cell Motion Mouse Tracking.
+   *     Ps = 1 0 0 3  -> Use All Motion Mouse Tracking.
+   *     Ps = 1 0 0 4  -> Send FocusIn/FocusOut events.
+   *     Ps = 1 0 0 5  -> Enable Extended Mouse Mode.
+   *     Ps = 1 0 1 0  -> Scroll to bottom on tty output (rxvt).
+   *     Ps = 1 0 1 1  -> Scroll to bottom on key press (rxvt).
+   *     Ps = 1 0 3 4  -> Interpret "meta" key, sets eighth bit.
+   *     (enables the eightBitInput resource).
+   *     Ps = 1 0 3 5  -> Enable special modifiers for Alt and Num-
+   *     Lock keys.  (This enables the numLock resource).
+   *     Ps = 1 0 3 6  -> Send ESC   when Meta modifies a key.  (This
+   *     enables the metaSendsEscape resource).
+   *     Ps = 1 0 3 7  -> Send DEL from the editing-keypad Delete
+   *     key.
+   *     Ps = 1 0 3 9  -> Send ESC  when Alt modifies a key.  (This
+   *     enables the altSendsEscape resource).
+   *     Ps = 1 0 4 0  -> Keep selection even if not highlighted.
+   *     (This enables the keepSelection resource).
+   *     Ps = 1 0 4 1  -> Use the CLIPBOARD selection.  (This enables
+   *     the selectToClipboard resource).
+   *     Ps = 1 0 4 2  -> Enable Urgency window manager hint when
+   *     Control-G is received.  (This enables the bellIsUrgent
+   *     resource).
+   *     Ps = 1 0 4 3  -> Enable raising of the window when Control-G
+   *     is received.  (enables the popOnBell resource).
+   *     Ps = 1 0 4 7  -> Use Alternate Screen Buffer.  (This may be
+   *     disabled by the titeInhibit resource).
+   *     Ps = 1 0 4 8  -> Save cursor as in DECSC.  (This may be dis-
+   *     abled by the titeInhibit resource).
+   *     Ps = 1 0 4 9  -> Save cursor as in DECSC and use Alternate
+   *     Screen Buffer, clearing it first.  (This may be disabled by
+   *     the titeInhibit resource).  This combines the effects of the 1
+   *     0 4 7  and 1 0 4 8  modes.  Use this with terminfo-based
+   *     applications rather than the 4 7  mode.
+   *     Ps = 1 0 5 0  -> Set terminfo/termcap function-key mode.
+   *     Ps = 1 0 5 1  -> Set Sun function-key mode.
+   *     Ps = 1 0 5 2  -> Set HP function-key mode.
+   *     Ps = 1 0 5 3  -> Set SCO function-key mode.
+   *     Ps = 1 0 6 0  -> Set legacy keyboard emulation (X11R6).
+   *     Ps = 1 0 6 1  -> Set VT220 keyboard emulation.
+   *     Ps = 2 0 0 4  -> Set bracketed paste mode.
+   * Modes:
+   *   http: *vt100.net/docs/vt220-rm/chapter4.html
+   */
+  public setMode(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 4:
+          this._terminal.insertMode = true;
+          break;
+        case 20:
+          // this._t.convertEol = true;
+          break;
+      }
+    }
+  }
+  public setModePrivate(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 1:
+          this._coreService.decPrivateModes.applicationCursorKeys = true;
+          break;
+        case 2:
+          this._terminal.setgCharset(0, DEFAULT_CHARSET);
+          this._terminal.setgCharset(1, DEFAULT_CHARSET);
+          this._terminal.setgCharset(2, DEFAULT_CHARSET);
+          this._terminal.setgCharset(3, DEFAULT_CHARSET);
+          // set VT100 mode here
+          break;
+        case 3: // 132 col mode
+          // TODO: move DECCOLM into compat addon
+          this._terminal.savedCols = this._bufferService.cols;
+          this._terminal.resize(132, this._bufferService.rows);
+          this._terminal.reset();
+          break;
+        case 6:
+          this._terminal.originMode = true;
+          this._setCursor(0, 0);
+          break;
+        case 7:
+          this._terminal.wraparoundMode = true;
+          break;
+        case 12:
+          // this.cursorBlink = true;
+          break;
+        case 66:
+          this._logService.debug('Serial port requested application keypad.');
+          this._terminal.applicationKeypad = true;
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          break;
+        case 9: // X10 Mouse
+          // no release, no motion, no wheel, no modifiers.
+          this._coreMouseService.activeProtocol = 'X10';
+          break;
+        case 1000: // vt200 mouse
+          // no motion.
+          this._coreMouseService.activeProtocol = 'VT200';
+          break;
+        case 1002: // button event mouse
+          this._coreMouseService.activeProtocol = 'DRAG';
+          break;
+        case 1003: // any event mouse
+          // any event - sends motion events,
+          // even if there is no button held down.
+          this._coreMouseService.activeProtocol = 'ANY';
+          break;
+        case 1004: // send focusin/focusout events
+          // focusin: ^[[I
+          // focusout: ^[[O
+          this._terminal.sendFocus = true;
+          break;
+        case 1005: // utf8 ext mode mouse - removed in #2507
+          this._logService.debug('DECSET 1005 not supported (see #2507)');
+          break;
+        case 1006: // sgr ext mode mouse
+          this._coreMouseService.activeEncoding = 'SGR';
+          break;
+        case 1015: // urxvt ext mode mouse - removed in #2507
+          this._logService.debug('DECSET 1015 not supported (see #2507)');
+          break;
+        case 25: // show cursor
+          this._terminal.cursorHidden = false;
+          break;
+        case 1048: // alt screen cursor
+          this.saveCursor();
+          break;
+        case 1049: // alt screen buffer cursor
+          this.saveCursor();
+          // FALL-THROUGH
+        case 47: // alt screen buffer
+        case 1047: // alt screen buffer
+          this._bufferService.buffers.activateAltBuffer(this._terminal.eraseAttrData());
+          this._terminal.refresh(0, this._bufferService.rows - 1);
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          this._terminal.showCursor();
+          break;
+        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)
+          this._terminal.bracketedPasteMode = true;
+          break;
+      }
+    }
+  }
+
+
+  /**
+   * CSI Pm l  Reset Mode (RM).
+   *     Ps = 2  -> Keyboard Action Mode (AM).
+   *     Ps = 4  -> Replace Mode (IRM).
+   *     Ps = 1 2  -> Send/receive (SRM).
+   *     Ps = 2 0  -> Normal Linefeed (LNM).
+   * CSI ? Pm l
+   *   DEC Private Mode Reset (DECRST).
+   *     Ps = 1  -> Normal Cursor Keys (DECCKM).
+   *     Ps = 2  -> Designate VT52 mode (DECANM).
+   *     Ps = 3  -> 80 Column Mode (DECCOLM).
+   *     Ps = 4  -> Jump (Fast) Scroll (DECSCLM).
+   *     Ps = 5  -> Normal Video (DECSCNM).
+   *     Ps = 6  -> Normal Cursor Mode (DECOM).
+   *     Ps = 7  -> No Wraparound Mode (DECAWM).
+   *     Ps = 8  -> No Auto-repeat Keys (DECARM).
+   *     Ps = 9  -> Don't send Mouse X & Y on button press.
+   *     Ps = 1 0  -> Hide toolbar (rxvt).
+   *     Ps = 1 2  -> Stop Blinking Cursor (att610).
+   *     Ps = 1 8  -> Don't print form feed (DECPFF).
+   *     Ps = 1 9  -> Limit print to scrolling region (DECPEX).
+   *     Ps = 2 5  -> Hide Cursor (DECTCEM).
+   *     Ps = 3 0  -> Don't show scrollbar (rxvt).
+   *     Ps = 3 5  -> Disable font-shifting functions (rxvt).
+   *     Ps = 4 0  -> Disallow 80 -> 132 Mode.
+   *     Ps = 4 1  -> No more(1) fix (see curses resource).
+   *     Ps = 4 2  -> Disable Nation Replacement Character sets (DEC-
+   *     NRCM).
+   *     Ps = 4 4  -> Turn Off Margin Bell.
+   *     Ps = 4 5  -> No Reverse-wraparound Mode.
+   *     Ps = 4 6  -> Stop Logging.  (This is normally disabled by a
+   *     compile-time option).
+   *     Ps = 4 7  -> Use Normal Screen Buffer.
+   *     Ps = 6 6  -> Numeric keypad (DECNKM).
+   *     Ps = 6 7  -> Backarrow key sends delete (DECBKM).
+   *     Ps = 1 0 0 0  -> Don't send Mouse X & Y on button press and
+   *     release.  See the section Mouse Tracking.
+   *     Ps = 1 0 0 1  -> Don't use Hilite Mouse Tracking.
+   *     Ps = 1 0 0 2  -> Don't use Cell Motion Mouse Tracking.
+   *     Ps = 1 0 0 3  -> Don't use All Motion Mouse Tracking.
+   *     Ps = 1 0 0 4  -> Don't send FocusIn/FocusOut events.
+   *     Ps = 1 0 0 5  -> Disable Extended Mouse Mode.
+   *     Ps = 1 0 1 0  -> Don't scroll to bottom on tty output
+   *     (rxvt).
+   *     Ps = 1 0 1 1  -> Don't scroll to bottom on key press (rxvt).
+   *     Ps = 1 0 3 4  -> Don't interpret "meta" key.  (This disables
+   *     the eightBitInput resource).
+   *     Ps = 1 0 3 5  -> Disable special modifiers for Alt and Num-
+   *     Lock keys.  (This disables the numLock resource).
+   *     Ps = 1 0 3 6  -> Don't send ESC  when Meta modifies a key.
+   *     (This disables the metaSendsEscape resource).
+   *     Ps = 1 0 3 7  -> Send VT220 Remove from the editing-keypad
+   *     Delete key.
+   *     Ps = 1 0 3 9  -> Don't send ESC  when Alt modifies a key.
+   *     (This disables the altSendsEscape resource).
+   *     Ps = 1 0 4 0  -> Do not keep selection when not highlighted.
+   *     (This disables the keepSelection resource).
+   *     Ps = 1 0 4 1  -> Use the PRIMARY selection.  (This disables
+   *     the selectToClipboard resource).
+   *     Ps = 1 0 4 2  -> Disable Urgency window manager hint when
+   *     Control-G is received.  (This disables the bellIsUrgent
+   *     resource).
+   *     Ps = 1 0 4 3  -> Disable raising of the window when Control-
+   *     G is received.  (This disables the popOnBell resource).
+   *     Ps = 1 0 4 7  -> Use Normal Screen Buffer, clearing screen
+   *     first if in the Alternate Screen.  (This may be disabled by
+   *     the titeInhibit resource).
+   *     Ps = 1 0 4 8  -> Restore cursor as in DECRC.  (This may be
+   *     disabled by the titeInhibit resource).
+   *     Ps = 1 0 4 9  -> Use Normal Screen Buffer and restore cursor
+   *     as in DECRC.  (This may be disabled by the titeInhibit
+   *     resource).  This combines the effects of the 1 0 4 7  and 1 0
+   *     4 8  modes.  Use this with terminfo-based applications rather
+   *     than the 4 7  mode.
+   *     Ps = 1 0 5 0  -> Reset terminfo/termcap function-key mode.
+   *     Ps = 1 0 5 1  -> Reset Sun function-key mode.
+   *     Ps = 1 0 5 2  -> Reset HP function-key mode.
+   *     Ps = 1 0 5 3  -> Reset SCO function-key mode.
+   *     Ps = 1 0 6 0  -> Reset legacy keyboard emulation (X11R6).
+   *     Ps = 1 0 6 1  -> Reset keyboard emulation to Sun/PC style.
+   *     Ps = 2 0 0 4  -> Reset bracketed paste mode.
+   */
+  public resetMode(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 4:
+          this._terminal.insertMode = false;
+          break;
+        case 20:
+          // this._t.convertEol = false;
+          break;
+      }
+    }
+  }
+  public resetModePrivate(params: IParams): void {
+    for (let i = 0; i < params.length; i++) {
+      switch (params.params[i]) {
+        case 1:
+          this._coreService.decPrivateModes.applicationCursorKeys = false;
+          break;
+        case 3:
+          // TODO: move DECCOLM into compat addon
+          // Note: This impl currently does not enforce col 80, instead reverts
+          // to previous terminal width before entering DECCOLM 132
+          if (this._bufferService.cols === 132 && this._terminal.savedCols) {
+            this._terminal.resize(this._terminal.savedCols, this._bufferService.rows);
+          }
+          delete this._terminal.savedCols;
+          this._terminal.reset();
+          break;
+        case 6:
+          this._terminal.originMode = false;
+          this._setCursor(0, 0);
+          break;
+        case 7:
+          this._terminal.wraparoundMode = false;
+          break;
+        case 12:
+          // this.cursorBlink = false;
+          break;
+        case 66:
+          this._logService.debug('Switching back to normal keypad.');
+          this._terminal.applicationKeypad = false;
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          break;
+        case 9: // X10 Mouse
+        case 1000: // vt200 mouse
+        case 1002: // button event mouse
+        case 1003: // any event mouse
+          this._coreMouseService.activeProtocol = 'NONE';
+          break;
+        case 1004: // send focusin/focusout events
+          this._terminal.sendFocus = false;
+          break;
+        case 1005: // utf8 ext mode mouse - removed in #2507
+          this._logService.debug('DECRST 1005 not supported (see #2507)');
+          break;
+        case 1006: // sgr ext mode mouse
+          this._coreMouseService.activeEncoding = 'DEFAULT';
+          break;
+        case 1015: // urxvt ext mode mouse - removed in #2507
+        this._logService.debug('DECRST 1015 not supported (see #2507)');
+          break;
+        case 25: // hide cursor
+          this._terminal.cursorHidden = true;
+          break;
+        case 1048: // alt screen cursor
+          this.restoreCursor();
+          break;
+        case 1049: // alt screen buffer cursor
+           // FALL-THROUGH
+        case 47: // normal screen buffer
+        case 1047: // normal screen buffer - clearing it first
+          // Ensure the selection manager has the correct buffer
+          this._bufferService.buffers.activateNormalBuffer();
+          if (params.params[i] === 1049) {
+            this.restoreCursor();
+          }
+          this._terminal.refresh(0, this._bufferService.rows - 1);
+          if (this._terminal.viewport) {
+            this._terminal.viewport.syncScrollArea();
+          }
+          this._terminal.showCursor();
+          break;
+        case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)
+          this._terminal.bracketedPasteMode = false;
+          break;
+      }
+    }
+  }
+
+  /**
+   * Helper to extract and apply color params/subparams.
+   * Returns advance for params index.
+   */
+  private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {
+    // normalize params
+    // meaning: [target, CM, ign, val, val, val]
+    // RGB    : [ 38/48,  2, ign,   r,   g,   b]
+    // P256   : [ 38/48,  5, ign,   v, ign, ign]
+    const accu = [0, 0, -1, 0, 0, 0];
+
+    // alignment placeholder for non color space sequences
+    let cSpace = 0;
+
+    // return advance we took in params
+    let advance = 0;
+
+    do {
+      accu[advance + cSpace] = params.params[pos + advance];
+      if (params.hasSubParams(pos + advance)) {
+        const subparams = params.getSubParams(pos + advance);
+        let i = 0;
+        do {
+          if (accu[1] === 5) {
+            cSpace = 1;
+          }
+          accu[advance + i + 1 + cSpace] = subparams[i];
+        } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);
+        break;
+      }
+      // exit early if can decide color mode with semicolons
+      if ((accu[1] === 5 && advance + cSpace >= 2)
+          || (accu[1] === 2 && advance + cSpace >= 5)) {
+        break;
+      }
+      // offset colorSpace slot for semicolon mode
+      if (accu[1]) {
+        cSpace = 1;
+      }
+    } while (++advance + pos < params.length && advance + cSpace < accu.length);
+
+    // set default values to 0
+    for (let i = 2; i < accu.length; ++i) {
+      if (accu[i] === -1) {
+        accu[i] = 0;
+      }
+    }
+
+    // apply colors
+    if (accu[0] === 38) {
+      if (accu[1] === 2) {
+        attr.fg |= Attributes.CM_RGB;
+        attr.fg &= ~Attributes.RGB_MASK;
+        attr.fg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);
+      } else if (accu[1] === 5) {
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.fg |= Attributes.CM_P256 | (accu[3] & 0xff);
+      }
+    } else if (accu[0] === 48) {
+      if (accu[1] === 2) {
+        attr.bg |= Attributes.CM_RGB;
+        attr.bg &= ~Attributes.RGB_MASK;
+        attr.bg |= AttributeData.fromColorRGB([accu[3], accu[4], accu[5]]);
+      } else if (accu[1] === 5) {
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.bg |= Attributes.CM_P256 | (accu[3] & 0xff);
+      }
+    }
+
+    return advance;
+  }
+
+  /**
+   * CSI Pm m  Character Attributes (SGR).
+   *     Ps = 0  -> Normal (default).
+   *     Ps = 1  -> Bold.
+   *     Ps = 2  -> Faint, decreased intensity (ISO 6429).
+   *     Ps = 4  -> Underlined.
+   *     Ps = 5  -> Blink (appears as Bold).
+   *     Ps = 7  -> Inverse.
+   *     Ps = 8  -> Invisible, i.e., hidden (VT300).
+   *     Ps = 2 2  -> Normal (neither bold nor faint).
+   *     Ps = 2 4  -> Not underlined.
+   *     Ps = 2 5  -> Steady (not blinking).
+   *     Ps = 2 7  -> Positive (not inverse).
+   *     Ps = 2 8  -> Visible, i.e., not hidden (VT300).
+   *     Ps = 3 0  -> Set foreground color to Black.
+   *     Ps = 3 1  -> Set foreground color to Red.
+   *     Ps = 3 2  -> Set foreground color to Green.
+   *     Ps = 3 3  -> Set foreground color to Yellow.
+   *     Ps = 3 4  -> Set foreground color to Blue.
+   *     Ps = 3 5  -> Set foreground color to Magenta.
+   *     Ps = 3 6  -> Set foreground color to Cyan.
+   *     Ps = 3 7  -> Set foreground color to White.
+   *     Ps = 3 9  -> Set foreground color to default (original).
+   *     Ps = 4 0  -> Set background color to Black.
+   *     Ps = 4 1  -> Set background color to Red.
+   *     Ps = 4 2  -> Set background color to Green.
+   *     Ps = 4 3  -> Set background color to Yellow.
+   *     Ps = 4 4  -> Set background color to Blue.
+   *     Ps = 4 5  -> Set background color to Magenta.
+   *     Ps = 4 6  -> Set background color to Cyan.
+   *     Ps = 4 7  -> Set background color to White.
+   *     Ps = 4 9  -> Set background color to default (original).
+   *
+   *   If 16-color support is compiled, the following apply.  Assume
+   *   that xterm's resources are set so that the ISO color codes are
+   *   the first 8 of a set of 16.  Then the aixterm colors are the
+   *   bright versions of the ISO colors:
+   *     Ps = 9 0  -> Set foreground color to Black.
+   *     Ps = 9 1  -> Set foreground color to Red.
+   *     Ps = 9 2  -> Set foreground color to Green.
+   *     Ps = 9 3  -> Set foreground color to Yellow.
+   *     Ps = 9 4  -> Set foreground color to Blue.
+   *     Ps = 9 5  -> Set foreground color to Magenta.
+   *     Ps = 9 6  -> Set foreground color to Cyan.
+   *     Ps = 9 7  -> Set foreground color to White.
+   *     Ps = 1 0 0  -> Set background color to Black.
+   *     Ps = 1 0 1  -> Set background color to Red.
+   *     Ps = 1 0 2  -> Set background color to Green.
+   *     Ps = 1 0 3  -> Set background color to Yellow.
+   *     Ps = 1 0 4  -> Set background color to Blue.
+   *     Ps = 1 0 5  -> Set background color to Magenta.
+   *     Ps = 1 0 6  -> Set background color to Cyan.
+   *     Ps = 1 0 7  -> Set background color to White.
+   *
+   *   If xterm is compiled with the 16-color support disabled, it
+   *   supports the following, from rxvt:
+   *     Ps = 1 0 0  -> Set foreground and background color to
+   *     default.
+   *
+   *   If 88- or 256-color support is compiled, the following apply.
+   *     Ps = 3 8  ; 5  ; Ps -> Set foreground color to the second
+   *     Ps.
+   *     Ps = 4 8  ; 5  ; Ps -> Set background color to the second
+   *     Ps.
+   */
+  public charAttributes(params: IParams): void {
+    // Optimize a single SGR0.
+    if (params.length === 1 && params.params[0] === 0) {
+      this._terminal.curAttrData.fg = DEFAULT_ATTR_DATA.fg;
+      this._terminal.curAttrData.bg = DEFAULT_ATTR_DATA.bg;
+      return;
+    }
+
+    const l = params.length;
+    let p;
+    const attr = this._terminal.curAttrData;
+
+    for (let i = 0; i < l; i++) {
+      p = params.params[i];
+      if (p >= 30 && p <= 37) {
+        // fg color 8
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.fg |= Attributes.CM_P16 | (p - 30);
+      } else if (p >= 40 && p <= 47) {
+        // bg color 8
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.bg |= Attributes.CM_P16 | (p - 40);
+      } else if (p >= 90 && p <= 97) {
+        // fg color 16
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.fg |= Attributes.CM_P16 | (p - 90) | 8;
+      } else if (p >= 100 && p <= 107) {
+        // bg color 16
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
+        attr.bg |= Attributes.CM_P16 | (p - 100) | 8;
+      } else if (p === 0) {
+        // default
+        attr.fg = DEFAULT_ATTR_DATA.fg;
+        attr.bg = DEFAULT_ATTR_DATA.bg;
+      } else if (p === 1) {
+        // bold text
+        attr.fg |= FgFlags.BOLD;
+      } else if (p === 3) {
+        // italic text
+        attr.bg |= BgFlags.ITALIC;
+      } else if (p === 4) {
+        // underlined text
+        attr.fg |= FgFlags.UNDERLINE;
+      } else if (p === 5) {
+        // blink
+        attr.fg |= FgFlags.BLINK;
+      } else if (p === 7) {
+        // inverse and positive
+        // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
+        attr.fg |= FgFlags.INVERSE;
+      } else if (p === 8) {
+        // invisible
+        attr.fg |= FgFlags.INVISIBLE;
+      } else if (p === 2) {
+        // dimmed text
+        attr.bg |= BgFlags.DIM;
+      } else if (p === 22) {
+        // not bold nor faint
+        attr.fg &= ~FgFlags.BOLD;
+        attr.bg &= ~BgFlags.DIM;
+      } else if (p === 23) {
+        // not italic
+        attr.bg &= ~BgFlags.ITALIC;
+      } else if (p === 24) {
+        // not underlined
+        attr.fg &= ~FgFlags.UNDERLINE;
+      } else if (p === 25) {
+        // not blink
+        attr.fg &= ~FgFlags.BLINK;
+      } else if (p === 27) {
+        // not inverse
+        attr.fg &= ~FgFlags.INVERSE;
+      } else if (p === 28) {
+        // not invisible
+        attr.fg &= ~FgFlags.INVISIBLE;
+      } else if (p === 39) {
+        // reset fg
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+      } else if (p === 49) {
+        // reset bg
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+      } else if (p === 38 || p === 48) {
+        // fg color 256 and RGB
+        i += this._extractColor(params, i, attr);
+      } else if (p === 100) {
+        // reset fg/bg
+        attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+        attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
+        attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
+      } else {
+        this._logService.debug('Unknown SGR attribute: %d.', p);
+      }
+    }
+  }
+
+  /**
+   * CSI Ps n  Device Status Report (DSR).
+   *     Ps = 5  -> Status Report.  Result (``OK'') is
+   *   CSI 0 n
+   *     Ps = 6  -> Report Cursor Position (CPR) [row;column].
+   *   Result is
+   *   CSI r ; c R
+   * CSI ? Ps n
+   *   Device Status Report (DSR, DEC-specific).
+   *     Ps = 6  -> Report Cursor Position (CPR) [row;column] as CSI
+   *     ? r ; c R (assumes page is zero).
+   *     Ps = 1 5  -> Report Printer status as CSI ? 1 0  n  (ready).
+   *     or CSI ? 1 1  n  (not ready).
+   *     Ps = 2 5  -> Report UDK status as CSI ? 2 0  n  (unlocked)
+   *     or CSI ? 2 1  n  (locked).
+   *     Ps = 2 6  -> Report Keyboard status as
+   *   CSI ? 2 7  ;  1  ;  0  ;  0  n  (North American).
+   *   The last two parameters apply to VT400 & up, and denote key-
+   *   board ready and LK01 respectively.
+   *     Ps = 5 3  -> Report Locator status as
+   *   CSI ? 5 3  n  Locator available, if compiled-in, or
+   *   CSI ? 5 0  n  No Locator, if not.
+   */
+  public deviceStatus(params: IParams): void {
+    switch (params.params[0]) {
+      case 5:
+        // status report
+        this._coreService.triggerDataEvent(`${C0.ESC}[0n`);
+        break;
+      case 6:
+        // cursor position
+        const y = this._bufferService.buffer.y + 1;
+        const x = this._bufferService.buffer.x + 1;
+        this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);
+        break;
+    }
+  }
+
+  public deviceStatusPrivate(params: IParams): void {
+    // modern xterm doesnt seem to
+    // respond to any of these except ?6, 6, and 5
+    switch (params.params[0]) {
+      case 6:
+        // cursor position
+        const y = this._bufferService.buffer.y + 1;
+        const x = this._bufferService.buffer.x + 1;
+        this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);
+        break;
+      case 15:
+        // no printer
+        // this.handler(C0.ESC + '[?11n');
+        break;
+      case 25:
+        // dont support user defined keys
+        // this.handler(C0.ESC + '[?21n');
+        break;
+      case 26:
+        // north american keyboard
+        // this.handler(C0.ESC + '[?27;1;0;0n');
+        break;
+      case 53:
+        // no dec locator/mouse
+        // this.handler(C0.ESC + '[?50n');
+        break;
+    }
+  }
+
+  /**
+   * CSI ! p   Soft terminal reset (DECSTR).
+   * http://vt100.net/docs/vt220-rm/table4-10.html
+   */
+  public softReset(params: IParams): void {
+    this._terminal.cursorHidden = false;
+    this._terminal.insertMode = false;
+    this._terminal.originMode = false;
+    this._terminal.wraparoundMode = true;  // defaults: xterm - true, vt100 - false
+    this._terminal.applicationKeypad = false; // ?
+    if (this._terminal.viewport) {
+      this._terminal.viewport.syncScrollArea();
+    }
+    this._coreService.decPrivateModes.applicationCursorKeys = false;
+    this._bufferService.buffer.scrollTop = 0;
+    this._bufferService.buffer.scrollBottom = this._bufferService.rows - 1;
+    this._terminal.curAttrData = DEFAULT_ATTR_DATA.clone();
+    this._bufferService.buffer.x = this._bufferService.buffer.y = 0; // ?
+    this._terminal.charset = null;
+    this._terminal.glevel = 0; // ??
+    this._terminal.charsets = [null]; // ??
+  }
+
+  /**
+   * CSI Ps SP q  Set cursor style (DECSCUSR, VT520).
+   *   Ps = 0  -> blinking block.
+   *   Ps = 1  -> blinking block (default).
+   *   Ps = 2  -> steady block.
+   *   Ps = 3  -> blinking underline.
+   *   Ps = 4  -> steady underline.
+   *   Ps = 5  -> blinking bar (xterm).
+   *   Ps = 6  -> steady bar (xterm).
+   */
+  public setCursorStyle(params: IParams): void {
+    const param = params.params[0] || 1;
+    switch (param) {
+      case 1:
+      case 2:
+        this._optionsService.options.cursorStyle = 'block';
+        break;
+      case 3:
+      case 4:
+        this._optionsService.options.cursorStyle = 'underline';
+        break;
+      case 5:
+      case 6:
+        this._optionsService.options.cursorStyle = 'bar';
+        break;
+    }
+    const isBlinking = param % 2 === 1;
+    this._optionsService.options.cursorBlink = isBlinking;
+  }
+
+  /**
+   * CSI Ps ; Ps r
+   *   Set Scrolling Region [top;bottom] (default = full size of win-
+   *   dow) (DECSTBM).
+   */
+  public setScrollRegion(params: IParams): void {
+    const top = params.params[0] || 1;
+    let bottom: number;
+
+    if (params.length < 2 || (bottom = params.params[1]) >  this._bufferService.rows || bottom === 0) {
+      bottom = this._bufferService.rows;
+    }
+
+    if (bottom > top) {
+      this._bufferService.buffer.scrollTop = top - 1;
+      this._bufferService.buffer.scrollBottom = bottom - 1;
+      this._setCursor(0, 0);
+    }
+  }
+
+
+  /**
+   * CSI s
+   * ESC 7
+   *   Save cursor (ANSI.SYS).
+   */
+  public saveCursor(params?: IParams): void {
+    this._bufferService.buffer.savedX = this._bufferService.buffer.x;
+    this._bufferService.buffer.savedY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;
+    this._bufferService.buffer.savedCurAttrData.fg = this._terminal.curAttrData.fg;
+    this._bufferService.buffer.savedCurAttrData.bg = this._terminal.curAttrData.bg;
+    this._bufferService.buffer.savedCharset = this._terminal.charset;
+  }
+
+
+  /**
+   * CSI u
+   * ESC 8
+   *   Restore cursor (ANSI.SYS).
+   */
+  public restoreCursor(params?: IParams): void {
+    this._bufferService.buffer.x = this._bufferService.buffer.savedX || 0;
+    this._bufferService.buffer.y = Math.max(this._bufferService.buffer.savedY - this._bufferService.buffer.ybase, 0);
+    this._terminal.curAttrData.fg = this._bufferService.buffer.savedCurAttrData.fg;
+    this._terminal.curAttrData.bg = this._bufferService.buffer.savedCurAttrData.bg;
+    this._terminal.charset = (this as any)._savedCharset;
+    if (this._bufferService.buffer.savedCharset) {
+      this._terminal.charset = this._bufferService.buffer.savedCharset;
+    }
+    this._restrictCursor();
+  }
+
+
+  /**
+   * OSC 0; <data> ST (set icon name + window title)
+   * OSC 2; <data> ST (set window title)
+   *   Proxy to set window title. Icon name is not supported.
+   */
+  public setTitle(data: string): void {
+    this._terminal.handleTitle(data);
+  }
+
+  /**
+   * ESC E
+   * C1.NEL
+   *   DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)
+   *   Moves cursor to first position on next line.
+   */
+  public nextLine(): void {
+    this._bufferService.buffer.x = 0;
+    this.index();
+  }
+
+  /**
+   * ESC =
+   *   DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)
+   *   Enables the numeric keypad to send application sequences to the host.
+   */
+  public keypadApplicationMode(): void {
+    this._logService.debug('Serial port requested application keypad.');
+    this._terminal.applicationKeypad = true;
+    if (this._terminal.viewport) {
+      this._terminal.viewport.syncScrollArea();
+    }
+  }
+
+  /**
+   * ESC >
+   *   DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)
+   *   Enables the keypad to send numeric characters to the host.
+   */
+  public keypadNumericMode(): void {
+    this._logService.debug('Switching back to normal keypad.');
+    this._terminal.applicationKeypad = false;
+    if (this._terminal.viewport) {
+      this._terminal.viewport.syncScrollArea();
+    }
+  }
+
+  /**
+   * ESC % @
+   * ESC % G
+   *   Select default character set. UTF-8 is not supported (string are unicode anyways)
+   *   therefore ESC % G does the same.
+   */
+  public selectDefaultCharset(): void {
+    this._terminal.setgLevel(0);
+    this._terminal.setgCharset(0, DEFAULT_CHARSET); // US (default)
+  }
+
+  /**
+   * ESC ( C
+   *   Designate G0 Character Set, VT100, ISO 2022.
+   * ESC ) C
+   *   Designate G1 Character Set (ISO 2022, VT100).
+   * ESC * C
+   *   Designate G2 Character Set (ISO 2022, VT220).
+   * ESC + C
+   *   Designate G3 Character Set (ISO 2022, VT220).
+   * ESC - C
+   *   Designate G1 Character Set (VT300).
+   * ESC . C
+   *   Designate G2 Character Set (VT300).
+   * ESC / C
+   *   Designate G3 Character Set (VT300). C = A  -> ISO Latin-1 Supplemental. - Supported?
+   */
+  public selectCharset(collectAndFlag: string): void {
+    if (collectAndFlag.length !== 2) {
+      this.selectDefaultCharset();
+      return;
+    }
+    if (collectAndFlag[0] === '/') {
+      return;  // TODO: Is this supported?
+    }
+    this._terminal.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);
+    return;
+  }
+
+  /**
+   * ESC D
+   * C1.IND
+   *   DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)
+   *   Moves the cursor down one line in the same column.
+   */
+  public index(): void {
+    this._restrictCursor();
+    const buffer = this._bufferService.buffer;
+    this._bufferService.buffer.y++;
+    if (buffer.y === buffer.scrollBottom + 1) {
+      buffer.y--;
+      this._terminal.scroll();
+    } else if (buffer.y >= this._bufferService.rows) {
+      buffer.y = this._bufferService.rows - 1;
+    }
+    this._restrictCursor();
+  }
+
+  /**
+   * ESC H
+   * C1.HTS
+   *   DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)
+   *   Sets a horizontal tab stop at the column position indicated by
+   *   the value of the active column when the terminal receives an HTS.
+   */
+  public tabSet(): void {
+    this._bufferService.buffer.tabs[this._bufferService.buffer.x] = true;
+  }
+
+  /**
+   * ESC M
+   * C1.RI
+   *   DEC mnemonic: HTS
+   *   Moves the cursor up one line in the same column. If the cursor is at the top margin,
+   *   the page scrolls down.
+   */
+  public reverseIndex(): void {
+    this._restrictCursor();
+    const buffer = this._bufferService.buffer;
+    if (buffer.y === buffer.scrollTop) {
+      // possibly move the code below to term.reverseScroll();
+      // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
+      // blankLine(true) is xterm/linux behavior
+      const scrollRegionHeight = buffer.scrollBottom - buffer.scrollTop;
+      buffer.lines.shiftElements(buffer.y + buffer.ybase, scrollRegionHeight, 1);
+      buffer.lines.set(buffer.y + buffer.ybase, buffer.getBlankLine(this._terminal.eraseAttrData()));
+      this._dirtyRowService.markRangeDirty(buffer.scrollTop, buffer.scrollBottom);
+    } else {
+      buffer.y--;
+      this._restrictCursor(); // quickfix to not run out of bounds
+    }
+  }
+
+  /**
+   * ESC c
+   *   DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)
+   *   Reset to initial state.
+   */
+  public reset(): void {
+    this._parser.reset();
+    this._terminal.reset();  // TODO: save to move from terminal?
+  }
+
+  /**
+   * ESC n
+   * ESC o
+   * ESC |
+   * ESC }
+   * ESC ~
+   *   DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)
+   *   When you use a locking shift, the character set remains in GL or GR until
+   *   you use another locking shift. (partly supported)
+   */
+  public setgLevel(level: number): void {
+    this._terminal.setgLevel(level);  // TODO: save to move from terminal?
+  }
+
+  /**
+   * ESC # 8
+   *   DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)
+   *   This control function fills the complete screen area with
+   *   a test pattern (E) used for adjusting screen alignment.
+   *
+   * TODO: move DECALN into compat addon
+   */
+  public screenAlignmentPattern(): void {
+    // prepare cell data
+    const cell = new CellData();
+    cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);
+    cell.fg = this._terminal.curAttrData.fg;
+    cell.bg = this._terminal.curAttrData.bg;
+
+    const buffer = this._bufferService.buffer;
+
+    this._setCursor(0, 0);
+    for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {
+      const row = buffer.y + buffer.ybase + yOffset;
+      buffer.lines.get(row).fill(cell);
+      buffer.lines.get(row).isWrapped = false;
+    }
+    this._dirtyRowService.markAllDirty();
+    this._setCursor(0, 0);
+  }
+}
diff --git a/node_modules/xterm/src/Terminal.ts b/node_modules/xterm/src/Terminal.ts
new file mode 100644 (file)
index 0000000..3e7e55c
--- /dev/null
@@ -0,0 +1,1610 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * @license MIT
+ *
+ * Originally forked from (with the author's permission):
+ *   Fabrice Bellard's javascript vt100 for jslinux:
+ *   http://bellard.org/jslinux/
+ *   Copyright (c) 2011 Fabrice Bellard
+ *   The original design remains. The terminal itself
+ *   has been extended to include xterm CSI codes, among
+ *   other features.
+ *
+ * Terminal Emulation References:
+ *   http://vt100.net/
+ *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
+ *   http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+ *   http://invisible-island.net/vttest/
+ *   http://www.inwap.com/pdp10/ansicode.txt
+ *   http://linux.die.net/man/4/console_codes
+ *   http://linux.die.net/man/7/urxvt
+ */
+
+import { IInputHandlingTerminal, ICompositionHelper, ITerminalOptions, ITerminal, IBrowser, CustomKeyEventHandler } from './Types';
+import { IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { CompositionHelper } from 'browser/input/CompositionHelper';
+import { Viewport } from 'browser/Viewport';
+import { rightClickHandler, moveTextAreaUnderMouseCursor, handlePasteEvent, copyHandler, paste } from 'browser/Clipboard';
+import { C0 } from 'common/data/EscapeSequences';
+import { InputHandler } from './InputHandler';
+import { Renderer } from './renderer/Renderer';
+import { Linkifier } from 'browser/Linkifier';
+import { SelectionService } from 'browser/services/SelectionService';
+import * as Browser from 'common/Platform';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import * as Strings from 'browser/LocalizableStrings';
+import { SoundService } from 'browser/services/SoundService';
+import { MouseZoneManager } from 'browser/MouseZoneManager';
+import { AccessibilityManager } from './AccessibilityManager';
+import { ITheme, IMarker, IDisposable, ISelectionPosition } from 'xterm';
+import { DomRenderer } from './renderer/dom/DomRenderer';
+import { IKeyboardEvent, KeyboardResultType, ICharset, IBufferLine, IAttributeData, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';
+import { evaluateKeyboardEvent } from 'common/input/Keyboard';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+import { applyWindowsMode } from './WindowsMode';
+import { ColorManager } from 'browser/ColorManager';
+import { RenderService } from 'browser/services/RenderService';
+import { IOptionsService, IBufferService, ICoreMouseService, ICoreService, ILogService, IDirtyRowService, IInstantiationService } from 'common/services/Services';
+import { OptionsService } from 'common/services/OptionsService';
+import { ICharSizeService, IRenderService, IMouseService, ISelectionService, ISoundService } from 'browser/services/Services';
+import { CharSizeService } from 'browser/services/CharSizeService';
+import { BufferService, MINIMUM_COLS, MINIMUM_ROWS } from 'common/services/BufferService';
+import { Disposable } from 'common/Lifecycle';
+import { IBufferSet, IBuffer } from 'common/buffer/Types';
+import { Attributes } from 'common/buffer/Constants';
+import { MouseService } from 'browser/services/MouseService';
+import { IParams, IFunctionIdentifier } from 'common/parser/Types';
+import { CoreService } from 'common/services/CoreService';
+import { LogService } from 'common/services/LogService';
+import { ILinkifier, IMouseZoneManager, LinkMatcherHandler, ILinkMatcherOptions, IViewport } from 'browser/Types';
+import { DirtyRowService } from 'common/services/DirtyRowService';
+import { InstantiationService } from 'common/services/InstantiationService';
+import { CoreMouseService } from 'common/services/CoreMouseService';
+import { WriteBuffer } from 'common/input/WriteBuffer';
+
+// Let it work inside Node.js for automated testing purposes.
+const document = (typeof window !== 'undefined') ? window.document : null;
+
+
+export class Terminal extends Disposable implements ITerminal, IDisposable, IInputHandlingTerminal {
+  public textarea: HTMLTextAreaElement;
+  public element: HTMLElement;
+  public screenElement: HTMLElement;
+
+  /**
+   * The HTMLElement that the terminal is created in, set by Terminal.open.
+   */
+  private _parent: HTMLElement | null;
+  private _document: Document;
+  private _viewportScrollArea: HTMLElement;
+  private _viewportElement: HTMLElement;
+  private _helperContainer: HTMLElement;
+  private _compositionView: HTMLElement;
+
+  private _visualBellTimer: number;
+
+  public browser: IBrowser = <any>Browser;
+
+  // TODO: We should remove options once components adopt optionsService
+  public get options(): ITerminalOptions { return this.optionsService.options; }
+
+  // TODO: This can be changed to an enum or boolean, 0 and 1 seem to be the only options
+  public cursorState: number;
+  public cursorHidden: boolean;
+
+  private _customKeyEventHandler: CustomKeyEventHandler;
+
+  // common services
+  private _bufferService: IBufferService;
+  private _coreService: ICoreService;
+  private _coreMouseService: ICoreMouseService;
+  private _dirtyRowService: IDirtyRowService;
+  private _instantiationService: IInstantiationService;
+  private _logService: ILogService;
+  public optionsService: IOptionsService;
+
+  // browser services
+  private _charSizeService: ICharSizeService;
+  private _mouseService: IMouseService;
+  private _renderService: IRenderService;
+  private _selectionService: ISelectionService;
+  private _soundService: ISoundService;
+
+  // modes
+  public applicationKeypad: boolean;
+  public originMode: boolean;
+  public insertMode: boolean;
+  public wraparoundMode: boolean; // defaults: xterm - true, vt100 - false
+  public bracketedPasteMode: boolean;
+
+  // charset
+  // The current charset
+  public charset: ICharset;
+  public gcharset: number;
+  public glevel: number;
+  public charsets: ICharset[];
+
+  // mouse properties
+  public mouseEvents: CoreMouseEventType = CoreMouseEventType.NONE;
+  public sendFocus: boolean;
+
+  // misc
+  public savedCols: number;
+
+  public curAttrData: IAttributeData;
+  private _eraseAttrData: IAttributeData;
+
+  public params: (string | number)[];
+  public currentParam: string | number;
+
+  // write buffer
+  private _writeBuffer: WriteBuffer;
+
+  // Store if user went browsing history in scrollback
+  private _userScrolling: boolean;
+
+  /**
+   * Records whether the keydown event has already been handled and triggered a data event, if so
+   * the keypress event should not trigger a data event but should still print to the textarea so
+   * screen readers will announce it.
+   */
+  private _keyDownHandled: boolean = false;
+
+  private _inputHandler: InputHandler;
+  public linkifier: ILinkifier;
+  public viewport: IViewport;
+  private _compositionHelper: ICompositionHelper;
+  private _mouseZoneManager: IMouseZoneManager;
+  private _accessibilityManager: AccessibilityManager;
+  private _colorManager: ColorManager;
+  private _theme: ITheme;
+  private _windowsMode: IDisposable | undefined;
+
+  // bufferline to clone/copy from for new blank lines
+  private _blankLine: IBufferLine = null;
+
+  public get cols(): number { return this._bufferService.cols; }
+  public get rows(): number { return this._bufferService.rows; }
+
+  private _onCursorMove = new EventEmitter<void>();
+  public get onCursorMove(): IEvent<void> { return this._onCursorMove.event; }
+  private _onData = new EventEmitter<string>();
+  public get onData(): IEvent<string> { return this._onData.event; }
+  private _onKey = new EventEmitter<{ key: string, domEvent: KeyboardEvent }>();
+  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._onKey.event; }
+  private _onLineFeed = new EventEmitter<void>();
+  public get onLineFeed(): IEvent<void> { return this._onLineFeed.event; }
+  private _onRender = new EventEmitter<{ start: number, end: number }>();
+  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }
+  private _onResize = new EventEmitter<{ cols: number, rows: number }>();
+  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._onResize.event; }
+  private _onScroll = new EventEmitter<number>();
+  public get onScroll(): IEvent<number> { return this._onScroll.event; }
+  private _onSelectionChange = new EventEmitter<void>();
+  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }
+  private _onTitleChange = new EventEmitter<string>();
+  public get onTitleChange(): IEvent<string> { return this._onTitleChange.event; }
+
+  private _onFocus = new EventEmitter<void>();
+  public get onFocus(): IEvent<void> { return this._onFocus.event; }
+  private _onBlur = new EventEmitter<void>();
+  public get onBlur(): IEvent<void> { return this._onBlur.event; }
+  public onA11yCharEmitter = new EventEmitter<string>();
+  public get onA11yChar(): IEvent<string> { return this.onA11yCharEmitter.event; }
+  public onA11yTabEmitter = new EventEmitter<number>();
+  public get onA11yTab(): IEvent<number> { return this.onA11yTabEmitter.event; }
+
+  /**
+   * Creates a new `Terminal` object.
+   *
+   * @param options An object containing a set of options, the available options are:
+   *   - `cursorBlink` (boolean): Whether the terminal cursor blinks
+   *   - `cols` (number): The number of columns of the terminal (horizontal size)
+   *   - `rows` (number): The number of rows of the terminal (vertical size)
+   *
+   * @public
+   * @class Xterm Xterm
+   * @alias module:xterm/src/xterm
+   */
+  constructor(
+    options: ITerminalOptions = {}
+  ) {
+    super();
+
+    // Setup and initialize common services
+    this._instantiationService = new InstantiationService();
+    this.optionsService = new OptionsService(options);
+    this._instantiationService.setService(IOptionsService, this.optionsService);
+    this._bufferService = this._instantiationService.createInstance(BufferService);
+    this._instantiationService.setService(IBufferService, this._bufferService);
+    this._logService = this._instantiationService.createInstance(LogService);
+    this._instantiationService.setService(ILogService, this._logService);
+    this._coreService = this._instantiationService.createInstance(CoreService, () => this.scrollToBottom());
+    this._instantiationService.setService(ICoreService, this._coreService);
+    this._coreService.onData(e => this._onData.fire(e));
+    this._coreMouseService = this._instantiationService.createInstance(CoreMouseService);
+    this._instantiationService.setService(ICoreMouseService, this._coreMouseService);
+    this._dirtyRowService = this._instantiationService.createInstance(DirtyRowService);
+    this._instantiationService.setService(IDirtyRowService, this._dirtyRowService);
+
+    this._setupOptionsListeners();
+    this._setup();
+
+    this._writeBuffer = new WriteBuffer(data => this._inputHandler.parse(data));
+  }
+
+  public dispose(): void {
+    if (this._isDisposed) {
+      return;
+    }
+    super.dispose();
+    if (this._windowsMode) {
+      this._windowsMode.dispose();
+      this._windowsMode = undefined;
+    }
+    if (this._renderService) {
+      this._renderService.dispose();
+    }
+    this._customKeyEventHandler = null;
+    this.write = () => {};
+    if (this.element && this.element.parentNode) {
+      this.element.parentNode.removeChild(this.element);
+    }
+  }
+
+  private _setup(): void {
+    this._parent = document ? document.body : null;
+
+    this.cursorState = 0;
+    this.cursorHidden = false;
+    this._customKeyEventHandler = null;
+
+    // modes
+    this.applicationKeypad = false;
+    this.originMode = false;
+    this.insertMode = false;
+    this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
+    this.bracketedPasteMode = false;
+
+    // charset
+    this.charset = null;
+    this.gcharset = null;
+    this.glevel = 0;
+    // TODO: Can this be just []?
+    this.charsets = [null];
+
+    this.curAttrData = DEFAULT_ATTR_DATA.clone();
+    this._eraseAttrData = DEFAULT_ATTR_DATA.clone();
+
+    this.params = [];
+    this.currentParam = 0;
+
+    this._userScrolling = false;
+
+    // Register input handler and refire/handle events
+    this._inputHandler = new InputHandler(this, this._bufferService, this._coreService, this._dirtyRowService, this._logService, this.optionsService, this._coreMouseService);
+    this._inputHandler.onCursorMove(() => this._onCursorMove.fire());
+    this._inputHandler.onLineFeed(() => this._onLineFeed.fire());
+    this.register(this._inputHandler);
+
+    this.linkifier = this.linkifier || new Linkifier(this._bufferService, this._logService);
+
+    if (this.options.windowsMode) {
+      this._windowsMode = applyWindowsMode(this);
+    }
+  }
+
+  /**
+   * Convenience property to active buffer.
+   */
+  public get buffer(): IBuffer {
+    return this.buffers.active;
+  }
+
+  public get buffers(): IBufferSet {
+    return this._bufferService.buffers;
+  }
+
+  /**
+   * back_color_erase feature for xterm.
+   */
+  public eraseAttrData(): IAttributeData {
+    this._eraseAttrData.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);
+    this._eraseAttrData.bg |= this.curAttrData.bg & ~0xFC000000;
+    return this._eraseAttrData;
+  }
+
+  /**
+   * Focus the terminal. Delegates focus handling to the terminal's DOM element.
+   */
+  public focus(): void {
+    if (this.textarea) {
+      this.textarea.focus({ preventScroll: true });
+    }
+  }
+
+  public get isFocused(): boolean {
+    return document.activeElement === this.textarea && document.hasFocus();
+  }
+
+  private _setupOptionsListeners(): void {
+    // TODO: These listeners should be owned by individual components
+    this.optionsService.onOptionChange(key => {
+      switch (key) {
+        case 'fontFamily':
+        case 'fontSize':
+          // When the font changes the size of the cells may change which requires a renderer clear
+          if (this._renderService) {
+            this._renderService.clear();
+          }
+          if (this._charSizeService) {
+            this._charSizeService.measure();
+          }
+          break;
+        case 'drawBoldTextInBrightColors':
+        case 'letterSpacing':
+        case 'lineHeight':
+        case 'fontWeight':
+        case 'fontWeightBold':
+          // When the font changes the size of the cells may change which requires a renderer clear
+          if (this._renderService) {
+            this._renderService.clear();
+            this._renderService.onResize(this.cols, this.rows);
+            this.refresh(0, this.rows - 1);
+          }
+          break;
+        case 'rendererType':
+          if (this._renderService) {
+            this._renderService.setRenderer(this._createRenderer());
+            this._renderService.onResize(this.cols, this.rows);
+          }
+          break;
+        case 'scrollback':
+          this.buffers.resize(this.cols, this.rows);
+          if (this.viewport) {
+            this.viewport.syncScrollArea();
+          }
+          break;
+        case 'screenReaderMode':
+          if (this.optionsService.options.screenReaderMode) {
+            if (!this._accessibilityManager && this._renderService) {
+              this._accessibilityManager = new AccessibilityManager(this, this._renderService);
+            }
+          } else {
+            if (this._accessibilityManager) {
+              this._accessibilityManager.dispose();
+              this._accessibilityManager = null;
+            }
+          }
+          break;
+        case 'tabStopWidth': this.buffers.setupTabStops(); break;
+        case 'theme':
+          this._setTheme(this.optionsService.options.theme);
+          break;
+        case 'windowsMode':
+          if (this.optionsService.options.windowsMode) {
+            if (!this._windowsMode) {
+              this._windowsMode = applyWindowsMode(this);
+            }
+          } else {
+            if (this._windowsMode) {
+              this._windowsMode.dispose();
+              this._windowsMode = undefined;
+            }
+          }
+          break;
+      }
+    });
+  }
+
+  /**
+   * Binds the desired focus behavior on a given terminal object.
+   */
+  private _onTextAreaFocus(ev: KeyboardEvent): void {
+    if (this.sendFocus) {
+      this._coreService.triggerDataEvent(C0.ESC + '[I');
+    }
+    this.updateCursorStyle(ev);
+    this.element.classList.add('focus');
+    this.showCursor();
+    this._onFocus.fire();
+  }
+
+  /**
+   * Blur the terminal, calling the blur function on the terminal's underlying
+   * textarea.
+   */
+  public blur(): void {
+    return this.textarea.blur();
+  }
+
+  /**
+   * Binds the desired blur behavior on a given terminal object.
+   */
+  private _onTextAreaBlur(): void {
+    // Text can safely be removed on blur. Doing it earlier could interfere with
+    // screen readers reading it out.
+    this.textarea.value = '';
+    this.refresh(this.buffer.y, this.buffer.y);
+    if (this.sendFocus) {
+      this._coreService.triggerDataEvent(C0.ESC + '[O');
+    }
+    this.element.classList.remove('focus');
+    this._onBlur.fire();
+  }
+
+  /**
+   * Initialize default behavior
+   */
+  private _initGlobal(): void {
+    this._bindKeys();
+
+    // Bind clipboard functionality
+    this.register(addDisposableDomListener(this.element, 'copy', (event: ClipboardEvent) => {
+      // If mouse events are active it means the selection manager is disabled and
+      // copy should be handled by the host program.
+      if (!this.hasSelection()) {
+        return;
+      }
+      copyHandler(event, this._selectionService);
+    }));
+    const pasteHandlerWrapper = (event: ClipboardEvent) => handlePasteEvent(event, this.textarea, this.bracketedPasteMode, this._coreService);
+    this.register(addDisposableDomListener(this.textarea, 'paste', pasteHandlerWrapper));
+    this.register(addDisposableDomListener(this.element, 'paste', pasteHandlerWrapper));
+
+    // Handle right click context menus
+    if (Browser.isFirefox) {
+      // Firefox doesn't appear to fire the contextmenu event on right click
+      this.register(addDisposableDomListener(this.element, 'mousedown', (event: MouseEvent) => {
+        if (event.button === 2) {
+          rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);
+        }
+      }));
+    } else {
+      this.register(addDisposableDomListener(this.element, 'contextmenu', (event: MouseEvent) => {
+        rightClickHandler(event, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord);
+      }));
+    }
+
+    // Move the textarea under the cursor when middle clicking on Linux to ensure
+    // middle click to paste selection works. This only appears to work in Chrome
+    // at the time is writing.
+    if (Browser.isLinux) {
+      // Use auxclick event over mousedown the latter doesn't seem to work. Note
+      // that the regular click event doesn't fire for the middle mouse button.
+      this.register(addDisposableDomListener(this.element, 'auxclick', (event: MouseEvent) => {
+        if (event.button === 1) {
+          moveTextAreaUnderMouseCursor(event, this.textarea, this.screenElement);
+        }
+      }));
+    }
+  }
+
+  /**
+   * Apply key handling to the terminal
+   */
+  private _bindKeys(): void {
+    this.register(addDisposableDomListener(this.textarea, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));
+    this.register(addDisposableDomListener(this.textarea, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));
+    this.register(addDisposableDomListener(this.textarea, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));
+    this.register(addDisposableDomListener(this.textarea, 'compositionstart', () => this._compositionHelper.compositionstart()));
+    this.register(addDisposableDomListener(this.textarea, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper.compositionupdate(e)));
+    this.register(addDisposableDomListener(this.textarea, 'compositionend', () => this._compositionHelper.compositionend()));
+    this.register(this.onRender(() => this._compositionHelper.updateCompositionElements()));
+    this.register(this.onRender(e => this._queueLinkification(e.start, e.end)));
+  }
+
+  /**
+   * Opens the terminal within an element.
+   *
+   * @param parent The element to create the terminal within.
+   */
+  public open(parent: HTMLElement): void {
+    this._parent = parent || this._parent;
+
+    if (!this._parent) {
+      throw new Error('Terminal requires a parent element.');
+    }
+
+    if (!document.body.contains(parent)) {
+      this._logService.warn('Terminal.open was called on an element that was not attached to the DOM');
+    }
+
+    this._document = this._parent.ownerDocument;
+
+    // Create main element container
+    this.element = this._document.createElement('div');
+    this.element.dir = 'ltr';   // xterm.css assumes LTR
+    this.element.classList.add('terminal');
+    this.element.classList.add('xterm');
+    this.element.setAttribute('tabindex', '0');
+    this._parent.appendChild(this.element);
+
+    // Performance: Use a document fragment to build the terminal
+    // viewport and helper elements detached from the DOM
+    const fragment = document.createDocumentFragment();
+    this._viewportElement = document.createElement('div');
+    this._viewportElement.classList.add('xterm-viewport');
+    fragment.appendChild(this._viewportElement);
+    this._viewportScrollArea = document.createElement('div');
+    this._viewportScrollArea.classList.add('xterm-scroll-area');
+    this._viewportElement.appendChild(this._viewportScrollArea);
+
+    this.screenElement = document.createElement('div');
+    this.screenElement.classList.add('xterm-screen');
+    // Create the container that will hold helpers like the textarea for
+    // capturing DOM Events. Then produce the helpers.
+    this._helperContainer = document.createElement('div');
+    this._helperContainer.classList.add('xterm-helpers');
+    this.screenElement.appendChild(this._helperContainer);
+    fragment.appendChild(this.screenElement);
+
+    this.textarea = document.createElement('textarea');
+    this.textarea.classList.add('xterm-helper-textarea');
+    this.textarea.setAttribute('aria-label', Strings.promptLabel);
+    this.textarea.setAttribute('aria-multiline', 'false');
+    this.textarea.setAttribute('autocorrect', 'off');
+    this.textarea.setAttribute('autocapitalize', 'off');
+    this.textarea.setAttribute('spellcheck', 'false');
+    this.textarea.tabIndex = 0;
+    this.register(addDisposableDomListener(this.textarea, 'focus', (ev: KeyboardEvent) => this._onTextAreaFocus(ev)));
+    this.register(addDisposableDomListener(this.textarea, 'blur', () => this._onTextAreaBlur()));
+    this._helperContainer.appendChild(this.textarea);
+
+    this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);
+    this._instantiationService.setService(ICharSizeService, this._charSizeService);
+
+    this._compositionView = document.createElement('div');
+    this._compositionView.classList.add('composition-view');
+    this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);
+    this._helperContainer.appendChild(this._compositionView);
+
+    // Performance: Add viewport and helper elements from the fragment
+    this.element.appendChild(fragment);
+
+    this._theme = this.options.theme || this._theme;
+    this.options.theme = undefined;
+    this._colorManager = new ColorManager(document, this.options.allowTransparency);
+    this._colorManager.setTheme(this._theme);
+
+    const renderer = this._createRenderer();
+    this._renderService = this._instantiationService.createInstance(RenderService, renderer, this.rows, this.screenElement);
+    this._instantiationService.setService(IRenderService, this._renderService);
+    this._renderService.onRender(e => this._onRender.fire(e));
+    this.onResize(e => this._renderService.resize(e.cols, e.rows));
+
+    this._soundService = this._instantiationService.createInstance(SoundService);
+    this._instantiationService.setService(ISoundService, this._soundService);
+    this._mouseService = this._instantiationService.createInstance(MouseService);
+    this._instantiationService.setService(IMouseService, this._mouseService);
+
+    this.viewport = this._instantiationService.createInstance(Viewport,
+      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),
+      this._viewportElement,
+      this._viewportScrollArea
+    );
+    this.viewport.onThemeChange(this._colorManager.colors);
+    this.register(this.viewport);
+
+    this.register(this.onCursorMove(() => this._renderService.onCursorMove()));
+    this.register(this.onResize(() => this._renderService.onResize(this.cols, this.rows)));
+    this.register(this.onBlur(() => this._renderService.onBlur()));
+    this.register(this.onFocus(() => this._renderService.onFocus()));
+    this.register(this._renderService.onDimensionsChange(() => this.viewport.syncScrollArea()));
+
+    this._selectionService = this._instantiationService.createInstance(SelectionService,
+      (amount: number, suppressEvent: boolean) => this.scrollLines(amount, suppressEvent),
+      this.element,
+      this.screenElement);
+    this._instantiationService.setService(ISelectionService, this._selectionService);
+    this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));
+    this.register(this._selectionService.onRedrawRequest(e => this._renderService.onSelectionChanged(e.start, e.end, e.columnSelectMode)));
+    this.register(this._selectionService.onLinuxMouseSelection(text => {
+      // If there's a new selection, put it into the textarea, focus and select it
+      // in order to register it as a selection on the OS. This event is fired
+      // only on Linux to enable middle click to paste selection.
+      this.textarea.value = text;
+      this.textarea.focus();
+      this.textarea.select();
+    }));
+    this.register(this.onScroll(() => {
+      this.viewport.syncScrollArea();
+      this._selectionService.refresh();
+    }));
+    this.register(addDisposableDomListener(this._viewportElement, 'scroll', () => this._selectionService.refresh()));
+
+    this._mouseZoneManager = this._instantiationService.createInstance(MouseZoneManager, this.element, this.screenElement);
+    this.register(this._mouseZoneManager);
+    this.register(this.onScroll(() => this._mouseZoneManager.clearAll()));
+    this.linkifier.attachToDom(this.element, this._mouseZoneManager);
+
+    // This event listener must be registered aftre MouseZoneManager is created
+    this.register(addDisposableDomListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService.onMouseDown(e)));
+
+    // apply mouse event classes set by escape codes before terminal was attached
+    if (this.mouseEvents) {
+      this._selectionService.disable();
+      this.element.classList.add('enable-mouse-events');
+    } else {
+      this._selectionService.enable();
+    }
+
+    if (this.options.screenReaderMode) {
+      // Note that this must be done *after* the renderer is created in order to
+      // ensure the correct order of the dprchange event
+      this._accessibilityManager = new AccessibilityManager(this, this._renderService);
+    }
+
+    // Measure the character size
+    this._charSizeService.measure();
+
+    // Setup loop that draws to screen
+    this.refresh(0, this.rows - 1);
+
+    // Initialize global actions that need to be taken on the document.
+    this._initGlobal();
+
+    // Listen for mouse events and translate
+    // them into terminal mouse protocols.
+    this.bindMouse();
+  }
+
+  private _createRenderer(): IRenderer {
+    switch (this.options.rendererType) {
+      case 'canvas': return new Renderer(this._colorManager.colors, this, this._bufferService, this._charSizeService, this.optionsService);
+      case 'dom': return new DomRenderer(this, this._colorManager.colors, this._charSizeService, this.optionsService);
+      default: throw new Error(`Unrecognized rendererType "${this.options.rendererType}"`);
+    }
+  }
+
+  /**
+   * Sets the theme on the renderer. The renderer must have been initialized.
+   * @param theme The theme to set.
+   */
+  private _setTheme(theme: ITheme): void {
+    this._theme = theme;
+    if (this._colorManager) {
+      this._colorManager.setTheme(theme);
+    }
+    if (this._renderService) {
+      this._renderService.setColors(this._colorManager.colors);
+    }
+    if (this.viewport) {
+      this.viewport.onThemeChange(this._colorManager.colors);
+    }
+  }
+
+  /**
+   * Bind certain mouse events to the terminal.
+   * By default only 3 button + wheel up/down is ativated. For higher buttons
+   * no mouse report will be created. Typically the standard actions will be active.
+   *
+   * There are several reasons not to enable support for higher buttons/wheel:
+   * - Button 4 and 5 are typically used for history back and forward navigation,
+   *   there is no straight forward way to supress/intercept those standard actions.
+   * - Support for higher buttons does not work in some platform/browser combinations.
+   * - Left/right wheel was not tested.
+   * - Emulators vary in mouse button support, typically only 3 buttons and
+   *   wheel up/down work reliable.
+   *
+   * TODO: Move mouse event code into its own file.
+   */
+  public bindMouse(): void {
+    const self = this;
+    const el = this.element;
+
+    // send event to CoreMouseService
+    function sendEvent(ev: MouseEvent | WheelEvent): boolean {
+      let pos;
+
+      // get mouse coordinates
+      pos = self._mouseService.getRawByteCoords(ev, self.screenElement, self.cols, self.rows);
+      if (!pos) {
+        return false;
+      }
+
+      let but: CoreMouseButton;
+      let action: CoreMouseAction;
+      switch ((<any>ev).overrideType || ev.type) {
+        case 'mousemove':
+          action = CoreMouseAction.MOVE;
+          if (ev.buttons === undefined) {
+            // buttons is not supported on macOS, try to get a value from button instead
+            but = CoreMouseButton.NONE;
+            if (ev.button !== undefined) {
+              but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
+            }
+          } else {
+            // according to MDN buttons only reports up to button 5 (AUX2)
+            but = ev.buttons & 1 ? CoreMouseButton.LEFT :
+                  ev.buttons & 4 ? CoreMouseButton.MIDDLE :
+                  ev.buttons & 2 ? CoreMouseButton.RIGHT :
+                  CoreMouseButton.NONE; // fallback to NONE
+          }
+          break;
+        case 'mouseup':
+          action = CoreMouseAction.UP;
+          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
+          break;
+        case 'mousedown':
+          action = CoreMouseAction.DOWN;
+          but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
+          break;
+        case 'wheel':
+          // only UP/DOWN wheel events are respected
+          if ((ev as WheelEvent).deltaY !== 0) {
+            action = (ev as WheelEvent).deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;
+          }
+          but = CoreMouseButton.WHEEL;
+          break;
+        default:
+          // dont handle other event types by accident
+          return false;
+      }
+
+      // exit if we cannot determine valid button/action values
+      // do nothing for higher buttons than wheel
+      if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {
+        return false;
+      }
+
+      return self._coreMouseService.triggerMouseEvent({
+        col: pos.x - 33, // FIXME: why -33 here?
+        row: pos.y - 33,
+        button: but,
+        action,
+        ctrl: ev.ctrlKey,
+        alt: ev.altKey,
+        shift: ev.shiftKey
+      });
+    }
+
+    /**
+     * Event listener state handling.
+     * We listen to the onProtocolChange event of CoreMouseService and put
+     * requested listeners in `requestedEvents`. With this the listeners
+     * have all bits to do the event listener juggling.
+     * Note: 'mousedown' currently is "always on" and not managed
+     * by onProtocolChange.
+     */
+    const requestedEvents: {[key: string]: ((ev: Event) => void) | null} = {
+      mouseup: null,
+      wheel: null,
+      mousedrag: null,
+      mousemove: null
+    };
+    const eventListeners: {[key: string]: (ev: Event) => void} = {
+      mouseup: (ev: MouseEvent) => {
+        sendEvent(ev);
+        if (!ev.buttons) {
+          // if no other button is held remove global handlers
+          this._document.removeEventListener('mouseup', requestedEvents.mouseup);
+          if (requestedEvents.mousedrag) {
+            this._document.removeEventListener('mousemove', requestedEvents.mousedrag);
+          }
+        }
+        return this.cancel(ev);
+      },
+      wheel: (ev: WheelEvent) => {
+        sendEvent(ev);
+        ev.preventDefault();
+        return this.cancel(ev);
+      },
+      mousedrag: (ev: MouseEvent) => {
+        // deal only with move while a button is held
+        if (ev.buttons) {
+          sendEvent(ev);
+        }
+      },
+      mousemove: (ev: MouseEvent) => {
+        // deal only with move without any button
+        if (!ev.buttons) {
+          sendEvent(ev);
+        }
+      }
+    };
+    this._coreMouseService.onProtocolChange(events => {
+      // apply global changes on events
+      this.mouseEvents = events;
+      if (events) {
+        if (this.optionsService.options.logLevel === 'debug') {
+          this._logService.debug('Binding to mouse events:', this._coreMouseService.explainEvents(events));
+        }
+        this.element.classList.add('enable-mouse-events');
+        this._selectionService.disable();
+      } else {
+        this._logService.debug('Unbinding from mouse events.');
+        this.element.classList.remove('enable-mouse-events');
+        this._selectionService.enable();
+      }
+
+      // add/remove handlers from requestedEvents
+
+      if (!(events & CoreMouseEventType.MOVE)) {
+        el.removeEventListener('mousemove', requestedEvents.mousemove);
+        requestedEvents.mousemove = null;
+      } else if (!requestedEvents.mousemove) {
+        el.addEventListener('mousemove', eventListeners.mousemove);
+        requestedEvents.mousemove = eventListeners.mousemove;
+      }
+
+      if (!(events & CoreMouseEventType.WHEEL)) {
+        el.removeEventListener('wheel', requestedEvents.wheel);
+        requestedEvents.wheel = null;
+      } else if (!requestedEvents.wheel) {
+        el.addEventListener('wheel', eventListeners.wheel);
+        requestedEvents.wheel = eventListeners.wheel;
+      }
+
+      if (!(events & CoreMouseEventType.UP)) {
+        this._document.removeEventListener('mouseup', requestedEvents.mouseup);
+        requestedEvents.mouseup = null;
+      } else if (!requestedEvents.mouseup) {
+        requestedEvents.mouseup = eventListeners.mouseup;
+      }
+
+      if (!(events & CoreMouseEventType.DRAG)) {
+        this._document.removeEventListener('mousemove', requestedEvents.mousedrag);
+        requestedEvents.mousedrag = null;
+      } else if (!requestedEvents.mousedrag) {
+        requestedEvents.mousedrag = eventListeners.mousedrag;
+      }
+    });
+    // force initial onProtocolChange so we dont miss early mouse requests
+    this._coreMouseService.activeProtocol = this._coreMouseService.activeProtocol;
+
+    /**
+     * "Always on" event listeners.
+     */
+    this.register(addDisposableDomListener(el, 'mousedown', (ev: MouseEvent) => {
+      ev.preventDefault();
+      this.focus();
+
+      // Don't send the mouse button to the pty if mouse events are disabled or
+      // if the selection manager is having selection forced (ie. a modifier is
+      // held).
+      if (!this.mouseEvents || this._selectionService.shouldForceSelection(ev)) {
+        return;
+      }
+
+      sendEvent(ev);
+
+      // Register additional global handlers which should keep reporting outside
+      // of the terminal element.
+      // Note: Other emulators also do this for 'mousedown' while a button
+      // is held, we currently limit 'mousedown' to the terminal only.
+      if (requestedEvents.mouseup) {
+        this._document.addEventListener('mouseup', requestedEvents.mouseup);
+      }
+      if (requestedEvents.mousedrag) {
+        this._document.addEventListener('mousemove', requestedEvents.mousedrag);
+      }
+
+      return this.cancel(ev);
+    }));
+
+    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {
+      if (!requestedEvents.wheel) {
+        // Convert wheel events into up/down events when the buffer does not have scrollback, this
+        // enables scrolling in apps hosted in the alt buffer such as vim or tmux.
+        if (!this.buffer.hasScrollback) {
+          const amount = this.viewport.getLinesScrolled(ev);
+
+          // Do nothing if there's no vertical scroll
+          if (amount === 0) {
+            return;
+          }
+
+          // Construct and send sequences
+          const sequence = C0.ESC + (this._coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + ( ev.deltaY < 0 ? 'A' : 'B');
+          let data = '';
+          for (let i = 0; i < Math.abs(amount); i++) {
+            data += sequence;
+          }
+          this._coreService.triggerDataEvent(data, true);
+        }
+        return;
+      }
+    }));
+
+    // allow wheel scrolling in
+    // the shell for example
+    this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {
+      if (requestedEvents.wheel) return;
+      if (!this.viewport.onWheel(ev)) {
+        return this.cancel(ev);
+      }
+    }));
+
+    this.register(addDisposableDomListener(el, 'touchstart', (ev: TouchEvent) => {
+      if (this.mouseEvents) return;
+      this.viewport.onTouchStart(ev);
+      return this.cancel(ev);
+    }));
+
+    this.register(addDisposableDomListener(el, 'touchmove', (ev: TouchEvent) => {
+      if (this.mouseEvents) return;
+      if (!this.viewport.onTouchMove(ev)) {
+        return this.cancel(ev);
+      }
+    }));
+  }
+
+
+  /**
+   * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
+   * opportunity.
+   * @param start The row to start from (between 0 and this.rows - 1).
+   * @param end The row to end at (between start and this.rows - 1).
+   */
+  public refresh(start: number, end: number): void {
+    if (this._renderService) {
+      this._renderService.refreshRows(start, end);
+    }
+  }
+
+  /**
+   * Queues linkification for the specified rows.
+   * @param start The row to start from (between 0 and this.rows - 1).
+   * @param end The row to end at (between start and this.rows - 1).
+   */
+  private _queueLinkification(start: number, end: number): void {
+    if (this.linkifier) {
+      this.linkifier.linkifyRows(start, end);
+    }
+  }
+
+  /**
+   * Change the cursor style for different selection modes
+   */
+  public updateCursorStyle(ev: KeyboardEvent): void {
+    if (this._selectionService && this._selectionService.shouldColumnSelect(ev)) {
+      this.element.classList.add('column-select');
+    } else {
+      this.element.classList.remove('column-select');
+    }
+  }
+
+  /**
+   * Display the cursor element
+   */
+  public showCursor(): void {
+    if (!this.cursorState) {
+      this.cursorState = 1;
+      this.refresh(this.buffer.y, this.buffer.y);
+    }
+  }
+
+  /**
+   * Scroll the terminal down 1 row, creating a blank line.
+   * @param isWrapped Whether the new line is wrapped from the previous line.
+   */
+  public scroll(isWrapped: boolean = false): void {
+    let newLine: IBufferLine;
+    newLine = this._blankLine;
+    const eraseAttr = this.eraseAttrData();
+    if (!newLine || newLine.length !== this.cols || newLine.getFg(0) !== eraseAttr.fg || newLine.getBg(0) !== eraseAttr.bg) {
+      newLine = this.buffer.getBlankLine(eraseAttr, isWrapped);
+      this._blankLine = newLine;
+    }
+    newLine.isWrapped = isWrapped;
+
+    const topRow = this.buffer.ybase + this.buffer.scrollTop;
+    const bottomRow = this.buffer.ybase + this.buffer.scrollBottom;
+
+    if (this.buffer.scrollTop === 0) {
+      // Determine whether the buffer is going to be trimmed after insertion.
+      const willBufferBeTrimmed = this.buffer.lines.isFull;
+
+      // Insert the line using the fastest method
+      if (bottomRow === this.buffer.lines.length - 1) {
+        if (willBufferBeTrimmed) {
+          this.buffer.lines.recycle().copyFrom(newLine);
+        } else {
+          this.buffer.lines.push(newLine.clone());
+        }
+      } else {
+        this.buffer.lines.splice(bottomRow + 1, 0, newLine.clone());
+      }
+
+      // Only adjust ybase and ydisp when the buffer is not trimmed
+      if (!willBufferBeTrimmed) {
+        this.buffer.ybase++;
+        // Only scroll the ydisp with ybase if the user has not scrolled up
+        if (!this._userScrolling) {
+          this.buffer.ydisp++;
+        }
+      } else {
+        // When the buffer is full and the user has scrolled up, keep the text
+        // stable unless ydisp is right at the top
+        if (this._userScrolling) {
+          this.buffer.ydisp = Math.max(this.buffer.ydisp - 1, 0);
+        }
+      }
+    } else {
+      // scrollTop is non-zero which means no line will be going to the
+      // scrollback, instead we can just shift them in-place.
+      const scrollRegionHeight = bottomRow - topRow + 1/*as it's zero-based*/;
+      this.buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1);
+      this.buffer.lines.set(bottomRow, newLine.clone());
+    }
+
+    // Move the viewport to the bottom of the buffer unless the user is
+    // scrolling.
+    if (!this._userScrolling) {
+      this.buffer.ydisp = this.buffer.ybase;
+    }
+
+    // Flag rows that need updating
+    this._dirtyRowService.markRangeDirty(this.buffer.scrollTop, this.buffer.scrollBottom);
+
+    this._onScroll.fire(this.buffer.ydisp);
+  }
+
+  /**
+   * Scroll the display of the terminal
+   * @param disp The number of lines to scroll down (negative scroll up).
+   * @param suppressScrollEvent Don't emit the scroll event as scrollLines. This is used
+   * to avoid unwanted events being handled by the viewport when the event was triggered from the
+   * viewport originally.
+   */
+  public scrollLines(disp: number, suppressScrollEvent?: boolean): void {
+    if (disp < 0) {
+      if (this.buffer.ydisp === 0) {
+        return;
+      }
+      this._userScrolling = true;
+    } else if (disp + this.buffer.ydisp >= this.buffer.ybase) {
+      this._userScrolling = false;
+    }
+
+    const oldYdisp = this.buffer.ydisp;
+    this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0);
+
+    // No change occurred, don't trigger scroll/refresh
+    if (oldYdisp === this.buffer.ydisp) {
+      return;
+    }
+
+    if (!suppressScrollEvent) {
+      this._onScroll.fire(this.buffer.ydisp);
+    }
+
+    this.refresh(0, this.rows - 1);
+  }
+
+  /**
+   * Scroll the display of the terminal by a number of pages.
+   * @param pageCount The number of pages to scroll (negative scrolls up).
+   */
+  public scrollPages(pageCount: number): void {
+    this.scrollLines(pageCount * (this.rows - 1));
+  }
+
+  /**
+   * Scrolls the display of the terminal to the top.
+   */
+  public scrollToTop(): void {
+    this.scrollLines(-this.buffer.ydisp);
+  }
+
+  /**
+   * Scrolls the display of the terminal to the bottom.
+   */
+  public scrollToBottom(): void {
+    this.scrollLines(this.buffer.ybase - this.buffer.ydisp);
+  }
+
+  public scrollToLine(line: number): void {
+    const scrollAmount = line - this.buffer.ydisp;
+    if (scrollAmount !== 0) {
+      this.scrollLines(scrollAmount);
+    }
+  }
+
+  public paste(data: string): void {
+    paste(data, this.textarea, this.bracketedPasteMode, this._coreService);
+  }
+
+  /**
+   * Attaches a custom key event handler which is run before keys are processed,
+   * giving consumers of xterm.js ultimate control as to what keys should be
+   * processed by the terminal and what keys should not.
+   * @param customKeyEventHandler The custom KeyboardEvent handler to attach.
+   * This is a function that takes a KeyboardEvent, allowing consumers to stop
+   * propagation and/or prevent the default action. The function returns whether
+   * the event should be processed by xterm.js.
+   */
+  public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {
+    this._customKeyEventHandler = customKeyEventHandler;
+  }
+
+  /** Add handler for ESC escape sequence. See xterm.d.ts for details. */
+  public addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable {
+    return this._inputHandler.addEscHandler(id, callback);
+  }
+
+  /** Add handler for DCS escape sequence. See xterm.d.ts for details. */
+  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable {
+    return this._inputHandler.addDcsHandler(id, callback);
+  }
+
+  /** Add handler for CSI escape sequence. See xterm.d.ts for details. */
+  public addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable {
+    return this._inputHandler.addCsiHandler(id, callback);
+  }
+  /** Add handler for OSC escape sequence. See xterm.d.ts for details. */
+  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {
+    return this._inputHandler.addOscHandler(ident, callback);
+  }
+
+  /**
+   * Registers a link matcher, allowing custom link patterns to be matched and
+   * handled.
+   * @param regex The regular expression to search for, specifically
+   * this searches the textContent of the rows. You will want to use \s to match
+   * a space ' ' character for example.
+   * @param handler The callback when the link is called.
+   * @param options Options for the link matcher.
+   * @return The ID of the new matcher, this can be used to deregister.
+   */
+  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: ILinkMatcherOptions): number {
+    const matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
+    this.refresh(0, this.rows - 1);
+    return matcherId;
+  }
+
+  /**
+   * Deregisters a link matcher if it has been registered.
+   * @param matcherId The link matcher's ID (returned after register)
+   */
+  public deregisterLinkMatcher(matcherId: number): void {
+    if (this.linkifier.deregisterLinkMatcher(matcherId)) {
+      this.refresh(0, this.rows - 1);
+    }
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
+    const joinerId = this._renderService.registerCharacterJoiner(handler);
+    this.refresh(0, this.rows - 1);
+    return joinerId;
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): void {
+    if (this._renderService.deregisterCharacterJoiner(joinerId)) {
+      this.refresh(0, this.rows - 1);
+    }
+  }
+
+  public get markers(): IMarker[] {
+    return this.buffer.markers;
+  }
+
+  public addMarker(cursorYOffset: number): IMarker {
+    // Disallow markers on the alt buffer
+    if (this.buffer !== this.buffers.normal) {
+      return;
+    }
+
+    return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);
+  }
+
+  /**
+   * Gets whether the terminal has an active selection.
+   */
+  public hasSelection(): boolean {
+    return this._selectionService ? this._selectionService.hasSelection : false;
+  }
+
+  /**
+   * Selects text within the terminal.
+   * @param column The column the selection starts at..
+   * @param row The row the selection starts at.
+   * @param length The length of the selection.
+   */
+  public select(column: number, row: number, length: number): void {
+    this._selectionService.setSelection(column, row, length);
+  }
+
+  /**
+   * Gets the terminal's current selection, this is useful for implementing copy
+   * behavior outside of xterm.js.
+   */
+  public getSelection(): string {
+    return this._selectionService ? this._selectionService.selectionText : '';
+  }
+
+  public getSelectionPosition(): ISelectionPosition | undefined {
+    if (!this._selectionService.hasSelection) {
+      return undefined;
+    }
+
+    return {
+      startColumn: this._selectionService.selectionStart[0],
+      startRow: this._selectionService.selectionStart[1],
+      endColumn: this._selectionService.selectionEnd[0],
+      endRow: this._selectionService.selectionEnd[1]
+    };
+  }
+
+  /**
+   * Clears the current terminal selection.
+   */
+  public clearSelection(): void {
+    if (this._selectionService) {
+      this._selectionService.clearSelection();
+    }
+  }
+
+  /**
+   * Selects all text within the terminal.
+   */
+  public selectAll(): void {
+    if (this._selectionService) {
+      this._selectionService.selectAll();
+    }
+  }
+
+  public selectLines(start: number, end: number): void {
+    if (this._selectionService) {
+      this._selectionService.selectLines(start, end);
+    }
+  }
+
+  /**
+   * Handle a keydown event
+   * Key Resources:
+   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
+   * @param ev The keydown event to be handled.
+   */
+  protected _keyDown(event: KeyboardEvent): boolean {
+    this._keyDownHandled = false;
+
+    if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {
+      return false;
+    }
+
+    if (!this._compositionHelper.keydown(event)) {
+      if (this.buffer.ybase !== this.buffer.ydisp) {
+        this.scrollToBottom();
+      }
+      return false;
+    }
+
+    const result = evaluateKeyboardEvent(event, this._coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);
+
+    this.updateCursorStyle(event);
+
+    if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {
+      const scrollCount = this.rows - 1;
+      this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);
+      return this.cancel(event, true);
+    }
+
+    if (result.type === KeyboardResultType.SELECT_ALL) {
+      this.selectAll();
+    }
+
+    if (this._isThirdLevelShift(this.browser, event)) {
+      return true;
+    }
+
+    if (result.cancel) {
+      // The event is canceled at the end already, is this necessary?
+      this.cancel(event, true);
+    }
+
+    if (!result.key) {
+      return true;
+    }
+
+    // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers
+    // will announce deleted characters. This will not work 100% of the time but it should cover
+    // most scenarios.
+    if (result.key === C0.ETX || result.key === C0.CR) {
+      this.textarea.value = '';
+    }
+
+    this._onKey.fire({ key: result.key, domEvent: event });
+    this.showCursor();
+    this._coreService.triggerDataEvent(result.key, true);
+
+    // Cancel events when not in screen reader mode so events don't get bubbled up and handled by
+    // other listeners. When screen reader mode is enabled, this could cause issues if the event
+    // is handled at a higher level, this is a compromise in order to echo keys to the screen
+    // reader.
+    if (!this.optionsService.options.screenReaderMode) {
+      return this.cancel(event, true);
+    }
+
+    this._keyDownHandled = true;
+  }
+
+  private _isThirdLevelShift(browser: IBrowser, ev: IKeyboardEvent): boolean {
+    const thirdLevelKey =
+        (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
+        (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
+
+    if (ev.type === 'keypress') {
+      return thirdLevelKey;
+    }
+
+    // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
+    return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
+  }
+
+  /**
+   * Set the G level of the terminal
+   * @param g
+   */
+  public setgLevel(g: number): void {
+    this.glevel = g;
+    this.charset = this.charsets[g];
+  }
+
+  /**
+   * Set the charset for the given G level of the terminal
+   * @param g
+   * @param charset
+   */
+  public setgCharset(g: number, charset: ICharset): void {
+    this.charsets[g] = charset;
+    if (this.glevel === g) {
+      this.charset = charset;
+    }
+  }
+
+  protected _keyUp(ev: KeyboardEvent): void {
+    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
+      return;
+    }
+
+    if (!wasModifierKeyOnlyEvent(ev)) {
+      this.focus();
+    }
+
+    this.updateCursorStyle(ev);
+  }
+
+  /**
+   * Handle a keypress event.
+   * Key Resources:
+   *   - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
+   * @param ev The keypress event to be handled.
+   */
+  protected _keyPress(ev: KeyboardEvent): boolean {
+    let key;
+
+    if (this._keyDownHandled) {
+      return false;
+    }
+
+    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
+      return false;
+    }
+
+    this.cancel(ev);
+
+    if (ev.charCode) {
+      key = ev.charCode;
+    } else if (ev.which === null || ev.which === undefined) {
+      key = ev.keyCode;
+    } else if (ev.which !== 0 && ev.charCode !== 0) {
+      key = ev.which;
+    } else {
+      return false;
+    }
+
+    if (!key || (
+      (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)
+    )) {
+      return false;
+    }
+
+    key = String.fromCharCode(key);
+
+    this._onKey.fire({ key, domEvent: ev });
+    this.showCursor();
+    this._coreService.triggerDataEvent(key, true);
+
+    return true;
+  }
+
+  /**
+   * Ring the bell.
+   * Note: We could do sweet things with webaudio here
+   */
+  public bell(): void {
+    if (this._soundBell()) {
+      this._soundService.playBellSound();
+    }
+
+    if (this._visualBell()) {
+      this.element.classList.add('visual-bell-active');
+      clearTimeout(this._visualBellTimer);
+      this._visualBellTimer = window.setTimeout(() => {
+        this.element.classList.remove('visual-bell-active');
+      }, 200);
+    }
+  }
+
+  /**
+   * Resizes the terminal.
+   *
+   * @param x The number of columns to resize to.
+   * @param y The number of rows to resize to.
+   */
+  public resize(x: number, y: number): void {
+    if (isNaN(x) || isNaN(y)) {
+      return;
+    }
+
+    if (x === this.cols && y === this.rows) {
+      // Check if we still need to measure the char size (fixes #785).
+      if (this._charSizeService && !this._charSizeService.hasValidSize) {
+        this._charSizeService.measure();
+      }
+      return;
+    }
+
+    if (x < MINIMUM_COLS) x = MINIMUM_COLS;
+    if (y < MINIMUM_ROWS) y = MINIMUM_ROWS;
+
+    this.buffers.resize(x, y);
+
+    this._bufferService.resize(x, y);
+    this.buffers.setupTabStops(this.cols);
+
+    if (this._charSizeService) {
+      this._charSizeService.measure();
+    }
+
+    // Sync the scroll area to make sure scroll events don't fire and scroll the viewport to an
+    // invalid location
+    this.viewport.syncScrollArea(true);
+
+    this.refresh(0, this.rows - 1);
+    this._onResize.fire({ cols: x, rows: y });
+  }
+
+  /**
+   * Clear the entire buffer, making the prompt line the new first line.
+   */
+  public clear(): void {
+    if (this.buffer.ybase === 0 && this.buffer.y === 0) {
+      // Don't clear if it's already clear
+      return;
+    }
+    this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y));
+    this.buffer.lines.length = 1;
+    this.buffer.ydisp = 0;
+    this.buffer.ybase = 0;
+    this.buffer.y = 0;
+    for (let i = 1; i < this.rows; i++) {
+      this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));
+    }
+    this.refresh(0, this.rows - 1);
+    this._onScroll.fire(this.buffer.ydisp);
+  }
+
+  /**
+   * Evaluate if the current terminal is the given argument.
+   * @param term The terminal name to evaluate
+   */
+  public is(term: string): boolean {
+    return (this.options.termName + '').indexOf(term) === 0;
+  }
+
+  /**
+   * Emit the data event and populate the given data.
+   * @param data The data to populate in the event.
+   */
+  // public handler(data: string): void {
+  //   // Prevents all events to pty process if stdin is disabled
+  //   if (this.options.disableStdin) {
+  //     return;
+  //   }
+
+  //   // Clear the selection if the selection manager is available and has an active selection
+  //   if (this.selectionService && this.selectionService.hasSelection) {
+  //     this.selectionService.clearSelection();
+  //   }
+
+  //   // Input is being sent to the terminal, the terminal should focus the prompt.
+  //   if (this.buffer.ybase !== this.buffer.ydisp) {
+  //     this.scrollToBottom();
+  //   }
+  //   this._onData.fire(data);
+  // }
+
+  /**
+   * Emit the 'title' event and populate the given title.
+   * @param title The title to populate in the event.
+   */
+  public handleTitle(title: string): void {
+    this._onTitleChange.fire(title);
+  }
+
+  /**
+   * Reset terminal.
+   * Note: Calling this directly from JS is synchronous but does not clear
+   * input buffers and does not reset the parser, thus the terminal will
+   * continue to apply pending input data.
+   * If you need in band reset (synchronous with input data) consider
+   * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).
+   */
+  public reset(): void {
+    /**
+     * Since _setup handles a full terminal creation, we have to carry forward
+     * a few things that should not reset.
+     */
+    this.options.rows = this.rows;
+    this.options.cols = this.cols;
+    const customKeyEventHandler = this._customKeyEventHandler;
+    const inputHandler = this._inputHandler;
+    const cursorState = this.cursorState;
+    const userScrolling = this._userScrolling;
+
+    this._setup();
+    this._bufferService.reset();
+    this._coreService.reset();
+    this._coreMouseService.reset();
+    if (this._selectionService) {
+      this._selectionService.reset();
+    }
+
+    // reattach
+    this._customKeyEventHandler = customKeyEventHandler;
+    this._inputHandler = inputHandler;
+    this.cursorState = cursorState;
+    this._userScrolling = userScrolling;
+
+    // do a full screen refresh
+    this.refresh(0, this.rows - 1);
+    if (this.viewport) {
+      this.viewport.syncScrollArea();
+    }
+  }
+
+  // TODO: Remove cancel function and cancelEvents option
+  public cancel(ev: Event, force?: boolean): boolean {
+    if (!this.options.cancelEvents && !force) {
+      return;
+    }
+    ev.preventDefault();
+    ev.stopPropagation();
+    return false;
+  }
+
+  private _visualBell(): boolean {
+    return false;
+    // return this.options.bellStyle === 'visual' ||
+    //     this.options.bellStyle === 'both';
+  }
+
+  private _soundBell(): boolean {
+    return this.options.bellStyle === 'sound';
+    // return this.options.bellStyle === 'sound' ||
+    //     this.options.bellStyle === 'both';
+  }
+
+  public write(data: string | Uint8Array, callback?: () => void): void {
+    this._writeBuffer.write(data, callback);
+  }
+
+  public writeSync(data: string | Uint8Array): void {
+    this._writeBuffer.writeSync(data);
+  }
+}
+
+/**
+ * Helpers
+ */
+
+function wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {
+  return ev.keyCode === 16 || // Shift
+    ev.keyCode === 17 || // Ctrl
+    ev.keyCode === 18; // Alt
+}
diff --git a/node_modules/xterm/src/Types.d.ts b/node_modules/xterm/src/Types.d.ts
new file mode 100644 (file)
index 0000000..be1019e
--- /dev/null
@@ -0,0 +1,260 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ITerminalOptions as IPublicTerminalOptions, IDisposable, IMarker, ISelectionPosition } from 'xterm';
+import { ICharset, IAttributeData, CharData, CoreMouseEventType } from 'common/Types';
+import { IEvent, IEventEmitter } from 'common/EventEmitter';
+import { IColorSet, ILinkifier, ILinkMatcherOptions, IViewport } from 'browser/Types';
+import { IOptionsService } from 'common/services/Services';
+import { IBuffer, IBufferSet } from 'common/buffer/Types';
+import { IParams, IFunctionIdentifier } from 'common/parser/Types';
+
+export type CustomKeyEventHandler = (event: KeyboardEvent) => boolean;
+
+export type LineData = CharData[];
+
+/**
+ * This interface encapsulates everything needed from the Terminal by the
+ * InputHandler. This cleanly separates the large amount of methods needed by
+ * InputHandler cleanly from the ITerminal interface.
+ */
+export interface IInputHandlingTerminal {
+  element: HTMLElement;
+  options: ITerminalOptions;
+  cols: number;
+  rows: number;
+  charset: ICharset;
+  gcharset: number;
+  glevel: number;
+  charsets: ICharset[];
+  applicationKeypad: boolean;
+  originMode: boolean;
+  insertMode: boolean;
+  wraparoundMode: boolean;
+  bracketedPasteMode: boolean;
+  curAttrData: IAttributeData;
+  savedCols: number;
+  mouseEvents: CoreMouseEventType;
+  sendFocus: boolean;
+  cursorHidden: boolean;
+
+  buffers: IBufferSet;
+  buffer: IBuffer;
+  viewport: IViewport;
+
+  onA11yCharEmitter: IEventEmitter<string>;
+  onA11yTabEmitter: IEventEmitter<number>;
+
+  bell(): void;
+  focus(): void;
+  scroll(isWrapped?: boolean): void;
+  setgLevel(g: number): void;
+  eraseAttrData(): IAttributeData;
+  is(term: string): boolean;
+  setgCharset(g: number, charset: ICharset): void;
+  resize(x: number, y: number): void;
+  reset(): void;
+  showCursor(): void;
+  refresh(start: number, end: number): void;
+  handleTitle(title: string): void;
+}
+
+export interface ICompositionHelper {
+  compositionstart(): void;
+  compositionupdate(ev: CompositionEvent): void;
+  compositionend(): void;
+  updateCompositionElements(dontRecurse?: boolean): void;
+  keydown(ev: KeyboardEvent): boolean;
+}
+
+/**
+ * Calls the parser and handles actions generated by the parser.
+ */
+export interface IInputHandler {
+  parse(data: string | Uint8Array): void;
+  print(data: Uint32Array, start: number, end: number): void;
+
+  /** C0 BEL */ bell(): void;
+  /** C0 LF */ lineFeed(): void;
+  /** C0 CR */ carriageReturn(): void;
+  /** C0 BS */ backspace(): void;
+  /** C0 HT */ tab(): void;
+  /** C0 SO */ shiftOut(): void;
+  /** C0 SI */ shiftIn(): void;
+
+  /** CSI @ */ insertChars(params: IParams): void;
+  /** CSI SP @ */ scrollLeft(params: IParams): void;
+  /** CSI A */ cursorUp(params: IParams): void;
+  /** CSI SP A */ scrollRight(params: IParams): void;
+  /** CSI B */ cursorDown(params: IParams): void;
+  /** CSI C */ cursorForward(params: IParams): void;
+  /** CSI D */ cursorBackward(params: IParams): void;
+  /** CSI E */ cursorNextLine(params: IParams): void;
+  /** CSI F */ cursorPrecedingLine(params: IParams): void;
+  /** CSI G */ cursorCharAbsolute(params: IParams): void;
+  /** CSI H */ cursorPosition(params: IParams): void;
+  /** CSI I */ cursorForwardTab(params: IParams): void;
+  /** CSI J */ eraseInDisplay(params: IParams): void;
+  /** CSI K */ eraseInLine(params: IParams): void;
+  /** CSI L */ insertLines(params: IParams): void;
+  /** CSI M */ deleteLines(params: IParams): void;
+  /** CSI P */ deleteChars(params: IParams): void;
+  /** CSI S */ scrollUp(params: IParams): void;
+  /** CSI T */ scrollDown(params: IParams, collect?: string): void;
+  /** CSI X */ eraseChars(params: IParams): void;
+  /** CSI Z */ cursorBackwardTab(params: IParams): void;
+  /** CSI ` */ charPosAbsolute(params: IParams): void;
+  /** CSI a */ hPositionRelative(params: IParams): void;
+  /** CSI b */ repeatPrecedingCharacter(params: IParams): void;
+  /** CSI c */ sendDeviceAttributesPrimary(params: IParams): void;
+  /** CSI > c */ sendDeviceAttributesSecondary(params: IParams): void;
+  /** CSI d */ linePosAbsolute(params: IParams): void;
+  /** CSI e */ vPositionRelative(params: IParams): void;
+  /** CSI f */ hVPosition(params: IParams): void;
+  /** CSI g */ tabClear(params: IParams): void;
+  /** CSI h */ setMode(params: IParams, collect?: string): void;
+  /** CSI l */ resetMode(params: IParams, collect?: string): void;
+  /** CSI m */ charAttributes(params: IParams): void;
+  /** CSI n */ deviceStatus(params: IParams, collect?: string): void;
+  /** CSI p */ softReset(params: IParams, collect?: string): void;
+  /** CSI q */ setCursorStyle(params: IParams, collect?: string): void;
+  /** CSI r */ setScrollRegion(params: IParams, collect?: string): void;
+  /** CSI s */ saveCursor(params: IParams): void;
+  /** CSI u */ restoreCursor(params: IParams): void;
+  /** CSI ' } */ insertColumns(params: IParams): void;
+  /** CSI ' ~ */ deleteColumns(params: IParams): void;
+  /** OSC 0
+      OSC 2 */ setTitle(data: string): void;
+  /** ESC E */ nextLine(): void;
+  /** ESC = */ keypadApplicationMode(): void;
+  /** ESC > */ keypadNumericMode(): void;
+  /** ESC % G
+      ESC % @ */ selectDefaultCharset(): void;
+  /** ESC ( C
+      ESC ) C
+      ESC * C
+      ESC + C
+      ESC - C
+      ESC . C
+      ESC / C */ selectCharset(collectAndFlag: string): void;
+  /** ESC D */ index(): void;
+  /** ESC H */ tabSet(): void;
+  /** ESC M */ reverseIndex(): void;
+  /** ESC c */ reset(): void;
+  /** ESC n
+      ESC o
+      ESC |
+      ESC }
+      ESC ~ */ setgLevel(level: number): void;
+  /** ESC # 8 */ screenAlignmentPattern(): void;
+}
+
+export interface ITerminal extends IPublicTerminal, IElementAccessor, IBufferAccessor, ILinkifierAccessor {
+  screenElement: HTMLElement;
+  browser: IBrowser;
+  cursorHidden: boolean;
+  cursorState: number;
+  buffer: IBuffer;
+  buffers: IBufferSet;
+  isFocused: boolean;
+  viewport: IViewport;
+  bracketedPasteMode: boolean;
+  optionsService: IOptionsService;
+  // TODO: We should remove options once components adopt optionsService
+  options: ITerminalOptions;
+
+  onBlur: IEvent<void>;
+  onFocus: IEvent<void>;
+  onA11yChar: IEvent<string>;
+  onA11yTab: IEvent<number>;
+
+  scrollLines(disp: number, suppressScrollEvent?: boolean): void;
+  cancel(ev: Event, force?: boolean): boolean | void;
+  showCursor(): void;
+}
+
+// Portions of the public API that are required by the internal Terminal
+export interface IPublicTerminal extends IDisposable {
+  textarea: HTMLTextAreaElement | undefined;
+  rows: number;
+  cols: number;
+  buffer: IBuffer;
+  markers: IMarker[];
+  onCursorMove: IEvent<void>;
+  onData: IEvent<string>;
+  onKey: IEvent<{ key: string, domEvent: KeyboardEvent }>;
+  onLineFeed: IEvent<void>;
+  onScroll: IEvent<number>;
+  onSelectionChange: IEvent<void>;
+  onRender: IEvent<{ start: number, end: number }>;
+  onResize: IEvent<{ cols: number, rows: number }>;
+  onTitleChange: IEvent<string>;
+  blur(): void;
+  focus(): void;
+  resize(columns: number, rows: number): void;
+  open(parent: HTMLElement): void;
+  attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void;
+  addCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean): IDisposable;
+  addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean): IDisposable;
+  addEscHandler(id: IFunctionIdentifier, callback: () => boolean): IDisposable;
+  addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable;
+  registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number;
+  deregisterLinkMatcher(matcherId: number): void;
+  registerCharacterJoiner(handler: (text: string) => [number, number][]): number;
+  deregisterCharacterJoiner(joinerId: number): void;
+  addMarker(cursorYOffset: number): IMarker;
+  hasSelection(): boolean;
+  getSelection(): string;
+  getSelectionPosition(): ISelectionPosition | undefined;
+  clearSelection(): void;
+  select(column: number, row: number, length: number): void;
+  selectAll(): void;
+  selectLines(start: number, end: number): void;
+  dispose(): void;
+  scrollLines(amount: number): void;
+  scrollPages(pageCount: number): void;
+  scrollToTop(): void;
+  scrollToBottom(): void;
+  scrollToLine(line: number): void;
+  clear(): void;
+  write(data: string | Uint8Array, callback?: () => void): void;
+  paste(data: string): void;
+  refresh(start: number, end: number): void;
+  reset(): void;
+}
+
+export interface IBufferAccessor {
+  buffer: IBuffer;
+}
+
+export interface IElementAccessor {
+  readonly element: HTMLElement | undefined;
+}
+
+export interface ILinkifierAccessor {
+  linkifier: ILinkifier;
+}
+
+// TODO: The options that are not in the public API should be reviewed
+export interface ITerminalOptions extends IPublicTerminalOptions {
+  [key: string]: any;
+  cancelEvents?: boolean;
+  convertEol?: boolean;
+  handler?: (data: string) => void;
+  screenKeys?: boolean;
+  termName?: string;
+  useFlowControl?: boolean;
+}
+
+export interface IBrowser {
+  isNode: boolean;
+  userAgent: string;
+  platform: string;
+  isFirefox: boolean;
+  isMac: boolean;
+  isIpad: boolean;
+  isIphone: boolean;
+  isWindows: boolean;
+}
diff --git a/node_modules/xterm/src/WindowsMode.ts b/node_modules/xterm/src/WindowsMode.ts
new file mode 100644 (file)
index 0000000..0838cae
--- /dev/null
@@ -0,0 +1,28 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'xterm';
+import { ITerminal } from './Types';
+import { CHAR_DATA_CODE_INDEX, NULL_CELL_CODE, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';
+
+export function applyWindowsMode(terminal: ITerminal): IDisposable {
+  // Winpty does not support wraparound mode which means that lines will never
+  // be marked as wrapped. This causes issues for things like copying a line
+  // retaining the wrapped new line characters or if consumers are listening
+  // in on the data stream.
+  //
+  // The workaround for this is to listen to every incoming line feed and mark
+  // the line as wrapped if the last character in the previous line is not a
+  // space. This is certainly not without its problems, but generally on
+  // Windows when text reaches the end of the terminal it's likely going to be
+  // wrapped.
+  return terminal.onLineFeed(() => {
+    const line = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y - 1);
+    const lastChar = line.get(terminal.cols - 1);
+
+    const nextLine = terminal.buffer.lines.get(terminal.buffer.ybase + terminal.buffer.y);
+    nextLine.isWrapped = (lastChar[CHAR_DATA_CODE_INDEX] !== NULL_CELL_CODE && lastChar[CHAR_DATA_CODE_INDEX] !== WHITESPACE_CELL_CODE);
+  });
+}
diff --git a/node_modules/xterm/src/browser/Clipboard.ts b/node_modules/xterm/src/browser/Clipboard.ts
new file mode 100644 (file)
index 0000000..594e442
--- /dev/null
@@ -0,0 +1,111 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ISelectionService } from 'browser/services/Services';
+import { ICoreService } from 'common/services/Services';
+
+/**
+ * Prepares text to be pasted into the terminal by normalizing the line endings
+ * @param text The pasted text that needs processing before inserting into the terminal
+ */
+export function prepareTextForTerminal(text: string): string {
+  return text.replace(/\r?\n/g, '\r');
+}
+
+/**
+ * Bracket text for paste, if necessary, as per https://cirw.in/blog/bracketed-paste
+ * @param text The pasted text to bracket
+ */
+export function bracketTextForPaste(text: string, bracketedPasteMode: boolean): string {
+  if (bracketedPasteMode) {
+    return '\x1b[200~' + text + '\x1b[201~';
+  }
+  return text;
+}
+
+/**
+ * Binds copy functionality to the given terminal.
+ * @param ev The original copy event to be handled
+ */
+export function copyHandler(ev: ClipboardEvent, selectionService: ISelectionService): void {
+  if (ev.clipboardData) {
+    ev.clipboardData.setData('text/plain', selectionService.selectionText);
+  }
+  // Prevent or the original text will be copied.
+  ev.preventDefault();
+}
+
+/**
+ * Redirect the clipboard's data to the terminal's input handler.
+ * @param ev The original paste event to be handled
+ * @param term The terminal on which to apply the handled paste event
+ */
+export function handlePasteEvent(ev: ClipboardEvent, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {
+  ev.stopPropagation();
+  if (ev.clipboardData) {
+    const text = ev.clipboardData.getData('text/plain');
+    paste(text, textarea, bracketedPasteMode, coreService);
+  }
+}
+
+export function paste(text: string, textarea: HTMLTextAreaElement, bracketedPasteMode: boolean, coreService: ICoreService): void {
+  text = prepareTextForTerminal(text);
+  text = bracketTextForPaste(text, bracketedPasteMode);
+  coreService.triggerDataEvent(text, true);
+  textarea.value = '';
+}
+
+/**
+ * Moves the textarea under the mouse cursor and focuses it.
+ * @param ev The original right click event to be handled.
+ * @param textarea The terminal's textarea.
+ */
+export function moveTextAreaUnderMouseCursor(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement): void {
+
+  // Calculate textarea position relative to the screen element
+  const pos = screenElement.getBoundingClientRect();
+  const left = ev.clientX - pos.left - 10;
+  const top = ev.clientY - pos.top - 10;
+
+  // Bring textarea at the cursor position
+  textarea.style.position = 'absolute';
+  textarea.style.width = '20px';
+  textarea.style.height = '20px';
+  textarea.style.left = `${left}px`;
+  textarea.style.top = `${top}px`;
+  textarea.style.zIndex = '1000';
+
+  textarea.focus();
+
+  // Reset the terminal textarea's styling
+  // Timeout needs to be long enough for click event to be handled.
+  setTimeout(() => {
+    textarea.style.position = null;
+    textarea.style.width = null;
+    textarea.style.height = null;
+    textarea.style.left = null;
+    textarea.style.top = null;
+    textarea.style.zIndex = null;
+  }, 200);
+}
+
+/**
+ * Bind to right-click event and allow right-click copy and paste.
+ * @param ev The original right click event to be handled.
+ * @param textarea The terminal's textarea.
+ * @param selectionService The terminal's selection manager.
+ * @param shouldSelectWord If true and there is no selection the current word will be selected
+ */
+export function rightClickHandler(ev: MouseEvent, textarea: HTMLTextAreaElement, screenElement: HTMLElement, selectionService: ISelectionService, shouldSelectWord: boolean): void {
+  moveTextAreaUnderMouseCursor(ev, textarea, screenElement);
+
+  if (shouldSelectWord && !selectionService.isClickInSelection(ev)) {
+    selectionService.selectWordAtCursor(ev);
+  }
+
+  // Get textarea ready to copy from the context menu
+  textarea.value = selectionService.selectionText;
+  textarea.select();
+}
diff --git a/node_modules/xterm/src/browser/ColorManager.ts b/node_modules/xterm/src/browser/ColorManager.ts
new file mode 100644 (file)
index 0000000..70d21a7
--- /dev/null
@@ -0,0 +1,190 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IColorManager, IColor, IColorSet } from 'browser/Types';
+import { ITheme } from 'common/services/Services';
+
+const DEFAULT_FOREGROUND = fromHex('#ffffff');
+const DEFAULT_BACKGROUND = fromHex('#000000');
+const DEFAULT_CURSOR = fromHex('#ffffff');
+const DEFAULT_CURSOR_ACCENT = fromHex('#000000');
+const DEFAULT_SELECTION = {
+  css: 'rgba(255, 255, 255, 0.3)',
+  rgba: 0xFFFFFF77
+};
+
+// An IIFE to generate DEFAULT_ANSI_COLORS. Do not mutate DEFAULT_ANSI_COLORS, instead make a copy
+// and mutate that.
+export const DEFAULT_ANSI_COLORS = (() => {
+  const colors = [
+    // dark:
+    fromHex('#2e3436'),
+    fromHex('#cc0000'),
+    fromHex('#4e9a06'),
+    fromHex('#c4a000'),
+    fromHex('#3465a4'),
+    fromHex('#75507b'),
+    fromHex('#06989a'),
+    fromHex('#d3d7cf'),
+    // bright:
+    fromHex('#555753'),
+    fromHex('#ef2929'),
+    fromHex('#8ae234'),
+    fromHex('#fce94f'),
+    fromHex('#729fcf'),
+    fromHex('#ad7fa8'),
+    fromHex('#34e2e2'),
+    fromHex('#eeeeec')
+  ];
+
+  // Fill in the remaining 240 ANSI colors.
+  // Generate colors (16-231)
+  const v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
+  for (let i = 0; i < 216; i++) {
+    const r = v[(i / 36) % 6 | 0];
+    const g = v[(i / 6) % 6 | 0];
+    const b = v[i % 6];
+    colors.push({
+      css: `#${toPaddedHex(r)}${toPaddedHex(g)}${toPaddedHex(b)}`,
+      // Use >>> 0 to force a conversion to an unsigned int
+      rgba: ((r << 24) | (g << 16) | (b << 8) | 0xFF) >>> 0
+    });
+  }
+
+  // Generate greys (232-255)
+  for (let i = 0; i < 24; i++) {
+    const c = 8 + i * 10;
+    const ch = toPaddedHex(c);
+    colors.push({
+      css: `#${ch}${ch}${ch}`,
+      rgba: ((c << 24) | (c << 16) | (c << 8) | 0xFF) >>> 0
+    });
+  }
+
+  return colors;
+})();
+
+function fromHex(css: string): IColor {
+  return {
+    css,
+    rgba: parseInt(css.slice(1), 16) << 8 | 0xFF
+  };
+}
+
+function toPaddedHex(c: number): string {
+  const s = c.toString(16);
+  return s.length < 2 ? '0' + s : s;
+}
+
+/**
+ * Manages the source of truth for a terminal's colors.
+ */
+export class ColorManager implements IColorManager {
+  public colors: IColorSet;
+  private _ctx: CanvasRenderingContext2D;
+  private _litmusColor: CanvasGradient;
+
+  constructor(document: Document, public allowTransparency: boolean) {
+    const canvas = document.createElement('canvas');
+    canvas.width = 1;
+    canvas.height = 1;
+    const ctx = canvas.getContext('2d');
+    if (!ctx) {
+      throw new Error('Could not get rendering context');
+    }
+    this._ctx = ctx;
+    this._ctx.globalCompositeOperation = 'copy';
+    this._litmusColor = this._ctx.createLinearGradient(0, 0, 1, 1);
+    this.colors = {
+      foreground: DEFAULT_FOREGROUND,
+      background: DEFAULT_BACKGROUND,
+      cursor: DEFAULT_CURSOR,
+      cursorAccent: DEFAULT_CURSOR_ACCENT,
+      selection: DEFAULT_SELECTION,
+      ansi: DEFAULT_ANSI_COLORS.slice()
+    };
+  }
+
+  /**
+   * Sets the terminal's theme.
+   * @param theme The  theme to use. If a partial theme is provided then default
+   * colors will be used where colors are not defined.
+   */
+  public setTheme(theme: ITheme = {}): void {
+    this.colors.foreground = this._parseColor(theme.foreground, DEFAULT_FOREGROUND);
+    this.colors.background = this._parseColor(theme.background, DEFAULT_BACKGROUND);
+    this.colors.cursor = this._parseColor(theme.cursor, DEFAULT_CURSOR, true);
+    this.colors.cursorAccent = this._parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT, true);
+    this.colors.selection = this._parseColor(theme.selection, DEFAULT_SELECTION, true);
+    this.colors.ansi[0] = this._parseColor(theme.black, DEFAULT_ANSI_COLORS[0]);
+    this.colors.ansi[1] = this._parseColor(theme.red, DEFAULT_ANSI_COLORS[1]);
+    this.colors.ansi[2] = this._parseColor(theme.green, DEFAULT_ANSI_COLORS[2]);
+    this.colors.ansi[3] = this._parseColor(theme.yellow, DEFAULT_ANSI_COLORS[3]);
+    this.colors.ansi[4] = this._parseColor(theme.blue, DEFAULT_ANSI_COLORS[4]);
+    this.colors.ansi[5] = this._parseColor(theme.magenta, DEFAULT_ANSI_COLORS[5]);
+    this.colors.ansi[6] = this._parseColor(theme.cyan, DEFAULT_ANSI_COLORS[6]);
+    this.colors.ansi[7] = this._parseColor(theme.white, DEFAULT_ANSI_COLORS[7]);
+    this.colors.ansi[8] = this._parseColor(theme.brightBlack, DEFAULT_ANSI_COLORS[8]);
+    this.colors.ansi[9] = this._parseColor(theme.brightRed, DEFAULT_ANSI_COLORS[9]);
+    this.colors.ansi[10] = this._parseColor(theme.brightGreen, DEFAULT_ANSI_COLORS[10]);
+    this.colors.ansi[11] = this._parseColor(theme.brightYellow, DEFAULT_ANSI_COLORS[11]);
+    this.colors.ansi[12] = this._parseColor(theme.brightBlue, DEFAULT_ANSI_COLORS[12]);
+    this.colors.ansi[13] = this._parseColor(theme.brightMagenta, DEFAULT_ANSI_COLORS[13]);
+    this.colors.ansi[14] = this._parseColor(theme.brightCyan, DEFAULT_ANSI_COLORS[14]);
+    this.colors.ansi[15] = this._parseColor(theme.brightWhite, DEFAULT_ANSI_COLORS[15]);
+  }
+
+  private _parseColor(
+    css: string | undefined,
+    fallback: IColor,
+    allowTransparency: boolean = this.allowTransparency
+  ): IColor {
+    if (css === undefined) {
+      return fallback;
+    }
+
+    // If parsing the value results in failure, then it must be ignored, and the attribute must
+    // retain its previous value.
+    // -- https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
+    this._ctx.fillStyle = this._litmusColor;
+    this._ctx.fillStyle = css;
+    if (typeof this._ctx.fillStyle !== 'string') {
+      console.warn(`Color: ${css} is invalid using fallback ${fallback.css}`);
+      return fallback;
+    }
+
+    this._ctx.fillRect(0, 0, 1, 1);
+    const data = this._ctx.getImageData(0, 0, 1, 1).data;
+
+    if (!allowTransparency && data[3] !== 0xFF) {
+      // Ideally we'd just ignore the alpha channel, but...
+      //
+      // Browsers may not give back exactly the same RGB values we put in, because most/all
+      // convert the color to a pre-multiplied representation. getImageData converts that back to
+      // a un-premultipled representation, but the precision loss may make the RGB channels unuable
+      // on their own.
+      //
+      // E.g. In Chrome #12345610 turns into #10305010, and in the extreme case, 0xFFFFFF00 turns
+      // into 0x00000000.
+      //
+      // "Note: Due to the lossy nature of converting to and from premultiplied alpha color values,
+      // pixels that have just been set using putImageData() might be returned to an equivalent
+      // getImageData() as different values."
+      // -- https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation
+      //
+      // So let's just use the fallback color in this case instead.
+      console.warn(
+        `Color: ${css} is using transparency, but allowTransparency is false. ` +
+        `Using fallback ${fallback.css}.`
+      );
+      return fallback;
+    }
+
+    return {
+      css,
+      rgba: (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0
+    };
+  }
+}
diff --git a/node_modules/xterm/src/browser/Lifecycle.ts b/node_modules/xterm/src/browser/Lifecycle.ts
new file mode 100644 (file)
index 0000000..1344ea9
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+/**
+ * Adds a disposable listener to a node in the DOM, returning the disposable.
+ * @param type The event type.
+ * @param handler The handler for the listener.
+ */
+export function addDisposableDomListener(
+  node: Element | Window | Document,
+  type: string,
+  handler: (e: any) => void,
+  useCapture?: boolean
+): IDisposable {
+  node.addEventListener(type, handler, useCapture);
+  return {
+    dispose: () => {
+      if (!handler) {
+        // Already disposed
+        return;
+      }
+      node.removeEventListener(type, handler, useCapture);
+    }
+  };
+}
diff --git a/node_modules/xterm/src/browser/Linkifier.ts b/node_modules/xterm/src/browser/Linkifier.ts
new file mode 100644 (file)
index 0000000..58aca70
--- /dev/null
@@ -0,0 +1,348 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ILinkifierEvent, ILinkMatcher, LinkMatcherHandler, ILinkMatcherOptions, ILinkifier, IMouseZoneManager, IMouseZone, IRegisteredLinkMatcher } from 'browser/Types';
+import { IBufferStringIteratorResult } from 'common/buffer/Types';
+import { getStringCellWidth } from 'common/CharWidth';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { ILogService, IBufferService } from 'common/services/Services';
+
+/**
+ * Limit of the unwrapping line expansion (overscan) at the top and bottom
+ * of the actual viewport in ASCII characters.
+ * A limit of 2000 should match most sane urls.
+ */
+const OVERSCAN_CHAR_LIMIT = 2000;
+
+/**
+ * The Linkifier applies links to rows shortly after they have been refreshed.
+ */
+export class Linkifier implements ILinkifier {
+  /**
+   * The time to wait after a row is changed before it is linkified. This prevents
+   * the costly operation of searching every row multiple times, potentially a
+   * huge amount of times.
+   */
+  protected static _timeBeforeLatency = 200;
+
+  protected _linkMatchers: IRegisteredLinkMatcher[] = [];
+
+  private _mouseZoneManager: IMouseZoneManager | undefined;
+  private _element: HTMLElement | undefined;
+
+  private _rowsTimeoutId: number | undefined;
+  private _nextLinkMatcherId = 0;
+  private _rowsToLinkify: { start: number | undefined, end: number | undefined };
+
+  private _onLinkHover = new EventEmitter<ILinkifierEvent>();
+  public get onLinkHover(): IEvent<ILinkifierEvent> { return this._onLinkHover.event; }
+  private _onLinkLeave = new EventEmitter<ILinkifierEvent>();
+  public get onLinkLeave(): IEvent<ILinkifierEvent> { return this._onLinkLeave.event; }
+  private _onLinkTooltip = new EventEmitter<ILinkifierEvent>();
+  public get onLinkTooltip(): IEvent<ILinkifierEvent> { return this._onLinkTooltip.event; }
+
+  constructor(
+    protected readonly _bufferService: IBufferService,
+    private readonly _logService: ILogService
+  ) {
+    this._rowsToLinkify = {
+      start: undefined,
+      end: undefined
+    };
+  }
+
+  /**
+   * Attaches the linkifier to the DOM, enabling linkification.
+   * @param mouseZoneManager The mouse zone manager to register link zones with.
+   */
+  public attachToDom(element: HTMLElement, mouseZoneManager: IMouseZoneManager): void {
+    this._element = element;
+    this._mouseZoneManager = mouseZoneManager;
+  }
+
+  /**
+   * Queue linkification on a set of rows.
+   * @param start The row to linkify from (inclusive).
+   * @param end The row to linkify to (inclusive).
+   */
+  public linkifyRows(start: number, end: number): void {
+    // Don't attempt linkify if not yet attached to DOM
+    if (!this._mouseZoneManager) {
+      return;
+    }
+
+    // Increase range to linkify
+    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {
+      this._rowsToLinkify.start = start;
+      this._rowsToLinkify.end = end;
+    } else {
+      this._rowsToLinkify.start = Math.min(this._rowsToLinkify.start, start);
+      this._rowsToLinkify.end = Math.max(this._rowsToLinkify.end, end);
+    }
+
+    // Clear out any existing links on this row range
+    this._mouseZoneManager.clearAll(start, end);
+
+    // Restart timer
+    if (this._rowsTimeoutId) {
+      clearTimeout(this._rowsTimeoutId);
+    }
+    this._rowsTimeoutId = <number><any>setTimeout(() => this._linkifyRows(), Linkifier._timeBeforeLatency);
+  }
+
+  /**
+   * Linkifies the rows requested.
+   */
+  private _linkifyRows(): void {
+    this._rowsTimeoutId = undefined;
+    const buffer = this._bufferService.buffer;
+
+    if (this._rowsToLinkify.start === undefined || this._rowsToLinkify.end === undefined) {
+      this._logService.debug('_rowToLinkify was unset before _linkifyRows was called');
+      return;
+    }
+
+    // Ensure the start row exists
+    const absoluteRowIndexStart = buffer.ydisp + this._rowsToLinkify.start;
+    if (absoluteRowIndexStart >= buffer.lines.length) {
+      return;
+    }
+
+    // Invalidate bad end row values (if a resize happened)
+    const absoluteRowIndexEnd = buffer.ydisp + Math.min(this._rowsToLinkify.end, this._bufferService.rows) + 1;
+
+    // Iterate over the range of unwrapped content strings within start..end
+    // (excluding).
+    // _doLinkifyRow gets full unwrapped lines with the start row as buffer offset
+    // for every matcher.
+    // The unwrapping is needed to also match content that got wrapped across
+    // several buffer lines. To avoid a worst case scenario where the whole buffer
+    // contains just a single unwrapped string we limit this line expansion beyond
+    // the viewport to +OVERSCAN_CHAR_LIMIT chars (overscan) at top and bottom.
+    // This comes with the tradeoff that matches longer than OVERSCAN_CHAR_LIMIT
+    // chars will not match anymore at the viewport borders.
+    const overscanLineLimit = Math.ceil(OVERSCAN_CHAR_LIMIT / this._bufferService.cols);
+    const iterator = this._bufferService.buffer.iterator(
+      false, absoluteRowIndexStart, absoluteRowIndexEnd, overscanLineLimit, overscanLineLimit);
+    while (iterator.hasNext()) {
+      const lineData: IBufferStringIteratorResult = iterator.next();
+      for (let i = 0; i < this._linkMatchers.length; i++) {
+        this._doLinkifyRow(lineData.range.first, lineData.content, this._linkMatchers[i]);
+      }
+    }
+
+    this._rowsToLinkify.start = undefined;
+    this._rowsToLinkify.end = undefined;
+  }
+
+  /**
+   * Registers a link matcher, allowing custom link patterns to be matched and
+   * handled.
+   * @param regex The regular expression to search for. Specifically, this
+   * searches the textContent of the rows. You will want to use \s to match a
+   * space ' ' character for example.
+   * @param handler The callback when the link is called.
+   * @param options Options for the link matcher.
+   * @return The ID of the new matcher, this can be used to deregister.
+   */
+  public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: ILinkMatcherOptions = {}): number {
+    if (!handler) {
+      throw new Error('handler must be defined');
+    }
+    const matcher: IRegisteredLinkMatcher = {
+      id: this._nextLinkMatcherId++,
+      regex,
+      handler,
+      matchIndex: options.matchIndex,
+      validationCallback: options.validationCallback,
+      hoverTooltipCallback: options.tooltipCallback,
+      hoverLeaveCallback: options.leaveCallback,
+      willLinkActivate: options.willLinkActivate,
+      priority: options.priority || 0
+    };
+    this._addLinkMatcherToList(matcher);
+    return matcher.id;
+  }
+
+  /**
+   * Inserts a link matcher to the list in the correct position based on the
+   * priority of each link matcher. New link matchers of equal priority are
+   * considered after older link matchers.
+   * @param matcher The link matcher to be added.
+   */
+  private _addLinkMatcherToList(matcher: IRegisteredLinkMatcher): void {
+    if (this._linkMatchers.length === 0) {
+      this._linkMatchers.push(matcher);
+      return;
+    }
+
+    for (let i = this._linkMatchers.length - 1; i >= 0; i--) {
+      if (matcher.priority <= this._linkMatchers[i].priority) {
+        this._linkMatchers.splice(i + 1, 0, matcher);
+        return;
+      }
+    }
+
+    this._linkMatchers.splice(0, 0, matcher);
+  }
+
+  /**
+   * Deregisters a link matcher if it has been registered.
+   * @param matcherId The link matcher's ID (returned after register)
+   * @return Whether a link matcher was found and deregistered.
+   */
+  public deregisterLinkMatcher(matcherId: number): boolean {
+    for (let i = 0; i < this._linkMatchers.length; i++) {
+      if (this._linkMatchers[i].id === matcherId) {
+        this._linkMatchers.splice(i, 1);
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Linkifies a row given a specific handler.
+   * @param rowIndex The row index to linkify (absolute index).
+   * @param text string content of the unwrapped row.
+   * @param matcher The link matcher for this line.
+   */
+  private _doLinkifyRow(rowIndex: number, text: string, matcher: ILinkMatcher): void {
+    // clone regex to do a global search on text
+    const rex = new RegExp(matcher.regex.source, (matcher.regex.flags || '') + 'g');
+    let match;
+    let stringIndex = -1;
+    while ((match = rex.exec(text)) !== null) {
+      const uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
+      if (!uri) {
+        // something matched but does not comply with the given matchIndex
+        // since this is most likely a bug the regex itself we simply do nothing here
+        this._logService.debug('match found without corresponding matchIndex', match, matcher);
+        break;
+      }
+
+      // Get index, match.index is for the outer match which includes negated chars
+      // therefore we cannot use match.index directly, instead we search the position
+      // of the match group in text again
+      // also correct regex and string search offsets for the next loop run
+      stringIndex = text.indexOf(uri, stringIndex + 1);
+      rex.lastIndex = stringIndex + uri.length;
+      if (stringIndex < 0) {
+        // invalid stringIndex (should not have happened)
+        break;
+      }
+
+      // get the buffer index as [absolute row, col] for the match
+      const bufferIndex = this._bufferService.buffer.stringIndexToBufferIndex(rowIndex, stringIndex);
+      if (bufferIndex[0] < 0) {
+        // invalid bufferIndex (should not have happened)
+        break;
+      }
+
+      const line = this._bufferService.buffer.lines.get(bufferIndex[0]);
+      if (!line) {
+        break;
+      }
+
+      const attr = line.getFg(bufferIndex[1]);
+      const fg = attr ? (attr >> 9) & 0x1ff : undefined;
+
+      if (matcher.validationCallback) {
+        matcher.validationCallback(uri, isValid => {
+          // Discard link if the line has already changed
+          if (this._rowsTimeoutId) {
+            return;
+          }
+          if (isValid) {
+            this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);
+          }
+        });
+      } else {
+        this._addLink(bufferIndex[1], bufferIndex[0] - this._bufferService.buffer.ydisp, uri, matcher, fg);
+      }
+    }
+  }
+
+  /**
+   * Registers a link to the mouse zone manager.
+   * @param x The column the link starts.
+   * @param y The row the link is on.
+   * @param uri The URI of the link.
+   * @param matcher The link matcher for the link.
+   * @param fg The link color for hover event.
+   */
+  private _addLink(x: number, y: number, uri: string, matcher: ILinkMatcher, fg: number | undefined): void {
+    if (!this._mouseZoneManager || !this._element) {
+      return;
+    }
+
+    const width = getStringCellWidth(uri);
+    const x1 = x % this._bufferService.cols;
+    const y1 = y + Math.floor(x / this._bufferService.cols);
+    let x2 = (x1 + width) % this._bufferService.cols;
+    let y2 = y1 + Math.floor((x1 + width) / this._bufferService.cols);
+    if (x2 === 0) {
+      x2 = this._bufferService.cols;
+      y2--;
+    }
+
+    this._mouseZoneManager.add(new MouseZone(
+      x1 + 1,
+      y1 + 1,
+      x2 + 1,
+      y2 + 1,
+      e => {
+        if (matcher.handler) {
+          return matcher.handler(e, uri);
+        }
+        window.open(uri, '_blank');
+      },
+      () => {
+        this._onLinkHover.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));
+        this._element!.classList.add('xterm-cursor-pointer');
+      },
+      e => {
+        this._onLinkTooltip.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));
+        if (matcher.hoverTooltipCallback) {
+          // Note that IViewportRange use 1-based coordinates to align with escape sequences such
+          // as CUP which use 1,1 as the default for row/col
+          matcher.hoverTooltipCallback(e, uri, { start: { x: x1, y: y1 }, end: { x: x2, y: y2 } });
+        }
+      },
+      () => {
+        this._onLinkLeave.fire(this._createLinkHoverEvent(x1, y1, x2, y2, fg));
+        this._element!.classList.remove('xterm-cursor-pointer');
+        if (matcher.hoverLeaveCallback) {
+          matcher.hoverLeaveCallback();
+        }
+      },
+      e => {
+        if (matcher.willLinkActivate) {
+          return matcher.willLinkActivate(e, uri);
+        }
+        return true;
+      }
+    ));
+  }
+
+  private _createLinkHoverEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {
+    return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };
+  }
+}
+
+export class MouseZone implements IMouseZone {
+  constructor(
+    public x1: number,
+    public y1: number,
+    public x2: number,
+    public y2: number,
+    public clickCallback: (e: MouseEvent) => any,
+    public hoverCallback: (e: MouseEvent) => any,
+    public tooltipCallback: (e: MouseEvent) => any,
+    public leaveCallback: () => void,
+    public willLinkActivate: (e: MouseEvent) => boolean
+  ) {
+  }
+}
diff --git a/node_modules/xterm/src/browser/LocalizableStrings.ts b/node_modules/xterm/src/browser/LocalizableStrings.ts
new file mode 100644 (file)
index 0000000..8e78233
--- /dev/null
@@ -0,0 +1,7 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export let promptLabel = 'Terminal input';
+export let tooMuchOutput = 'Too much output to announce, navigate to rows manually to read';
diff --git a/node_modules/xterm/src/browser/MouseZoneManager.ts b/node_modules/xterm/src/browser/MouseZoneManager.ts
new file mode 100644 (file)
index 0000000..7eb7c5f
--- /dev/null
@@ -0,0 +1,241 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Disposable } from 'common/Lifecycle';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { IMouseService, ISelectionService } from 'browser/services/Services';
+import { IMouseZoneManager, IMouseZone } from 'browser/Types';
+import { IBufferService } from 'common/services/Services';
+
+const HOVER_DURATION = 500;
+
+/**
+ * The MouseZoneManager allows components to register zones within the terminal
+ * that trigger hover and click callbacks.
+ *
+ * This class was intentionally made not so robust initially as the only case it
+ * needed to support was single-line links which never overlap. Improvements can
+ * be made in the future.
+ */
+export class MouseZoneManager extends Disposable implements IMouseZoneManager {
+  private _zones: IMouseZone[] = [];
+
+  private _areZonesActive: boolean = false;
+  private _mouseMoveListener: (e: MouseEvent) => any;
+  private _mouseLeaveListener: (e: MouseEvent) => any;
+  private _clickListener: (e: MouseEvent) => any;
+
+  private _tooltipTimeout: number | undefined;
+  private _currentZone: IMouseZone | undefined;
+  private _lastHoverCoords: [number | undefined, number | undefined] = [undefined, undefined];
+  private _initialSelectionLength: number = 0;
+
+  constructor(
+    private readonly _element: HTMLElement,
+    private readonly _screenElement: HTMLElement,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @IMouseService private readonly _mouseService: IMouseService,
+    @ISelectionService private readonly _selectionService: ISelectionService
+  ) {
+    super();
+
+    this.register(addDisposableDomListener(this._element, 'mousedown', e => this._onMouseDown(e)));
+
+    // These events are expensive, only listen to it when mouse zones are active
+    this._mouseMoveListener = e => this._onMouseMove(e);
+    this._mouseLeaveListener = e => this._onMouseLeave(e);
+    this._clickListener = e => this._onClick(e);
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this._deactivate();
+  }
+
+  public add(zone: IMouseZone): void {
+    this._zones.push(zone);
+    if (this._zones.length === 1) {
+      this._activate();
+    }
+  }
+
+  public clearAll(start?: number, end?: number): void {
+    // Exit if there's nothing to clear
+    if (this._zones.length === 0) {
+      return;
+    }
+
+    // Clear all if start/end weren't set
+    if (!start || !end) {
+      start = 0;
+      end = this._bufferService.rows - 1;
+    }
+
+    // Iterate through zones and clear them out if they're within the range
+    for (let i = 0; i < this._zones.length; i++) {
+      const zone = this._zones[i];
+      if ((zone.y1 > start && zone.y1 <= end + 1) ||
+          (zone.y2 > start && zone.y2 <= end + 1) ||
+          (zone.y1 < start && zone.y2 > end + 1)) {
+        if (this._currentZone && this._currentZone === zone) {
+          this._currentZone.leaveCallback();
+          this._currentZone = undefined;
+        }
+        this._zones.splice(i--, 1);
+      }
+    }
+
+    // Deactivate the mouse zone manager if all the zones have been removed
+    if (this._zones.length === 0) {
+      this._deactivate();
+    }
+  }
+
+  private _activate(): void {
+    if (!this._areZonesActive) {
+      this._areZonesActive = true;
+      this._element.addEventListener('mousemove', this._mouseMoveListener);
+      this._element.addEventListener('mouseleave', this._mouseLeaveListener);
+      this._element.addEventListener('click', this._clickListener);
+    }
+  }
+
+  private _deactivate(): void {
+    if (this._areZonesActive) {
+      this._areZonesActive = false;
+      this._element.removeEventListener('mousemove', this._mouseMoveListener);
+      this._element.removeEventListener('mouseleave', this._mouseLeaveListener);
+      this._element.removeEventListener('click', this._clickListener);
+    }
+  }
+
+  private _onMouseMove(e: MouseEvent): void {
+    // TODO: Ideally this would only clear the hover state when the mouse moves
+    // outside of the mouse zone
+    if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {
+      this._onHover(e);
+      // Record the current coordinates
+      this._lastHoverCoords = [e.pageX, e.pageY];
+    }
+  }
+
+  private _onHover(e: MouseEvent): void {
+    const zone = this._findZoneEventAt(e);
+
+    // Do nothing if the zone is the same
+    if (zone === this._currentZone) {
+      return;
+    }
+
+    // Fire the hover end callback and cancel any existing timer if a new zone
+    // is being hovered
+    if (this._currentZone) {
+      this._currentZone.leaveCallback();
+      this._currentZone = undefined;
+      if (this._tooltipTimeout) {
+        clearTimeout(this._tooltipTimeout);
+      }
+    }
+
+    // Exit if there is not zone
+    if (!zone) {
+      return;
+    }
+    this._currentZone = zone;
+
+    // Trigger the hover callback
+    if (zone.hoverCallback) {
+      zone.hoverCallback(e);
+    }
+
+    // Restart the tooltip timeout
+    this._tooltipTimeout = <number><any>setTimeout(() => this._onTooltip(e), HOVER_DURATION);
+  }
+
+  private _onTooltip(e: MouseEvent): void {
+    this._tooltipTimeout = undefined;
+    const zone = this._findZoneEventAt(e);
+    if (zone && zone.tooltipCallback) {
+      zone.tooltipCallback(e);
+    }
+  }
+
+  private _onMouseDown(e: MouseEvent): void {
+    // Store current terminal selection length, to check if we're performing
+    // a selection operation
+    this._initialSelectionLength = this._getSelectionLength();
+
+    // Ignore the event if there are no zones active
+    if (!this._areZonesActive) {
+      return;
+    }
+
+    // Find the active zone, prevent event propagation if found to prevent other
+    // components from handling the mouse event.
+    const zone = this._findZoneEventAt(e);
+    if (zone) {
+      if (zone.willLinkActivate(e)) {
+        e.preventDefault();
+        e.stopImmediatePropagation();
+      }
+    }
+  }
+
+  private _onMouseLeave(e: MouseEvent): void {
+    // Fire the hover end callback and cancel any existing timer if the mouse
+    // leaves the terminal element
+    if (this._currentZone) {
+      this._currentZone.leaveCallback();
+      this._currentZone = undefined;
+      if (this._tooltipTimeout) {
+        clearTimeout(this._tooltipTimeout);
+      }
+    }
+  }
+
+  private _onClick(e: MouseEvent): void {
+    // Find the active zone and click it if found and no selection was
+    // being performed
+    const zone = this._findZoneEventAt(e);
+    const currentSelectionLength = this._getSelectionLength();
+
+    if (zone && currentSelectionLength === this._initialSelectionLength) {
+      zone.clickCallback(e);
+      e.preventDefault();
+      e.stopImmediatePropagation();
+    }
+  }
+
+  private _getSelectionLength(): number {
+    const selectionText = this._selectionService.selectionText;
+    return selectionText ? selectionText.length : 0;
+  }
+
+  private _findZoneEventAt(e: MouseEvent): IMouseZone | undefined {
+    const coords = this._mouseService.getCoords(e, this._screenElement, this._bufferService.cols, this._bufferService.rows);
+    if (!coords) {
+      return undefined;
+    }
+    const x = coords[0];
+    const y = coords[1];
+    for (let i = 0; i < this._zones.length; i++) {
+      const zone = this._zones[i];
+      if (zone.y1 === zone.y2) {
+        // Single line link
+        if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {
+          return zone;
+        }
+      } else {
+        // Multi-line link
+        if ((y === zone.y1 && x >= zone.x1) ||
+            (y === zone.y2 && x < zone.x2) ||
+            (y > zone.y1 && y < zone.y2)) {
+          return zone;
+        }
+      }
+    }
+    return undefined;
+  }
+}
diff --git a/node_modules/xterm/src/browser/RenderDebouncer.ts b/node_modules/xterm/src/browser/RenderDebouncer.ts
new file mode 100644 (file)
index 0000000..27c866d
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+/**
+ * Debounces calls to render terminal rows using animation frames.
+ */
+export class RenderDebouncer implements IDisposable {
+  private _rowStart: number | undefined;
+  private _rowEnd: number | undefined;
+  private _rowCount: number | undefined;
+  private _animationFrame: number | undefined;
+
+  constructor(
+    private _renderCallback: (start: number, end: number) => void
+  ) {
+  }
+
+  public dispose(): void {
+    if (this._animationFrame) {
+      window.cancelAnimationFrame(this._animationFrame);
+      this._animationFrame = undefined;
+    }
+  }
+
+  public refresh(rowStart: number, rowEnd: number, rowCount: number): void {
+    this._rowCount = rowCount;
+    // Get the min/max row start/end for the arg values
+    rowStart = rowStart !== undefined ? rowStart : 0;
+    rowEnd = rowEnd !== undefined ? rowEnd : this._rowCount - 1;
+    // Set the properties to the updated values
+    this._rowStart = this._rowStart !== undefined ? Math.min(this._rowStart, rowStart) : rowStart;
+    this._rowEnd = this._rowEnd !== undefined ? Math.max(this._rowEnd, rowEnd) : rowEnd;
+
+    if (this._animationFrame) {
+      return;
+    }
+
+    this._animationFrame = window.requestAnimationFrame(() => this._innerRefresh());
+  }
+
+  private _innerRefresh(): void {
+    // Make sure values are set
+    if (this._rowStart === undefined || this._rowEnd === undefined || this._rowCount === undefined) {
+      return;
+    }
+
+    // Clamp values
+    this._rowStart = Math.max(this._rowStart, 0);
+    this._rowEnd = Math.min(this._rowEnd, this._rowCount - 1);
+
+    // Run render callback
+    this._renderCallback(this._rowStart, this._rowEnd);
+
+    // Reset debouncer
+    this._rowStart = undefined;
+    this._rowEnd = undefined;
+    this._animationFrame = undefined;
+  }
+}
diff --git a/node_modules/xterm/src/browser/ScreenDprMonitor.ts b/node_modules/xterm/src/browser/ScreenDprMonitor.ts
new file mode 100644 (file)
index 0000000..ec8c6d8
--- /dev/null
@@ -0,0 +1,69 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Disposable } from 'common/Lifecycle';
+
+export type ScreenDprListener = (newDevicePixelRatio?: number, oldDevicePixelRatio?: number) => void;
+
+/**
+ * The screen device pixel ratio monitor allows listening for when the
+ * window.devicePixelRatio value changes. This is done not with polling but with
+ * the use of window.matchMedia to watch media queries. When the event fires,
+ * the listener will be reattached using a different media query to ensure that
+ * any further changes will register.
+ *
+ * The listener should fire on both window zoom changes and switching to a
+ * monitor with a different DPI.
+ */
+export class ScreenDprMonitor extends Disposable {
+  private _currentDevicePixelRatio: number = window.devicePixelRatio;
+  private _outerListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | undefined;
+  private _listener: ScreenDprListener | undefined;
+  private _resolutionMediaMatchList: MediaQueryList | undefined;
+
+  public setListener(listener: ScreenDprListener): void {
+    if (this._listener) {
+      this.clearListener();
+    }
+    this._listener = listener;
+    this._outerListener = () => {
+      if (!this._listener) {
+        return;
+      }
+      this._listener(window.devicePixelRatio, this._currentDevicePixelRatio);
+      this._updateDpr();
+    };
+    this._updateDpr();
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this.clearListener();
+  }
+
+  private _updateDpr(): void {
+    if (!this._resolutionMediaMatchList || !this._outerListener) {
+      return;
+    }
+
+    // Clear listeners for old DPR
+    this._resolutionMediaMatchList.removeListener(this._outerListener);
+
+    // Add listeners for new DPR
+    this._currentDevicePixelRatio = window.devicePixelRatio;
+    this._resolutionMediaMatchList = window.matchMedia(`screen and (resolution: ${window.devicePixelRatio}dppx)`);
+    this._resolutionMediaMatchList.addListener(this._outerListener);
+  }
+
+  public clearListener(): void {
+    if (!this._resolutionMediaMatchList || !this._listener || !this._outerListener) {
+      return;
+    }
+    this._resolutionMediaMatchList.removeListener(this._outerListener);
+    this._resolutionMediaMatchList = undefined;
+    this._listener = undefined;
+    this._outerListener = undefined;
+  }
+}
diff --git a/node_modules/xterm/src/browser/Types.d.ts b/node_modules/xterm/src/browser/Types.d.ts
new file mode 100644 (file)
index 0000000..aa7a4c8
--- /dev/null
@@ -0,0 +1,145 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent } from 'common/EventEmitter';
+import { IDisposable } from 'common/Types';
+
+export interface IColorManager {
+  colors: IColorSet;
+}
+
+export interface IColor {
+  css: string;
+  rgba: number; // 32-bit int with rgba in each byte
+}
+
+export interface IColorSet {
+  foreground: IColor;
+  background: IColor;
+  cursor: IColor;
+  cursorAccent: IColor;
+  selection: IColor;
+  ansi: IColor[];
+}
+
+export interface IPartialColorSet {
+  foreground: IColor;
+  background: IColor;
+  cursor?: IColor;
+  cursorAccent?: IColor;
+  selection?: IColor;
+  ansi: IColor[];
+}
+
+export interface IViewport extends IDisposable {
+  scrollBarWidth: number;
+  syncScrollArea(immediate?: boolean): void;
+  getLinesScrolled(ev: WheelEvent): number;
+  onWheel(ev: WheelEvent): boolean;
+  onTouchStart(ev: TouchEvent): void;
+  onTouchMove(ev: TouchEvent): boolean;
+  onThemeChange(colors: IColorSet): void;
+}
+
+export interface IViewportRange {
+  start: IViewportRangePosition;
+  end: IViewportRangePosition;
+}
+
+export interface IViewportRangePosition {
+  x: number;
+  y: number;
+}
+
+export type LinkMatcherHandler = (event: MouseEvent, uri: string) => void;
+export type LinkMatcherHoverTooltipCallback = (event: MouseEvent, uri: string, position: IViewportRange) => void;
+export type LinkMatcherValidationCallback = (uri: string, callback: (isValid: boolean) => void) => void;
+
+export interface ILinkMatcher {
+  id: number;
+  regex: RegExp;
+  handler: LinkMatcherHandler;
+  hoverTooltipCallback?: LinkMatcherHoverTooltipCallback;
+  hoverLeaveCallback?: () => void;
+  matchIndex?: number;
+  validationCallback?: LinkMatcherValidationCallback;
+  priority?: number;
+  willLinkActivate?: (event: MouseEvent, uri: string) => boolean;
+}
+
+export interface IRegisteredLinkMatcher extends ILinkMatcher {
+  priority: number;
+}
+
+export interface ILinkifierEvent {
+  x1: number;
+  y1: number;
+  x2: number;
+  y2: number;
+  cols: number;
+  fg: number | undefined;
+}
+
+export interface ILinkifier {
+  onLinkHover: IEvent<ILinkifierEvent>;
+  onLinkLeave: IEvent<ILinkifierEvent>;
+  onLinkTooltip: IEvent<ILinkifierEvent>;
+
+  attachToDom(element: HTMLElement, mouseZoneManager: IMouseZoneManager): void;
+  linkifyRows(start: number, end: number): void;
+  registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: ILinkMatcherOptions): number;
+  deregisterLinkMatcher(matcherId: number): boolean;
+}
+
+export interface ILinkMatcherOptions {
+  /**
+   * The index of the link from the regex.match(text) call. This defaults to 0
+   * (for regular expressions without capture groups).
+   */
+  matchIndex?: number;
+  /**
+   * A callback that validates an individual link, returning true if valid and
+   * false if invalid.
+   */
+  validationCallback?: LinkMatcherValidationCallback;
+  /**
+   * A callback that fires when the mouse hovers over a link.
+   */
+  tooltipCallback?: LinkMatcherHoverTooltipCallback;
+  /**
+   * A callback that fires when the mouse leaves a link that was hovered.
+   */
+  leaveCallback?: () => void;
+  /**
+   * The priority of the link matcher, this defines the order in which the link
+   * matcher is evaluated relative to others, from highest to lowest. The
+   * default value is 0.
+   */
+  priority?: number;
+  /**
+   * A callback that fires when the mousedown and click events occur that
+   * determines whether a link will be activated upon click. This enables
+   * only activating a link when a certain modifier is held down, if not the
+   * mouse event will continue propagation (eg. double click to select word).
+   */
+  willLinkActivate?: (event: MouseEvent, uri: string) => boolean;
+}
+
+export interface IMouseZoneManager extends IDisposable {
+  add(zone: IMouseZone): void;
+  clearAll(start?: number, end?: number): void;
+}
+
+export interface IMouseZone {
+  x1: number;
+  x2: number;
+  y1: number;
+  y2: number;
+  clickCallback: (e: MouseEvent) => any;
+  hoverCallback: (e: MouseEvent) => any | undefined;
+  tooltipCallback: (e: MouseEvent) => any | undefined;
+  leaveCallback: () => any | undefined;
+  willLinkActivate: (e: MouseEvent) => boolean;
+}
diff --git a/node_modules/xterm/src/browser/Viewport.ts b/node_modules/xterm/src/browser/Viewport.ts
new file mode 100644 (file)
index 0000000..b88f381
--- /dev/null
@@ -0,0 +1,267 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Disposable } from 'common/Lifecycle';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { IColorSet, IViewport } from 'browser/Types';
+import { ICharSizeService, IRenderService } from 'browser/services/Services';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+const FALLBACK_SCROLL_BAR_WIDTH = 15;
+
+/**
+ * Represents the viewport of a terminal, the visible area within the larger buffer of output.
+ * Logic for the virtual scroll bar is included in this object.
+ */
+export class Viewport extends Disposable implements IViewport {
+  public scrollBarWidth: number = 0;
+  private _currentRowHeight: number = 0;
+  private _lastRecordedBufferLength: number = 0;
+  private _lastRecordedViewportHeight: number = 0;
+  private _lastRecordedBufferHeight: number = 0;
+  private _lastTouchY: number = 0;
+  private _lastScrollTop: number = 0;
+
+  // Stores a partial line amount when scrolling, this is used to keep track of how much of a line
+  // is scrolled so we can "scroll" over partial lines and feel natural on touchpads. This is a
+  // quick fix and could have a more robust solution in place that reset the value when needed.
+  private _wheelPartialScroll: number = 0;
+
+  private _refreshAnimationFrame: number | null = null;
+  private _ignoreNextScrollEvent: boolean = false;
+
+  constructor(
+    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,
+    private readonly _viewportElement: HTMLElement,
+    private readonly _scrollArea: HTMLElement,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @IOptionsService private readonly _optionsService: IOptionsService,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService,
+    @IRenderService private readonly _renderService: IRenderService
+  ) {
+    super();
+
+    // Measure the width of the scrollbar. If it is 0 we can assume it's an OSX overlay scrollbar.
+    // Unfortunately the overlay scrollbar would be hidden underneath the screen element in that case,
+    // therefore we account for a standard amount to make it visible
+    this.scrollBarWidth = (this._viewportElement.offsetWidth - this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH;
+    this.register(addDisposableDomListener(this._viewportElement, 'scroll', this._onScroll.bind(this)));
+
+    // Perform this async to ensure the ICharSizeService is ready.
+    setTimeout(() => this.syncScrollArea(), 0);
+  }
+
+  public onThemeChange(colors: IColorSet): void {
+    this._viewportElement.style.backgroundColor = colors.background.css;
+  }
+
+  /**
+   * Refreshes row height, setting line-height, viewport height and scroll area height if
+   * necessary.
+   */
+  private _refresh(immediate: boolean): void {
+    if (immediate) {
+      this._innerRefresh();
+      if (this._refreshAnimationFrame !== null) {
+        cancelAnimationFrame(this._refreshAnimationFrame);
+      }
+      return;
+    }
+    if (this._refreshAnimationFrame === null) {
+      this._refreshAnimationFrame = requestAnimationFrame(() => this._innerRefresh());
+    }
+  }
+
+  private _innerRefresh(): void {
+    if (this._charSizeService.height > 0) {
+      this._currentRowHeight = this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio;
+      this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;
+      const newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._renderService.dimensions.canvasHeight);
+      if (this._lastRecordedBufferHeight !== newBufferHeight) {
+        this._lastRecordedBufferHeight = newBufferHeight;
+        this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px';
+      }
+    }
+
+    // Sync scrollTop
+    const scrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;
+    if (this._viewportElement.scrollTop !== scrollTop) {
+      // Ignore the next scroll event which will be triggered by setting the scrollTop as we do not
+      // want this event to scroll the terminal
+      this._ignoreNextScrollEvent = true;
+      this._viewportElement.scrollTop = scrollTop;
+    }
+
+    this._refreshAnimationFrame = null;
+  }
+  /**
+   * Updates dimensions and synchronizes the scroll area if necessary.
+   */
+  public syncScrollArea(immediate: boolean = false): void {
+    // If buffer height changed
+    if (this._lastRecordedBufferLength !== this._bufferService.buffer.lines.length) {
+      this._lastRecordedBufferLength = this._bufferService.buffer.lines.length;
+      this._refresh(immediate);
+      return;
+    }
+
+    // If viewport height changed
+    if (this._lastRecordedViewportHeight !== this._renderService.dimensions.canvasHeight) {
+      this._refresh(immediate);
+      return;
+    }
+
+    // If the buffer position doesn't match last scroll top
+    const newScrollTop = this._bufferService.buffer.ydisp * this._currentRowHeight;
+    if (this._lastScrollTop !== newScrollTop) {
+      this._refresh(immediate);
+      return;
+    }
+
+    // If element's scroll top changed, this can happen when hiding the element
+    if (this._lastScrollTop !== this._viewportElement.scrollTop) {
+      this._refresh(immediate);
+      return;
+    }
+
+    // If row height changed
+    if (this._renderService.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) {
+      this._refresh(immediate);
+      return;
+    }
+  }
+
+  /**
+   * Handles scroll events on the viewport, calculating the new viewport and requesting the
+   * terminal to scroll to it.
+   * @param ev The scroll event.
+   */
+  private _onScroll(ev: Event): void {
+    // Record current scroll top position
+    this._lastScrollTop = this._viewportElement.scrollTop;
+
+    // Don't attempt to scroll if the element is not visible, otherwise scrollTop will be corrupt
+    // which causes the terminal to scroll the buffer to the top
+    if (!this._viewportElement.offsetParent) {
+      return;
+    }
+
+    // Ignore the event if it was flagged to ignore (when the source of the event is from Viewport)
+    if (this._ignoreNextScrollEvent) {
+      this._ignoreNextScrollEvent = false;
+      return;
+    }
+
+    const newRow = Math.round(this._lastScrollTop / this._currentRowHeight);
+    const diff = newRow - this._bufferService.buffer.ydisp;
+    this._scrollLines(diff, true);
+  }
+
+  /**
+   * Handles bubbling of scroll event in case the viewport has reached top or bottom
+   * @param ev The scroll event.
+   * @param amount The amount scrolled
+   */
+  private _bubbleScroll(ev: Event, amount: number): boolean {
+    const scrollPosFromTop = this._viewportElement.scrollTop + this._lastRecordedViewportHeight;
+    if ((amount < 0 && this._viewportElement.scrollTop !== 0) ||
+        (amount > 0 &&  scrollPosFromTop < this._lastRecordedBufferHeight)) {
+      if (ev.cancelable) {
+        ev.preventDefault();
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Handles mouse wheel events by adjusting the viewport's scrollTop and delegating the actual
+   * scrolling to `onScroll`, this event needs to be attached manually by the consumer of
+   * `Viewport`.
+   * @param ev The mouse wheel event.
+   */
+  public onWheel(ev: WheelEvent): boolean {
+    const amount = this._getPixelsScrolled(ev);
+    if (amount === 0) {
+      return false;
+    }
+    this._viewportElement.scrollTop += amount;
+    return this._bubbleScroll(ev, amount);
+  }
+
+  private _getPixelsScrolled(ev: WheelEvent): number {
+    // Do nothing if it's not a vertical scroll event
+    if (ev.deltaY === 0) {
+      return 0;
+    }
+
+    // Fallback to WheelEvent.DOM_DELTA_PIXEL
+    let amount = this._applyScrollModifier(ev.deltaY, ev);
+    if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {
+      amount *= this._currentRowHeight;
+    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
+      amount *= this._currentRowHeight * this._bufferService.rows;
+    }
+    return amount;
+  }
+
+  /**
+   * Gets the number of pixels scrolled by the mouse event taking into account what type of delta
+   * is being used.
+   * @param ev The mouse wheel event.
+   */
+  public getLinesScrolled(ev: WheelEvent): number {
+    // Do nothing if it's not a vertical scroll event
+    if (ev.deltaY === 0) {
+      return 0;
+    }
+
+    // Fallback to WheelEvent.DOM_DELTA_LINE
+    let amount = this._applyScrollModifier(ev.deltaY, ev);
+    if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
+      amount /= this._currentRowHeight + 0.0; // Prevent integer division
+      this._wheelPartialScroll += amount;
+      amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);
+      this._wheelPartialScroll %= 1;
+    } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
+      amount *= this._bufferService.rows;
+    }
+    return amount;
+  }
+
+  private _applyScrollModifier(amount: number, ev: WheelEvent): number {
+    const modifier = this._optionsService.options.fastScrollModifier;
+    // Multiply the scroll speed when the modifier is down
+    if ((modifier === 'alt' && ev.altKey) ||
+        (modifier === 'ctrl' && ev.ctrlKey) ||
+        (modifier === 'shift' && ev.shiftKey)) {
+      return amount * this._optionsService.options.fastScrollSensitivity * this._optionsService.options.scrollSensitivity;
+    }
+
+    return amount * this._optionsService.options.scrollSensitivity;
+  }
+
+  /**
+   * Handles the touchstart event, recording the touch occurred.
+   * @param ev The touch event.
+   */
+  public onTouchStart(ev: TouchEvent): void {
+    this._lastTouchY = ev.touches[0].pageY;
+  }
+
+  /**
+   * Handles the touchmove event, scrolling the viewport if the position shifted.
+   * @param ev The touch event.
+   */
+  public onTouchMove(ev: TouchEvent): boolean {
+    const deltaY = this._lastTouchY - ev.touches[0].pageY;
+    this._lastTouchY = ev.touches[0].pageY;
+    if (deltaY === 0) {
+      return false;
+    }
+    this._viewportElement.scrollTop += deltaY;
+    return this._bubbleScroll(ev, deltaY);
+  }
+}
diff --git a/node_modules/xterm/src/browser/input/CompositionHelper.ts b/node_modules/xterm/src/browser/input/CompositionHelper.ts
new file mode 100644 (file)
index 0000000..e6994ea
--- /dev/null
@@ -0,0 +1,229 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharSizeService } from 'browser/services/Services';
+import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';
+
+interface IPosition {
+  start: number;
+  end: number;
+}
+
+/**
+ * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend
+ * events, displaying the in-progress composition to the UI and forwarding the final composition
+ * to the handler.
+ */
+export class CompositionHelper {
+  /**
+   * Whether input composition is currently happening, eg. via a mobile keyboard, speech input or
+   * IME. This variable determines whether the compositionText should be displayed on the UI.
+   */
+  private _isComposing: boolean;
+
+  /**
+   * The position within the input textarea's value of the current composition.
+   */
+  private _compositionPosition: IPosition;
+
+  /**
+   * Whether a composition is in the process of being sent, setting this to false will cancel any
+   * in-progress composition.
+   */
+  private _isSendingComposition: boolean;
+
+  constructor(
+    private readonly _textarea: HTMLTextAreaElement,
+    private readonly _compositionView: HTMLElement,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @IOptionsService private readonly _optionsService: IOptionsService,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService,
+    @ICoreService private readonly _coreService: ICoreService
+  ) {
+    this._isComposing = false;
+    this._isSendingComposition = false;
+    this._compositionPosition = { start: 0, end: 0 };
+  }
+
+  /**
+   * Handles the compositionstart event, activating the composition view.
+   */
+  public compositionstart(): void {
+    this._isComposing = true;
+    this._compositionPosition.start = this._textarea.value.length;
+    this._compositionView.textContent = '';
+    this._compositionView.classList.add('active');
+  }
+
+  /**
+   * Handles the compositionupdate event, updating the composition view.
+   * @param ev The event.
+   */
+  public compositionupdate(ev: CompositionEvent): void {
+    this._compositionView.textContent = ev.data;
+    this.updateCompositionElements();
+    setTimeout(() => {
+      this._compositionPosition.end = this._textarea.value.length;
+    }, 0);
+  }
+
+  /**
+   * Handles the compositionend event, hiding the composition view and sending the composition to
+   * the handler.
+   */
+  public compositionend(): void {
+    this._finalizeComposition(true);
+  }
+
+  /**
+   * Handles the keydown event, routing any necessary events to the CompositionHelper functions.
+   * @param ev The keydown event.
+   * @return Whether the Terminal should continue processing the keydown event.
+   */
+  public keydown(ev: KeyboardEvent): boolean {
+    if (this._isComposing || this._isSendingComposition) {
+      if (ev.keyCode === 229) {
+        // Continue composing if the keyCode is the "composition character"
+        return false;
+      } else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {
+        // Continue composing if the keyCode is a modifier key
+        return false;
+      }
+      // Finish composition immediately. This is mainly here for the case where enter is
+      // pressed and the handler needs to be triggered before the command is executed.
+      this._finalizeComposition(false);
+    }
+
+    if (ev.keyCode === 229) {
+      // If the "composition character" is used but gets to this point it means a non-composition
+      // character (eg. numbers and punctuation) was pressed when the IME was active.
+      this._handleAnyTextareaChanges();
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Finalizes the composition, resuming regular input actions. This is called when a composition
+   * is ending.
+   * @param waitForPropagation Whether to wait for events to propagate before sending
+   *   the input. This should be false if a non-composition keystroke is entered before the
+   *   compositionend event is triggered, such as enter, so that the composition is sent before
+   *   the command is executed.
+   */
+  private _finalizeComposition(waitForPropagation: boolean): void {
+    this._compositionView.classList.remove('active');
+    this._isComposing = false;
+    this._clearTextareaPosition();
+
+    if (!waitForPropagation) {
+      // Cancel any delayed composition send requests and send the input immediately.
+      this._isSendingComposition = false;
+      const input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end);
+      this._coreService.triggerDataEvent(input, true);
+    } else {
+      // Make a deep copy of the composition position here as a new compositionstart event may
+      // fire before the setTimeout executes.
+      const currentCompositionPosition = {
+        start: this._compositionPosition.start,
+        end: this._compositionPosition.end
+      };
+
+      // Since composition* events happen before the changes take place in the textarea on most
+      // browsers, use a setTimeout with 0ms time to allow the native compositionend event to
+      // complete. This ensures the correct character is retrieved.
+      // This solution was used because:
+      // - The compositionend event's data property is unreliable, at least on Chromium
+      // - The last compositionupdate event's data property does not always accurately describe
+      //   the character, a counter example being Korean where an ending consonsant can move to
+      //   the following character if the following input is a vowel.
+      this._isSendingComposition = true;
+      setTimeout(() => {
+        // Ensure that the input has not already been sent
+        if (this._isSendingComposition) {
+          this._isSendingComposition = false;
+          let input;
+          if (this._isComposing) {
+            // Use the end position to get the string if a new composition has started.
+            input = this._textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);
+          } else {
+            // Don't use the end position here in order to pick up any characters after the
+            // composition has finished, for example when typing a non-composition character
+            // (eg. 2) after a composition character.
+            input = this._textarea.value.substring(currentCompositionPosition.start);
+          }
+          this._coreService.triggerDataEvent(input, true);
+        }
+      }, 0);
+    }
+  }
+
+  /**
+   * Apply any changes made to the textarea after the current event chain is allowed to complete.
+   * This should be called when not currently composing but a keydown event with the "composition
+   * character" (229) is triggered, in order to allow non-composition text to be entered when an
+   * IME is active.
+   */
+  private _handleAnyTextareaChanges(): void {
+    const oldValue = this._textarea.value;
+    setTimeout(() => {
+      // Ignore if a composition has started since the timeout
+      if (!this._isComposing) {
+        const newValue = this._textarea.value;
+        const diff = newValue.replace(oldValue, '');
+        if (diff.length > 0) {
+          this._coreService.triggerDataEvent(diff, true);
+        }
+      }
+    }, 0);
+  }
+
+  /**
+   * Positions the composition view on top of the cursor and the textarea just below it (so the
+   * IME helper dialog is positioned correctly).
+   * @param dontRecurse Whether to use setTimeout to recursively trigger another update, this is
+   *   necessary as the IME events across browsers are not consistently triggered.
+   */
+  public updateCompositionElements(dontRecurse?: boolean): void {
+    if (!this._isComposing) {
+      return;
+    }
+
+    if (this._bufferService.buffer.isCursorInViewport) {
+      const cellHeight = Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);
+      const cursorTop = this._bufferService.buffer.y * cellHeight;
+      const cursorLeft = this._bufferService.buffer.x * this._charSizeService.width;
+
+      this._compositionView.style.left = cursorLeft + 'px';
+      this._compositionView.style.top = cursorTop + 'px';
+      this._compositionView.style.height = cellHeight + 'px';
+      this._compositionView.style.lineHeight = cellHeight + 'px';
+      this._compositionView.style.fontFamily = this._optionsService.options.fontFamily;
+      this._compositionView.style.fontSize = this._optionsService.options.fontSize + 'px';
+      // Sync the textarea to the exact position of the composition view so the IME knows where the
+      // text is.
+      const compositionViewBounds = this._compositionView.getBoundingClientRect();
+      this._textarea.style.left = cursorLeft + 'px';
+      this._textarea.style.top = cursorTop + 'px';
+      this._textarea.style.width = compositionViewBounds.width + 'px';
+      this._textarea.style.height = compositionViewBounds.height + 'px';
+      this._textarea.style.lineHeight = compositionViewBounds.height + 'px';
+    }
+
+    if (!dontRecurse) {
+      setTimeout(() => this.updateCompositionElements(true), 0);
+    }
+  }
+
+  /**
+   * Clears the textarea's position so that the cursor does not blink on IE.
+   * @private
+   */
+  private _clearTextareaPosition(): void {
+    this._textarea.style.left = '';
+    this._textarea.style.top = '';
+  }
+}
diff --git a/node_modules/xterm/src/browser/input/Mouse.ts b/node_modules/xterm/src/browser/input/Mouse.ts
new file mode 100644 (file)
index 0000000..2986fb3
--- /dev/null
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export function getCoordsRelativeToElement(event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {
+  const rect = element.getBoundingClientRect();
+  return [event.clientX - rect.left, event.clientY - rect.top];
+}
+
+/**
+ * Gets coordinates within the terminal for a particular mouse event. The result
+ * is returned as an array in the form [x, y] instead of an object as it's a
+ * little faster and this function is used in some low level code.
+ * @param event The mouse event.
+ * @param element The terminal's container element.
+ * @param colCount The number of columns in the terminal.
+ * @param rowCount The number of rows n the terminal.
+ * @param isSelection Whether the request is for the selection or not. This will
+ * apply an offset to the x value such that the left half of the cell will
+ * select that cell and the right half will select the next cell.
+ */
+export function getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, actualCellWidth: number, actualCellHeight: number, isSelection?: boolean): [number, number] | undefined {
+  // Coordinates cannot be measured if there are no valid
+  if (!hasValidCharSize) {
+    return undefined;
+  }
+
+  const coords = getCoordsRelativeToElement(event, element);
+  if (!coords) {
+    return undefined;
+  }
+
+  coords[0] = Math.ceil((coords[0] + (isSelection ? actualCellWidth / 2 : 0)) / actualCellWidth);
+  coords[1] = Math.ceil(coords[1] / actualCellHeight);
+
+  // Ensure coordinates are within the terminal viewport. Note that selections
+  // need an addition point of precision to cover the end point (as characters
+  // cover half of one char and half of the next).
+  coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));
+  coords[1] = Math.min(Math.max(coords[1], 1), rowCount);
+
+  return coords;
+}
+
+/**
+ * Gets coordinates within the terminal for a particular mouse event, wrapping
+ * them to the bounds of the terminal and adding 32 to both the x and y values
+ * as expected by xterm.
+ */
+export function getRawByteCoords(coords: [number, number] | undefined): { x: number, y: number } | undefined {
+  if (!coords) {
+    return undefined;
+  }
+
+  // xterm sends raw bytes and starts at 32 (SP) for each.
+  return { x: coords[0] + 32, y: coords[1] + 32 };
+}
diff --git a/node_modules/xterm/src/browser/input/MoveToCell.ts b/node_modules/xterm/src/browser/input/MoveToCell.ts
new file mode 100644 (file)
index 0000000..406ec80
--- /dev/null
@@ -0,0 +1,230 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { C0 } from 'common/data/EscapeSequences';
+import { IBufferService } from 'common/services/Services';
+
+const enum Direction {
+  UP = 'A',
+  DOWN = 'B',
+  RIGHT = 'C',
+  LEFT = 'D'
+}
+
+/**
+ * Concatenates all the arrow sequences together.
+ * Resets the starting row to an unwrapped row, moves to the requested row,
+ * then moves to requested col.
+ */
+export function moveToCellSequence(targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  const startX = bufferService.buffer.x;
+  const startY = bufferService.buffer.y;
+
+  // The alt buffer should try to navigate between rows
+  if (!bufferService.buffer.hasScrollback) {
+    return resetStartingRow(startX, startY, targetX, targetY, bufferService, applicationCursor) +
+      moveToRequestedRow(startY, targetY, bufferService, applicationCursor) +
+      moveToRequestedCol(startX, startY, targetX, targetY, bufferService, applicationCursor);
+  }
+
+  // Only move horizontally for the normal buffer
+  return moveHorizontallyOnly(startX, startY, targetX, targetY, bufferService, applicationCursor);
+}
+
+/**
+ * If the initial position of the cursor is on a row that is wrapped, move the
+ * cursor up to the first row that is not wrapped to have accurate vertical
+ * positioning.
+ */
+function resetStartingRow(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length === 0) {
+    return '';
+  }
+  return repeat(bufferLine(
+    startX, startY, startX,
+    startY - wrappedRowsForRow(bufferService, startY), false, bufferService
+  ).length, sequence(Direction.LEFT, applicationCursor));
+}
+
+/**
+ * Using the reset starting and ending row, move to the requested row,
+ * ignoring wrapped rows
+ */
+function moveToRequestedRow(startY: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  const startRow = startY - wrappedRowsForRow(bufferService, startY);
+  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);
+
+  const rowsToMove = Math.abs(startRow - endRow) - wrappedRowsCount(startY, targetY, bufferService);
+
+  return repeat(rowsToMove, sequence(verticalDirection(startY, targetY), applicationCursor));
+}
+
+/**
+ * Move to the requested col on the ending row
+ */
+function moveToRequestedCol(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  let startRow;
+  if (moveToRequestedRow(startY, targetY, bufferService, applicationCursor).length > 0) {
+    startRow = targetY - wrappedRowsForRow(bufferService, targetY);
+  } else {
+    startRow = startY;
+  }
+
+  const endRow = targetY;
+  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);
+
+  return repeat(bufferLine(
+    startX, startRow, targetX, endRow,
+    direction === Direction.RIGHT, bufferService
+  ).length, sequence(direction, applicationCursor));
+}
+
+function moveHorizontallyOnly(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): string {
+  const direction = horizontalDirection(startX, startY, targetX, targetY, bufferService, applicationCursor);
+  return repeat(Math.abs(startX - targetX), sequence(direction, applicationCursor));
+}
+
+/**
+ * Utility functions
+ */
+
+/**
+ * Calculates the number of wrapped rows between the unwrapped starting and
+ * ending rows. These rows need to ignored since the cursor skips over them.
+ */
+function wrappedRowsCount(startY: number, targetY: number, bufferService: IBufferService): number {
+  let wrappedRows = 0;
+  const startRow = startY - wrappedRowsForRow(bufferService, startY);
+  const endRow = targetY - wrappedRowsForRow(bufferService, targetY);
+
+  for (let i = 0; i < Math.abs(startRow - endRow); i++) {
+    const direction = verticalDirection(startY, targetY) === Direction.UP ? -1 : 1;
+    const line = bufferService.buffer.lines.get(startRow + (direction * i));
+    if (line && line.isWrapped) {
+      wrappedRows++;
+    }
+  }
+
+  return wrappedRows;
+}
+
+/**
+ * Calculates the number of wrapped rows that make up a given row.
+ * @param currentRow The row to determine how many wrapped rows make it up
+ */
+function wrappedRowsForRow(bufferService: IBufferService, currentRow: number): number {
+  let rowCount = 0;
+  let line = bufferService.buffer.lines.get(currentRow);
+  let lineWraps = line && line.isWrapped;
+
+  while (lineWraps && currentRow >= 0 && currentRow < bufferService.rows) {
+    rowCount++;
+    line = bufferService.buffer.lines.get(--currentRow);
+    lineWraps = line && line.isWrapped;
+  }
+
+  return rowCount;
+}
+
+/**
+ * Direction determiners
+ */
+
+/**
+ * Determines if the right or left arrow is needed
+ */
+function horizontalDirection(startX: number, startY: number, targetX: number, targetY: number, bufferService: IBufferService, applicationCursor: boolean): Direction {
+  let startRow;
+  if (moveToRequestedRow(targetX, targetY, bufferService, applicationCursor).length > 0) {
+    startRow = targetY - wrappedRowsForRow(bufferService, targetY);
+  } else {
+    startRow = startY;
+  }
+
+  if ((startX < targetX &&
+    startRow <= targetY) || // down/right or same y/right
+    (startX >= targetX &&
+    startRow < targetY)) {  // down/left or same y/left
+    return Direction.RIGHT;
+  }
+  return Direction.LEFT;
+}
+
+/**
+ * Determines if the up or down arrow is needed
+ */
+function verticalDirection(startY: number, targetY: number): Direction {
+  return startY > targetY ? Direction.UP : Direction.DOWN;
+}
+
+/**
+ * Constructs the string of chars in the buffer from a starting row and col
+ * to an ending row and col
+ * @param startCol The starting column position
+ * @param startRow The starting row position
+ * @param endCol The ending column position
+ * @param endRow The ending row position
+ * @param forward Direction to move
+ */
+function bufferLine(
+  startCol: number,
+  startRow: number,
+  endCol: number,
+  endRow: number,
+  forward: boolean,
+  bufferService: IBufferService
+): string {
+  let currentCol = startCol;
+  let currentRow = startRow;
+  let bufferStr = '';
+
+  while (currentCol !== endCol || currentRow !== endRow) {
+    currentCol += forward ? 1 : -1;
+
+    if (forward && currentCol > bufferService.cols - 1) {
+      bufferStr += bufferService.buffer.translateBufferLineToString(
+        currentRow, false, startCol, currentCol
+      );
+      currentCol = 0;
+      startCol = 0;
+      currentRow++;
+    } else if (!forward && currentCol < 0) {
+      bufferStr += bufferService.buffer.translateBufferLineToString(
+        currentRow, false, 0, startCol + 1
+      );
+      currentCol = bufferService.cols - 1;
+      startCol = currentCol;
+      currentRow--;
+    }
+  }
+
+  return bufferStr + bufferService.buffer.translateBufferLineToString(
+    currentRow, false, startCol, currentCol
+  );
+}
+
+/**
+ * Constructs the escape sequence for clicking an arrow
+ * @param direction The direction to move
+ */
+function sequence(direction: Direction, applicationCursor: boolean): string {
+  const mod =  applicationCursor ? 'O' : '[';
+  return C0.ESC + mod + direction;
+}
+
+/**
+ * Returns a string repeated a given number of times
+ * Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
+ * @param count The number of times to repeat the string
+ * @param string The string that is to be repeated
+ */
+function repeat(count: number, str: string): string {
+  count = Math.floor(count);
+  let rpt = '';
+  for (let i = 0; i < count; i++) {
+    rpt += str;
+  }
+  return rpt;
+}
diff --git a/node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts b/node_modules/xterm/src/browser/renderer/BaseRenderLayer.ts
new file mode 100644 (file)
index 0000000..e9ad5b3
--- /dev/null
@@ -0,0 +1,385 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions, IRenderLayer } from 'browser/renderer/Types';
+import { ICellData } from 'common/Types';
+import { DEFAULT_COLOR, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE } from 'common/buffer/Constants';
+import { IGlyphIdentifier } from 'browser/renderer/atlas/Types';
+import { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';
+import { acquireCharAtlas } from 'browser/renderer/atlas/CharAtlasCache';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { IColorSet } from 'browser/Types';
+import { CellData } from 'common/buffer/CellData';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+import { throwIfFalsy } from 'browser/renderer/RendererUtils';
+
+export abstract class BaseRenderLayer implements IRenderLayer {
+  private _canvas: HTMLCanvasElement;
+  protected _ctx!: CanvasRenderingContext2D;
+  private _scaledCharWidth: number = 0;
+  private _scaledCharHeight: number = 0;
+  private _scaledCellWidth: number = 0;
+  private _scaledCellHeight: number = 0;
+  private _scaledCharLeft: number = 0;
+  private _scaledCharTop: number = 0;
+
+  protected _charAtlas: BaseCharAtlas | undefined;
+
+  /**
+   * An object that's reused when drawing glyphs in order to reduce GC.
+   */
+  private _currentGlyphIdentifier: IGlyphIdentifier = {
+    chars: '',
+    code: 0,
+    bg: 0,
+    fg: 0,
+    bold: false,
+    dim: false,
+    italic: false
+  };
+
+  constructor(
+    private _container: HTMLElement,
+    id: string,
+    zIndex: number,
+    private _alpha: boolean,
+    protected _colors: IColorSet,
+    private _rendererId: number,
+    protected readonly _bufferService: IBufferService,
+    protected readonly _optionsService: IOptionsService
+  ) {
+    this._canvas = document.createElement('canvas');
+    this._canvas.classList.add(`xterm-${id}-layer`);
+    this._canvas.style.zIndex = zIndex.toString();
+    this._initCanvas();
+    this._container.appendChild(this._canvas);
+  }
+
+  public dispose(): void {
+    this._container.removeChild(this._canvas);
+    if (this._charAtlas) {
+      this._charAtlas.dispose();
+    }
+  }
+
+  private _initCanvas(): void {
+    this._ctx = throwIfFalsy(this._canvas.getContext('2d', {alpha: this._alpha}));
+    // Draw the background if this is an opaque layer
+    if (!this._alpha) {
+      this._clearAll();
+    }
+  }
+
+  public onOptionsChanged(): void {}
+  public onBlur(): void {}
+  public onFocus(): void {}
+  public onCursorMove(): void {}
+  public onGridChanged(startRow: number, endRow: number): void {}
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {}
+
+  public setColors(colorSet: IColorSet): void {
+    this._refreshCharAtlas(colorSet);
+  }
+
+  protected _setTransparency(alpha: boolean): void {
+    // Do nothing when alpha doesn't change
+    if (alpha === this._alpha) {
+      return;
+    }
+
+    // Create new canvas and replace old one
+    const oldCanvas = this._canvas;
+    this._alpha = alpha;
+    // Cloning preserves properties
+    this._canvas = <HTMLCanvasElement>this._canvas.cloneNode();
+    this._initCanvas();
+    this._container.replaceChild(this._canvas, oldCanvas);
+
+    // Regenerate char atlas and force a full redraw
+    this._refreshCharAtlas(this._colors);
+    this.onGridChanged(0, this._bufferService.rows - 1);
+  }
+
+  /**
+   * Refreshes the char atlas, aquiring a new one if necessary.
+   * @param colorSet The color set to use for the char atlas.
+   */
+  private _refreshCharAtlas(colorSet: IColorSet): void {
+    if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) {
+      return;
+    }
+    this._charAtlas = acquireCharAtlas(this._optionsService.options, this._rendererId, colorSet, this._scaledCharWidth, this._scaledCharHeight);
+    this._charAtlas.warmUp();
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    this._scaledCellWidth = dim.scaledCellWidth;
+    this._scaledCellHeight = dim.scaledCellHeight;
+    this._scaledCharWidth = dim.scaledCharWidth;
+    this._scaledCharHeight = dim.scaledCharHeight;
+    this._scaledCharLeft = dim.scaledCharLeft;
+    this._scaledCharTop = dim.scaledCharTop;
+    this._canvas.width = dim.scaledCanvasWidth;
+    this._canvas.height = dim.scaledCanvasHeight;
+    this._canvas.style.width = `${dim.canvasWidth}px`;
+    this._canvas.style.height = `${dim.canvasHeight}px`;
+
+    // Draw the background if this is an opaque layer
+    if (!this._alpha) {
+      this._clearAll();
+    }
+
+    this._refreshCharAtlas(this._colors);
+  }
+
+  public abstract reset(): void;
+
+  /**
+   * Fills 1+ cells completely. This uses the existing fillStyle on the context.
+   * @param x The column to start at.
+   * @param y The row to start at
+   * @param width The number of columns to fill.
+   * @param height The number of rows to fill.
+   */
+  protected _fillCells(x: number, y: number, width: number, height: number): void {
+    this._ctx.fillRect(
+        x * this._scaledCellWidth,
+        y * this._scaledCellHeight,
+        width * this._scaledCellWidth,
+        height * this._scaledCellHeight);
+  }
+
+  /**
+   * Fills a 1px line (2px on HDPI) at the bottom of the cell. This uses the
+   * existing fillStyle on the context.
+   * @param x The column to fill.
+   * @param y The row to fill.
+   */
+  protected _fillBottomLineAtCells(x: number, y: number, width: number = 1): void {
+    this._ctx.fillRect(
+        x * this._scaledCellWidth,
+        (y + 1) * this._scaledCellHeight - window.devicePixelRatio - 1 /* Ensure it's drawn within the cell */,
+        width * this._scaledCellWidth,
+        window.devicePixelRatio);
+  }
+
+  /**
+   * Fills a 1px line (2px on HDPI) at the left of the cell. This uses the
+   * existing fillStyle on the context.
+   * @param x The column to fill.
+   * @param y The row to fill.
+   */
+  protected _fillLeftLineAtCell(x: number, y: number): void {
+    this._ctx.fillRect(
+        x * this._scaledCellWidth,
+        y * this._scaledCellHeight,
+        window.devicePixelRatio,
+        this._scaledCellHeight);
+  }
+
+  /**
+   * Strokes a 1px rectangle (2px on HDPI) around a cell. This uses the existing
+   * strokeStyle on the context.
+   * @param x The column to fill.
+   * @param y The row to fill.
+   */
+  protected _strokeRectAtCell(x: number, y: number, width: number, height: number): void {
+    this._ctx.lineWidth = window.devicePixelRatio;
+    this._ctx.strokeRect(
+        x * this._scaledCellWidth + window.devicePixelRatio / 2,
+        y * this._scaledCellHeight + (window.devicePixelRatio / 2),
+        width * this._scaledCellWidth - window.devicePixelRatio,
+        (height * this._scaledCellHeight) - window.devicePixelRatio);
+  }
+
+  /**
+   * Clears the entire canvas.
+   */
+  protected _clearAll(): void {
+    if (this._alpha) {
+      this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
+    } else {
+      this._ctx.fillStyle = this._colors.background.css;
+      this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
+    }
+  }
+
+  /**
+   * Clears 1+ cells completely.
+   * @param x The column to start at.
+   * @param y The row to start at.
+   * @param width The number of columns to clear.
+   * @param height The number of rows to clear.
+   */
+  protected _clearCells(x: number, y: number, width: number, height: number): void {
+    if (this._alpha) {
+      this._ctx.clearRect(
+          x * this._scaledCellWidth,
+          y * this._scaledCellHeight,
+          width * this._scaledCellWidth,
+          height * this._scaledCellHeight);
+    } else {
+      this._ctx.fillStyle = this._colors.background.css;
+      this._ctx.fillRect(
+          x * this._scaledCellWidth,
+          y * this._scaledCellHeight,
+          width * this._scaledCellWidth,
+          height * this._scaledCellHeight);
+    }
+  }
+
+  /**
+   * Draws a truecolor character at the cell. The character will be clipped to
+   * ensure that it fits with the cell, including the cell to the right if it's
+   * a wide character. This uses the existing fillStyle on the context.
+   * @param cell The cell data for the character to draw.
+   * @param x The column to draw at.
+   * @param y The row to draw at.
+   * @param color The color of the character.
+   */
+  protected _fillCharTrueColor(cell: CellData, x: number, y: number): void {
+    this._ctx.font = this._getFont(false, false);
+    this._ctx.textBaseline = 'middle';
+    this._clipRow(y);
+    this._ctx.fillText(
+        cell.getChars(),
+        x * this._scaledCellWidth + this._scaledCharLeft,
+        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);
+  }
+
+  /**
+   * Draws one or more characters at a cell. If possible this will draw using
+   * the character atlas to reduce draw time.
+   * @param chars The character or characters.
+   * @param code The character code.
+   * @param width The width of the characters.
+   * @param x The column to draw at.
+   * @param y The row to draw at.
+   * @param fg The foreground color, in the format stored within the attributes.
+   * @param bg The background color, in the format stored within the attributes.
+   * This is used to validate whether a cached image can be used.
+   * @param bold Whether the text is bold.
+   */
+  protected _drawChars(cell: ICellData, x: number, y: number): void {
+
+    // skip cache right away if we draw in RGB
+    // Note: to avoid bad runtime JoinedCellData will be skipped
+    //       in the cache handler itself (atlasDidDraw == false) and
+    //       fall through to uncached later down below
+    if (cell.isFgRGB() || cell.isBgRGB()) {
+      this._drawUncachedChars(cell, x, y);
+      return;
+    }
+
+    let fg;
+    let bg;
+    if (cell.isInverse()) {
+      fg = (cell.isBgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getBgColor();
+      bg = (cell.isFgDefault()) ? INVERTED_DEFAULT_COLOR : cell.getFgColor();
+    } else {
+      bg = (cell.isBgDefault()) ? DEFAULT_COLOR : cell.getBgColor();
+      fg = (cell.isFgDefault()) ? DEFAULT_COLOR : cell.getFgColor();
+    }
+
+    const drawInBrightColor = this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8 && fg !== INVERTED_DEFAULT_COLOR;
+
+    fg += drawInBrightColor ? 8 : 0;
+    this._currentGlyphIdentifier.chars = cell.getChars() || WHITESPACE_CELL_CHAR;
+    this._currentGlyphIdentifier.code = cell.getCode() || WHITESPACE_CELL_CODE;
+    this._currentGlyphIdentifier.bg = bg;
+    this._currentGlyphIdentifier.fg = fg;
+    this._currentGlyphIdentifier.bold = !!cell.isBold();
+    this._currentGlyphIdentifier.dim = !!cell.isDim();
+    this._currentGlyphIdentifier.italic = !!cell.isItalic();
+    const atlasDidDraw = this._charAtlas && this._charAtlas.draw(
+      this._ctx,
+      this._currentGlyphIdentifier,
+      x * this._scaledCellWidth + this._scaledCharLeft,
+      y * this._scaledCellHeight + this._scaledCharTop
+    );
+
+    if (!atlasDidDraw) {
+      this._drawUncachedChars(cell, x, y);
+    }
+  }
+
+  /**
+   * Draws one or more characters at one or more cells. The character(s) will be
+   * clipped to ensure that they fit with the cell(s), including the cell to the
+   * right if the last character is a wide character.
+   * @param chars The character.
+   * @param width The width of the character.
+   * @param fg The foreground color, in the format stored within the attributes.
+   * @param x The column to draw at.
+   * @param y The row to draw at.
+   */
+  private _drawUncachedChars(cell: ICellData, x: number, y: number): void {
+    this._ctx.save();
+    this._ctx.font = this._getFont(!!cell.isBold(), !!cell.isItalic());
+    this._ctx.textBaseline = 'middle';
+
+    if (cell.isInverse()) {
+      if (cell.isBgDefault()) {
+        this._ctx.fillStyle = this._colors.background.css;
+      } else if (cell.isBgRGB()) {
+        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;
+      } else {
+        this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;
+      }
+    } else {
+      if (cell.isFgDefault()) {
+        this._ctx.fillStyle = this._colors.foreground.css;
+      } else if (cell.isFgRGB()) {
+        this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;
+      } else {
+        let fg = cell.getFgColor();
+        if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {
+          fg += 8;
+        }
+        this._ctx.fillStyle = this._colors.ansi[fg].css;
+      }
+    }
+
+    this._clipRow(y);
+
+    // Apply alpha to dim the character
+    if (cell.isDim()) {
+      this._ctx.globalAlpha = DIM_OPACITY;
+    }
+    // Draw the character
+    this._ctx.fillText(
+        cell.getChars(),
+        x * this._scaledCellWidth + this._scaledCharLeft,
+        y * this._scaledCellHeight + this._scaledCharTop + this._scaledCharHeight / 2);
+    this._ctx.restore();
+  }
+
+  /**
+   * Clips a row to ensure no pixels will be drawn outside the cells in the row.
+   * @param y The row to clip.
+   */
+  private _clipRow(y: number): void {
+    this._ctx.beginPath();
+    this._ctx.rect(
+        0,
+        y * this._scaledCellHeight,
+        this._bufferService.cols * this._scaledCellWidth,
+        this._scaledCellHeight);
+    this._ctx.clip();
+  }
+
+  /**
+   * Gets the current font.
+   * @param isBold If we should use the bold fontWeight.
+   */
+  protected _getFont(isBold: boolean, isItalic: boolean): string {
+    const fontWeight = isBold ? this._optionsService.options.fontWeightBold : this._optionsService.options.fontWeight;
+    const fontStyle = isItalic ? 'italic' : '';
+
+    return `${fontStyle} ${fontWeight} ${this._optionsService.options.fontSize * window.devicePixelRatio}px ${this._optionsService.options.fontFamily}`;
+  }
+}
+
diff --git a/node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts b/node_modules/xterm/src/browser/renderer/CharacterJoinerRegistry.ts
new file mode 100644 (file)
index 0000000..5385b76
--- /dev/null
@@ -0,0 +1,326 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferLine, ICellData, CharData } from 'common/Types';
+import { ICharacterJoinerRegistry, ICharacterJoiner } from 'browser/renderer/Types';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { IBufferService } from 'common/services/Services';
+
+export class JoinedCellData extends AttributeData implements ICellData {
+  private _width: number;
+  // .content carries no meaning for joined CellData, simply nullify it
+  // thus we have to overload all other .content accessors
+  public content: number = 0;
+  public fg: number;
+  public bg: number;
+  public combinedData: string = '';
+
+  constructor(firstCell: ICellData, chars: string, width: number) {
+    super();
+    this.fg = firstCell.fg;
+    this.bg = firstCell.bg;
+    this.combinedData = chars;
+    this._width = width;
+  }
+
+  public isCombined(): number {
+    // always mark joined cell data as combined
+    return Content.IS_COMBINED_MASK;
+  }
+
+  public getWidth(): number {
+    return this._width;
+  }
+
+  public getChars(): string {
+    return this.combinedData;
+  }
+
+  public getCode(): number {
+    // code always gets the highest possible fake codepoint (read as -1)
+    // this is needed as code is used by caches as identifier
+    return 0x1FFFFF;
+  }
+
+  public setFromCharData(value: CharData): void {
+    throw new Error('not implemented');
+  }
+
+  public getAsCharData(): CharData {
+    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
+  }
+}
+
+export class CharacterJoinerRegistry implements ICharacterJoinerRegistry {
+
+  private _characterJoiners: ICharacterJoiner[] = [];
+  private _nextCharacterJoinerId: number = 0;
+  private _workCell: CellData = new CellData();
+
+  constructor(private _bufferService: IBufferService) { }
+
+  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
+    const joiner: ICharacterJoiner = {
+      id: this._nextCharacterJoinerId++,
+      handler
+    };
+
+    this._characterJoiners.push(joiner);
+    return joiner.id;
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): boolean {
+    for (let i = 0; i < this._characterJoiners.length; i++) {
+      if (this._characterJoiners[i].id === joinerId) {
+        this._characterJoiners.splice(i, 1);
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  public getJoinedCharacters(row: number): [number, number][] {
+    if (this._characterJoiners.length === 0) {
+      return [];
+    }
+
+    const line = this._bufferService.buffer.lines.get(row);
+    if (!line || line.length === 0) {
+      return [];
+    }
+
+    const ranges: [number, number][] = [];
+    const lineStr = line.translateToString(true);
+
+    // Because some cells can be represented by multiple javascript characters,
+    // we track the cell and the string indexes separately. This allows us to
+    // translate the string ranges we get from the joiners back into cell ranges
+    // for use when rendering
+    let rangeStartColumn = 0;
+    let currentStringIndex = 0;
+    let rangeStartStringIndex = 0;
+    let rangeAttrFG = line.getFg(0);
+    let rangeAttrBG = line.getBg(0);
+
+    for (let x = 0; x < line.getTrimmedLength(); x++) {
+      line.loadCell(x, this._workCell);
+
+      if (this._workCell.getWidth() === 0) {
+        // If this character is of width 0, skip it.
+        continue;
+      }
+
+      // End of range
+      if (this._workCell.fg !== rangeAttrFG || this._workCell.bg !== rangeAttrBG) {
+        // If we ended up with a sequence of more than one character,
+        // look for ranges to join.
+        if (x - rangeStartColumn > 1) {
+          const joinedRanges = this._getJoinedRanges(
+            lineStr,
+            rangeStartStringIndex,
+            currentStringIndex,
+            line,
+            rangeStartColumn
+          );
+          for (let i = 0; i < joinedRanges.length; i++) {
+            ranges.push(joinedRanges[i]);
+          }
+        }
+
+        // Reset our markers for a new range.
+        rangeStartColumn = x;
+        rangeStartStringIndex = currentStringIndex;
+        rangeAttrFG = this._workCell.fg;
+        rangeAttrBG = this._workCell.bg;
+      }
+
+      currentStringIndex += this._workCell.getChars().length || WHITESPACE_CELL_CHAR.length;
+    }
+
+    // Process any trailing ranges.
+    if (this._bufferService.cols - rangeStartColumn > 1) {
+      const joinedRanges = this._getJoinedRanges(
+        lineStr,
+        rangeStartStringIndex,
+        currentStringIndex,
+        line,
+        rangeStartColumn
+      );
+      for (let i = 0; i < joinedRanges.length; i++) {
+        ranges.push(joinedRanges[i]);
+      }
+    }
+
+    return ranges;
+  }
+
+  /**
+   * Given a segment of a line of text, find all ranges of text that should be
+   * joined in a single rendering unit. Ranges are internally converted to
+   * column ranges, rather than string ranges.
+   * @param line String representation of the full line of text
+   * @param startIndex Start position of the range to search in the string (inclusive)
+   * @param endIndex End position of the range to search in the string (exclusive)
+   */
+  private _getJoinedRanges(line: string, startIndex: number, endIndex: number, lineData: IBufferLine, startCol: number): [number, number][] {
+    const text = line.substring(startIndex, endIndex);
+    // At this point we already know that there is at least one joiner so
+    // we can just pull its value and assign it directly rather than
+    // merging it into an empty array, which incurs unnecessary writes.
+    const joinedRanges: [number, number][] = this._characterJoiners[0].handler(text);
+    for (let i = 1; i < this._characterJoiners.length; i++) {
+      // We merge any overlapping ranges across the different joiners
+      const joinerRanges = this._characterJoiners[i].handler(text);
+      for (let j = 0; j < joinerRanges.length; j++) {
+        CharacterJoinerRegistry._mergeRanges(joinedRanges, joinerRanges[j]);
+      }
+    }
+    this._stringRangesToCellRanges(joinedRanges, lineData, startCol);
+    return joinedRanges;
+  }
+
+  /**
+   * Modifies the provided ranges in-place to adjust for variations between
+   * string length and cell width so that the range represents a cell range,
+   * rather than the string range the joiner provides.
+   * @param ranges String ranges containing start (inclusive) and end (exclusive) index
+   * @param line Cell data for the relevant line in the terminal
+   * @param startCol Offset within the line to start from
+   */
+  private _stringRangesToCellRanges(ranges: [number, number][], line: IBufferLine, startCol: number): void {
+    let currentRangeIndex = 0;
+    let currentRangeStarted = false;
+    let currentStringIndex = 0;
+    let currentRange = ranges[currentRangeIndex];
+
+    // If we got through all of the ranges, stop searching
+    if (!currentRange) {
+      return;
+    }
+
+    for (let x = startCol; x < this._bufferService.cols; x++) {
+      const width = line.getWidth(x);
+      const length = line.getString(x).length || WHITESPACE_CELL_CHAR.length;
+
+      // We skip zero-width characters when creating the string to join the text
+      // so we do the same here
+      if (width === 0) {
+        continue;
+      }
+
+      // Adjust the start of the range
+      if (!currentRangeStarted && currentRange[0] <= currentStringIndex) {
+        currentRange[0] = x;
+        currentRangeStarted = true;
+      }
+
+      // Adjust the end of the range
+      if (currentRange[1] <= currentStringIndex) {
+        currentRange[1] = x;
+
+        // We're finished with this range, so we move to the next one
+        currentRange = ranges[++currentRangeIndex];
+
+        // If there are no more ranges left, stop searching
+        if (!currentRange) {
+          break;
+        }
+
+        // Ranges can be on adjacent characters. Because the end index of the
+        // ranges are exclusive, this means that the index for the start of a
+        // range can be the same as the end index of the previous range. To
+        // account for the start of the next range, we check here just in case.
+        if (currentRange[0] <= currentStringIndex) {
+          currentRange[0] = x;
+          currentRangeStarted = true;
+        } else {
+          currentRangeStarted = false;
+        }
+      }
+
+      // Adjust the string index based on the character length to line up with
+      // the column adjustment
+      currentStringIndex += length;
+    }
+
+    // If there is still a range left at the end, it must extend all the way to
+    // the end of the line.
+    if (currentRange) {
+      currentRange[1] = this._bufferService.cols;
+    }
+  }
+
+  /**
+   * Merges the range defined by the provided start and end into the list of
+   * existing ranges. The merge is done in place on the existing range for
+   * performance and is also returned.
+   * @param ranges Existing range list
+   * @param newRange Tuple of two numbers representing the new range to merge in.
+   * @returns The ranges input with the new range merged in place
+   */
+  private static _mergeRanges(ranges: [number, number][], newRange: [number, number]): [number, number][] {
+    let inRange = false;
+    for (let i = 0; i < ranges.length; i++) {
+      const range = ranges[i];
+      if (!inRange) {
+        if (newRange[1] <= range[0]) {
+          // Case 1: New range is before the search range
+          ranges.splice(i, 0, newRange);
+          return ranges;
+        }
+
+        if (newRange[1] <= range[1]) {
+          // Case 2: New range is either wholly contained within the
+          // search range or overlaps with the front of it
+          range[0] = Math.min(newRange[0], range[0]);
+          return ranges;
+        }
+
+        if (newRange[0] < range[1]) {
+          // Case 3: New range either wholly contains the search range
+          // or overlaps with the end of it
+          range[0] = Math.min(newRange[0], range[0]);
+          inRange = true;
+        }
+
+        // Case 4: New range starts after the search range
+        continue;
+      } else {
+        if (newRange[1] <= range[0]) {
+          // Case 5: New range extends from previous range but doesn't
+          // reach the current one
+          ranges[i - 1][1] = newRange[1];
+          return ranges;
+        }
+
+        if (newRange[1] <= range[1]) {
+          // Case 6: New range extends from prvious range into the
+          // current range
+          ranges[i - 1][1] = Math.max(newRange[1], range[1]);
+          ranges.splice(i, 1);
+          return ranges;
+        }
+
+        // Case 7: New range extends from previous range past the
+        // end of the current range
+        ranges.splice(i, 1);
+        i--;
+      }
+    }
+
+    if (inRange) {
+      // Case 8: New range extends past the last existing range
+      ranges[ranges.length - 1][1] = newRange[1];
+    } else {
+      // Case 9: New range starts after the last existing range
+      ranges.push(newRange);
+    }
+
+    return ranges;
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/GridCache.ts b/node_modules/xterm/src/browser/renderer/GridCache.ts
new file mode 100644 (file)
index 0000000..b48798d
--- /dev/null
@@ -0,0 +1,33 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export class GridCache<T> {
+  public cache: (T | undefined)[][];
+
+  public constructor() {
+    this.cache = [];
+  }
+
+  public resize(width: number, height: number): void {
+    for (let x = 0; x < width; x++) {
+      if (this.cache.length <= x) {
+        this.cache.push([]);
+      }
+      for (let y = this.cache[x].length; y < height; y++) {
+        this.cache[x].push(undefined);
+      }
+      this.cache[x].length = height;
+    }
+    this.cache.length = width;
+  }
+
+  public clear(): void {
+    for (let x = 0; x < this.cache.length; x++) {
+      for (let y = 0; y < this.cache[x].length; y++) {
+        this.cache[x][y] = undefined;
+      }
+    }
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts b/node_modules/xterm/src/browser/renderer/LinkRenderLayer.ts
new file mode 100644 (file)
index 0000000..a7be54e
--- /dev/null
@@ -0,0 +1,79 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions } from 'browser/renderer/Types';
+import { BaseRenderLayer } from './BaseRenderLayer';
+import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { is256Color } from 'browser/renderer/atlas/CharAtlasUtils';
+import { IColorSet, ILinkifierEvent, ILinkifier } from 'browser/Types';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+export class LinkRenderLayer extends BaseRenderLayer {
+  private _state: ILinkifierEvent | undefined;
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    rendererId: number,
+    linkifier: ILinkifier,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'link', zIndex, true, colors, rendererId, bufferService, optionsService);
+    linkifier.onLinkHover(e => this._onLinkHover(e));
+    linkifier.onLinkLeave(e => this._onLinkLeave(e));
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._state = undefined;
+  }
+
+  public reset(): void {
+    this._clearCurrentLink();
+  }
+
+  private _clearCurrentLink(): void {
+    if (this._state) {
+      this._clearCells(this._state.x1, this._state.y1, this._state.cols - this._state.x1, 1);
+      const middleRowCount = this._state.y2 - this._state.y1 - 1;
+      if (middleRowCount > 0) {
+        this._clearCells(0, this._state.y1 + 1, this._state.cols, middleRowCount);
+      }
+      this._clearCells(0, this._state.y2, this._state.x2, 1);
+      this._state = undefined;
+    }
+  }
+
+  private _onLinkHover(e: ILinkifierEvent): void {
+    if (e.fg === INVERTED_DEFAULT_COLOR) {
+      this._ctx.fillStyle = this._colors.background.css;
+    } else if (e.fg && is256Color(e.fg)) {
+      // 256 color support
+      this._ctx.fillStyle = this._colors.ansi[e.fg].css;
+    } else {
+      this._ctx.fillStyle = this._colors.foreground.css;
+    }
+
+    if (e.y1 === e.y2) {
+      // Single line link
+      this._fillBottomLineAtCells(e.x1, e.y1, e.x2 - e.x1);
+    } else {
+      // Multi-line link
+      this._fillBottomLineAtCells(e.x1, e.y1, e.cols - e.x1);
+      for (let y = e.y1 + 1; y < e.y2; y++) {
+        this._fillBottomLineAtCells(0, y, e.cols);
+      }
+      this._fillBottomLineAtCells(0, e.y2, e.x2);
+    }
+    this._state = e;
+  }
+
+  private _onLinkLeave(e: ILinkifierEvent): void {
+    this._clearCurrentLink();
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/RendererUtils.ts b/node_modules/xterm/src/browser/renderer/RendererUtils.ts
new file mode 100644 (file)
index 0000000..48fd26a
--- /dev/null
@@ -0,0 +1,11 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export function throwIfFalsy<T>(value: T | undefined | null): T {
+  if (!value) {
+    throw new Error('value must not be falsy');
+  }
+  return value;
+}
diff --git a/node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts b/node_modules/xterm/src/browser/renderer/SelectionRenderLayer.ts
new file mode 100644 (file)
index 0000000..5cd2fd9
--- /dev/null
@@ -0,0 +1,127 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions } from 'browser/renderer/Types';
+import { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';
+import { IColorSet } from 'browser/Types';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+interface ISelectionState {
+  start?: [number, number];
+  end?: [number, number];
+  columnSelectMode?: boolean;
+  ydisp?: number;
+}
+
+export class SelectionRenderLayer extends BaseRenderLayer {
+  private _state!: ISelectionState;
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    rendererId: number,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'selection', zIndex, true, colors, rendererId, bufferService, optionsService);
+    this._clearState();
+  }
+
+  private _clearState(): void {
+    this._state = {
+      start: undefined,
+      end: undefined,
+      columnSelectMode: undefined,
+      ydisp: undefined
+    };
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._clearState();
+  }
+
+  public reset(): void {
+    if (this._state.start && this._state.end) {
+      this._clearState();
+      this._clearAll();
+    }
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {
+    // Selection has not changed
+    if (!this._didStateChange(start, end, columnSelectMode, this._bufferService.buffer.ydisp)) {
+      return;
+    }
+
+    // Remove all selections
+    this._clearAll();
+
+    // Selection does not exist
+    if (!start || !end) {
+      this._clearState();
+      return;
+    }
+
+    // Translate from buffer position to viewport position
+    const viewportStartRow = start[1] - this._bufferService.buffer.ydisp;
+    const viewportEndRow = end[1] - this._bufferService.buffer.ydisp;
+    const viewportCappedStartRow = Math.max(viewportStartRow, 0);
+    const viewportCappedEndRow = Math.min(viewportEndRow, this._bufferService.rows - 1);
+
+    // No need to draw the selection
+    if (viewportCappedStartRow >= this._bufferService.rows || viewportCappedEndRow < 0) {
+      return;
+    }
+
+    this._ctx.fillStyle = this._colors.selection.css;
+
+    if (columnSelectMode) {
+      const startCol = start[0];
+      const width = end[0] - startCol;
+      const height = viewportCappedEndRow - viewportCappedStartRow + 1;
+      this._fillCells(startCol, viewportCappedStartRow, width, height);
+    } else {
+      // Draw first row
+      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;
+      const startRowEndCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;
+      this._fillCells(startCol, viewportCappedStartRow, startRowEndCol - startCol, 1);
+
+      // Draw middle rows
+      const middleRowsCount = Math.max(viewportCappedEndRow - viewportCappedStartRow - 1, 0);
+      this._fillCells(0, viewportCappedStartRow + 1, this._bufferService.cols, middleRowsCount);
+
+      // Draw final row
+      if (viewportCappedStartRow !== viewportCappedEndRow) {
+        // Only draw viewportEndRow if it's not the same as viewportStartRow
+        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._bufferService.cols;
+        this._fillCells(0, viewportCappedEndRow, endCol, 1);
+      }
+    }
+
+    // Save state for next render
+    this._state.start = [start[0], start[1]];
+    this._state.end = [end[0], end[1]];
+    this._state.columnSelectMode = columnSelectMode;
+    this._state.ydisp = this._bufferService.buffer.ydisp;
+  }
+
+  private _didStateChange(start: [number, number], end: [number, number], columnSelectMode: boolean, ydisp: number): boolean {
+    return !this._areCoordinatesEqual(start, this._state.start) ||
+      !this._areCoordinatesEqual(end, this._state.end) ||
+      columnSelectMode !== this._state.columnSelectMode ||
+      ydisp !== this._state.ydisp;
+  }
+
+  private _areCoordinatesEqual(coord1: [number, number] | undefined, coord2: [number, number] | undefined): boolean {
+    if (!coord1 || !coord2) {
+      return false;
+    }
+
+    return coord1[0] === coord2[0] && coord1[1] === coord2[1];
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/TextRenderLayer.ts b/node_modules/xterm/src/browser/renderer/TextRenderLayer.ts
new file mode 100644 (file)
index 0000000..330400c
--- /dev/null
@@ -0,0 +1,324 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharacterJoinerRegistry, IRenderDimensions } from 'browser/renderer/Types';
+import { CharData, ICellData } from 'common/Types';
+import { GridCache } from 'browser/renderer/GridCache';
+import { BaseRenderLayer } from 'browser/renderer/BaseRenderLayer';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { NULL_CELL_CODE, Content } from 'common/buffer/Constants';
+import { JoinedCellData } from 'browser/renderer/CharacterJoinerRegistry';
+import { IColorSet } from 'browser/Types';
+import { CellData } from 'common/buffer/CellData';
+import { IOptionsService, IBufferService } from 'common/services/Services';
+
+/**
+ * This CharData looks like a null character, which will forc a clear and render
+ * when the character changes (a regular space ' ' character may not as it's
+ * drawn state is a cleared cell).
+ */
+// const OVERLAP_OWNED_CHAR_DATA: CharData = [null, '', 0, -1];
+
+export class TextRenderLayer extends BaseRenderLayer {
+  private _state: GridCache<CharData>;
+  private _characterWidth: number = 0;
+  private _characterFont: string = '';
+  private _characterOverlapCache: { [key: string]: boolean } = {};
+  private _characterJoinerRegistry: ICharacterJoinerRegistry;
+  private _workCell = new CellData();
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    characterJoinerRegistry: ICharacterJoinerRegistry,
+    alpha: boolean,
+    rendererId: number,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'text', zIndex, alpha, colors, rendererId, bufferService, optionsService);
+    this._state = new GridCache<CharData>();
+    this._characterJoinerRegistry = characterJoinerRegistry;
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+
+    // Clear the character width cache if the font or width has changed
+    const terminalFont = this._getFont(false, false);
+    if (this._characterWidth !== dim.scaledCharWidth || this._characterFont !== terminalFont) {
+      this._characterWidth = dim.scaledCharWidth;
+      this._characterFont = terminalFont;
+      this._characterOverlapCache = {};
+    }
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._state.clear();
+    this._state.resize(this._bufferService.cols, this._bufferService.rows);
+  }
+
+  public reset(): void {
+    this._state.clear();
+    this._clearAll();
+  }
+
+  private _forEachCell(
+    firstRow: number,
+    lastRow: number,
+    joinerRegistry: ICharacterJoinerRegistry | null,
+    callback: (
+      cell: ICellData,
+      x: number,
+      y: number
+    ) => void
+  ): void {
+    for (let y = firstRow; y <= lastRow; y++) {
+      const row = y + this._bufferService.buffer.ydisp;
+      const line = this._bufferService.buffer.lines.get(row);
+      const joinedRanges = joinerRegistry ? joinerRegistry.getJoinedCharacters(row) : [];
+      for (let x = 0; x < this._bufferService.cols; x++) {
+        line!.loadCell(x, this._workCell);
+        let cell = this._workCell;
+
+        // If true, indicates that the current character(s) to draw were joined.
+        let isJoined = false;
+        let lastCharX = x;
+
+        // The character to the left is a wide character, drawing is owned by
+        // the char at x-1
+        if (cell.getWidth() === 0) {
+          continue;
+        }
+
+        // Process any joined character ranges as needed. Because of how the
+        // ranges are produced, we know that they are valid for the characters
+        // and attributes of our input.
+        if (joinedRanges.length > 0 && x === joinedRanges[0][0]) {
+          isJoined = true;
+          const range = joinedRanges.shift()!;
+
+          // We already know the exact start and end column of the joined range,
+          // so we get the string and width representing it directly
+
+          cell = new JoinedCellData(
+            this._workCell,
+            line!.translateToString(true, range[0], range[1]),
+            range[1] - range[0]
+          );
+
+          // Skip over the cells occupied by this range in the loop
+          lastCharX = range[1] - 1;
+        }
+
+        // If the character is an overlapping char and the character to the
+        // right is a space, take ownership of the cell to the right. We skip
+        // this check for joined characters because their rendering likely won't
+        // yield the same result as rendering the last character individually.
+        if (!isJoined && this._isOverlapping(cell)) {
+          // If the character is overlapping, we want to force a re-render on every
+          // frame. This is specifically to work around the case where two
+          // overlaping chars `a` and `b` are adjacent, the cursor is moved to b and a
+          // space is added. Without this, the first half of `b` would never
+          // get removed, and `a` would not re-render because it thinks it's
+          // already in the correct state.
+          // this._state.cache[x][y] = OVERLAP_OWNED_CHAR_DATA;
+          if (lastCharX < line!.length - 1 && line!.getCodePoint(lastCharX + 1) === NULL_CELL_CODE) {
+            // patch width to 2
+            cell.content &= ~Content.WIDTH_MASK;
+            cell.content |= 2 << Content.WIDTH_SHIFT;
+            // this._clearChar(x + 1, y);
+            // The overlapping char's char data will force a clear and render when the
+            // overlapping char is no longer to the left of the character and also when
+            // the space changes to another character.
+            // this._state.cache[x + 1][y] = OVERLAP_OWNED_CHAR_DATA;
+          }
+        }
+
+        callback(
+          cell,
+          x,
+          y
+        );
+
+        x = lastCharX;
+      }
+    }
+  }
+
+  /**
+   * Draws the background for a specified range of columns. Tries to batch adjacent cells of the
+   * same color together to reduce draw calls.
+   */
+  private _drawBackground(firstRow: number, lastRow: number): void {
+    const ctx = this._ctx;
+    const cols = this._bufferService.cols;
+    let startX: number = 0;
+    let startY: number = 0;
+    let prevFillStyle: string | null = null;
+
+    ctx.save();
+
+    this._forEachCell(firstRow, lastRow, null, (cell, x, y) => {
+      // libvte and xterm both draw the background (but not foreground) of invisible characters,
+      // so we should too.
+      let nextFillStyle = null; // null represents default background color
+
+      if (cell.isInverse()) {
+        if (cell.isFgDefault()) {
+          nextFillStyle = this._colors.foreground.css;
+        } else if (cell.isFgRGB()) {
+          nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;
+        } else {
+          nextFillStyle = this._colors.ansi[cell.getFgColor()].css;
+        }
+      } else if (cell.isBgRGB()) {
+        nextFillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;
+      } else if (cell.isBgPalette()) {
+        nextFillStyle = this._colors.ansi[cell.getBgColor()].css;
+      }
+
+      if (prevFillStyle === null) {
+        // This is either the first iteration, or the default background was set. Either way, we
+        // don't need to draw anything.
+        startX = x;
+        startY = y;
+      }
+
+      if (y !== startY) {
+        // our row changed, draw the previous row
+        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';
+        this._fillCells(startX, startY, cols - startX, 1);
+        startX = x;
+        startY = y;
+      } else if (prevFillStyle !== nextFillStyle) {
+        // our color changed, draw the previous characters in this row
+        ctx.fillStyle = prevFillStyle ? prevFillStyle : '';
+        this._fillCells(startX, startY, x - startX, 1);
+        startX = x;
+        startY = y;
+      }
+
+      prevFillStyle = nextFillStyle;
+    });
+
+    // flush the last color we encountered
+    if (prevFillStyle !== null) {
+      ctx.fillStyle = prevFillStyle;
+      this._fillCells(startX, startY, cols - startX, 1);
+    }
+
+    ctx.restore();
+  }
+
+  private _drawForeground(firstRow: number, lastRow: number): void {
+    this._forEachCell(firstRow, lastRow, this._characterJoinerRegistry, (cell, x, y) => {
+      if (cell.isInvisible()) {
+        return;
+      }
+      this._drawChars(cell, x, y);
+      if (cell.isUnderline()) {
+        this._ctx.save();
+
+        if (cell.isInverse()) {
+          if (cell.isBgDefault()) {
+            this._ctx.fillStyle = this._colors.background.css;
+          } else if (cell.isBgRGB()) {
+            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getBgColor()).join(',')})`;
+          } else {
+            this._ctx.fillStyle = this._colors.ansi[cell.getBgColor()].css;
+          }
+        } else {
+          if (cell.isFgDefault()) {
+            this._ctx.fillStyle = this._colors.foreground.css;
+          } else if (cell.isFgRGB()) {
+            this._ctx.fillStyle = `rgb(${AttributeData.toColorRGB(cell.getFgColor()).join(',')})`;
+          } else {
+            let fg = cell.getFgColor();
+            if (this._optionsService.options.drawBoldTextInBrightColors && cell.isBold() && fg < 8) {
+              fg += 8;
+            }
+            this._ctx.fillStyle = this._colors.ansi[fg].css;
+          }
+        }
+
+        this._fillBottomLineAtCells(x, y, cell.getWidth());
+        this._ctx.restore();
+      }
+    });
+  }
+
+  public onGridChanged(firstRow: number, lastRow: number): void {
+    // Resize has not been called yet
+    if (this._state.cache.length === 0) {
+      return;
+    }
+
+    if (this._charAtlas) {
+      this._charAtlas.beginFrame();
+    }
+
+    this._clearCells(0, firstRow, this._bufferService.cols, lastRow - firstRow + 1);
+    this._drawBackground(firstRow, lastRow);
+    this._drawForeground(firstRow, lastRow);
+  }
+
+  public onOptionsChanged(): void {
+    this._setTransparency(this._optionsService.options.allowTransparency);
+  }
+
+  /**
+   * Whether a character is overlapping to the next cell.
+   */
+  private _isOverlapping(cell: ICellData): boolean {
+    // Only single cell characters can be overlapping, rendering issues can
+    // occur without this check
+    if (cell.getWidth() !== 1) {
+      return false;
+    }
+
+    // We assume that any ascii character will not overlap
+    if (cell.getCode() < 256) {
+      return false;
+    }
+
+    const chars = cell.getChars();
+
+    // Deliver from cache if available
+    if (this._characterOverlapCache.hasOwnProperty(chars)) {
+      return this._characterOverlapCache[chars];
+    }
+
+    // Setup the font
+    this._ctx.save();
+    this._ctx.font = this._characterFont;
+
+    // Measure the width of the character, but Math.floor it
+    // because that is what the renderer does when it calculates
+    // the character dimensions we are comparing against
+    const overlaps = Math.floor(this._ctx.measureText(chars).width) > this._characterWidth;
+
+    // Restore the original context
+    this._ctx.restore();
+
+    // Cache and return
+    this._characterOverlapCache[chars] = overlaps;
+    return overlaps;
+  }
+
+  /**
+   * Clear the charcater at the cell specified.
+   * @param x The column of the char.
+   * @param y The row of the char.
+   */
+  // private _clearChar(x: number, y: number): void {
+  //   let colsToClear = 1;
+  //   // Clear the adjacent character if it was wide
+  //   const state = this._state.cache[x][y];
+  //   if (state && state[CHAR_DATA_WIDTH_INDEX] === 2) {
+  //     colsToClear = 2;
+  //   }
+  //   this.clearCells(x, y, colsToClear, 1);
+  // }
+}
diff --git a/node_modules/xterm/src/browser/renderer/Types.d.ts b/node_modules/xterm/src/browser/renderer/Types.d.ts
new file mode 100644 (file)
index 0000000..7f84dfd
--- /dev/null
@@ -0,0 +1,116 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+import { IColorSet } from 'browser/Types';
+
+export type CharacterJoinerHandler = (text: string) => [number, number][];
+
+export interface IRenderDimensions {
+  scaledCharWidth: number;
+  scaledCharHeight: number;
+  scaledCellWidth: number;
+  scaledCellHeight: number;
+  scaledCharLeft: number;
+  scaledCharTop: number;
+  scaledCanvasWidth: number;
+  scaledCanvasHeight: number;
+  canvasWidth: number;
+  canvasHeight: number;
+  actualCellWidth: number;
+  actualCellHeight: number;
+}
+
+/**
+ * Note that IRenderer implementations should emit the refresh event after
+ * rendering rows to the screen.
+ */
+export interface IRenderer extends IDisposable {
+  readonly dimensions: IRenderDimensions;
+
+  dispose(): void;
+  setColors(colors: IColorSet): void;
+  onDevicePixelRatioChange(): void;
+  onResize(cols: number, rows: number): void;
+  onCharSizeChanged(): void;
+  onBlur(): void;
+  onFocus(): void;
+  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;
+  onCursorMove(): void;
+  onOptionsChanged(): void;
+  clear(): void;
+  renderRows(start: number, end: number): void;
+  registerCharacterJoiner(handler: CharacterJoinerHandler): number;
+  deregisterCharacterJoiner(joinerId: number): boolean;
+}
+
+export interface ICharacterJoiner {
+  id: number;
+  handler: CharacterJoinerHandler;
+}
+
+export interface ICharacterJoinerRegistry {
+  registerCharacterJoiner(handler: (text: string) => [number, number][]): number;
+  deregisterCharacterJoiner(joinerId: number): boolean;
+  getJoinedCharacters(row: number): [number, number][];
+}
+
+export interface IRenderLayer extends IDisposable {
+  /**
+   * Called when the terminal loses focus.
+   */
+  onBlur(): void;
+
+  /**
+   * * Called when the terminal gets focus.
+   */
+  onFocus(): void;
+
+  /**
+   * Called when the cursor is moved.
+   */
+  onCursorMove(): void;
+
+  /**
+   * Called when options change.
+   */
+  onOptionsChanged(): void;
+
+  /**
+   * Called when the theme changes.
+   */
+  setColors(colorSet: IColorSet): void;
+
+  /**
+   * Called when the data in the grid has changed (or needs to be rendered
+   * again).
+   */
+  onGridChanged(startRow: number, endRow: number): void;
+
+  /**
+   * Calls when the selection changes.
+   */
+  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;
+
+  /**
+   * Registers a handler to join characters to render as a group
+   */
+  registerCharacterJoiner?(joiner: ICharacterJoiner): void;
+
+  /**
+   * Deregisters the specified character joiner handler
+   */
+  deregisterCharacterJoiner?(joinerId: number): void;
+
+  /**
+   * Resize the render layer.
+   */
+  resize(dim: IRenderDimensions): void;
+
+  /**
+   * Clear the state of the render layer.
+   */
+  reset(): void;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts b/node_modules/xterm/src/browser/renderer/atlas/BaseCharAtlas.ts
new file mode 100644 (file)
index 0000000..dc11460
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IGlyphIdentifier } from 'browser/renderer/atlas/Types';
+import { IDisposable } from 'common/Types';
+
+export abstract class BaseCharAtlas implements IDisposable {
+  private _didWarmUp: boolean = false;
+
+  public dispose(): void { }
+
+  /**
+   * Perform any work needed to warm the cache before it can be used. May be called multiple times.
+   * Implement _doWarmUp instead if you only want to get called once.
+   */
+  public warmUp(): void {
+    if (!this._didWarmUp) {
+      this._doWarmUp();
+      this._didWarmUp = true;
+    }
+  }
+
+  /**
+   * Perform any work needed to warm the cache before it can be used. Used by the default
+   * implementation of warmUp(), and will only be called once.
+   */
+  protected _doWarmUp(): void { }
+
+  /**
+   * Called when we start drawing a new frame.
+   *
+   * TODO: We rely on this getting called by TextRenderLayer. This should really be called by
+   * Renderer instead, but we need to make Renderer the source-of-truth for the char atlas, instead
+   * of BaseRenderLayer.
+   */
+  public beginFrame(): void { }
+
+  /**
+   * May be called before warmUp finishes, however it is okay for the implementation to
+   * do nothing and return false in that case.
+   *
+   * @param ctx Where to draw the character onto.
+   * @param glyph Information about what to draw
+   * @param x The position on the context to start drawing at
+   * @param y The position on the context to start drawing at
+   * @returns The success state. True if we drew the character.
+   */
+  public abstract draw(
+    ctx: CanvasRenderingContext2D,
+    glyph: IGlyphIdentifier,
+    x: number,
+    y: number
+  ): boolean;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts b/node_modules/xterm/src/browser/renderer/atlas/CharAtlasCache.ts
new file mode 100644 (file)
index 0000000..257835b
--- /dev/null
@@ -0,0 +1,95 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { generateConfig, configEquals } from 'browser/renderer/atlas/CharAtlasUtils';
+import { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';
+import { DynamicCharAtlas } from 'browser/renderer/atlas/DynamicCharAtlas';
+import { ICharAtlasConfig } from 'browser/renderer/atlas/Types';
+import { IColorSet } from 'browser/Types';
+import { ITerminalOptions } from 'common/services/Services';
+
+interface ICharAtlasCacheEntry {
+  atlas: BaseCharAtlas;
+  config: ICharAtlasConfig;
+  // N.B. This implementation potentially holds onto copies of the terminal forever, so
+  // this may cause memory leaks.
+  ownedBy: number[];
+}
+
+const charAtlasCache: ICharAtlasCacheEntry[] = [];
+
+/**
+ * Acquires a char atlas, either generating a new one or returning an existing
+ * one that is in use by another terminal.
+ */
+export function acquireCharAtlas(
+  options: ITerminalOptions,
+  rendererId: number,
+  colors: IColorSet,
+  scaledCharWidth: number,
+  scaledCharHeight: number
+): BaseCharAtlas {
+  const newConfig = generateConfig(scaledCharWidth, scaledCharHeight, options, colors);
+
+  // Check to see if the renderer already owns this config
+  for (let i = 0; i < charAtlasCache.length; i++) {
+    const entry = charAtlasCache[i];
+    const ownedByIndex = entry.ownedBy.indexOf(rendererId);
+    if (ownedByIndex >= 0) {
+      if (configEquals(entry.config, newConfig)) {
+        return entry.atlas;
+      }
+      // The configs differ, release the renderer from the entry
+      if (entry.ownedBy.length === 1) {
+        entry.atlas.dispose();
+        charAtlasCache.splice(i, 1);
+      } else {
+        entry.ownedBy.splice(ownedByIndex, 1);
+      }
+      break;
+    }
+  }
+
+  // Try match a char atlas from the cache
+  for (let i = 0; i < charAtlasCache.length; i++) {
+    const entry = charAtlasCache[i];
+    if (configEquals(entry.config, newConfig)) {
+      // Add the renderer to the cache entry and return
+      entry.ownedBy.push(rendererId);
+      return entry.atlas;
+    }
+  }
+
+  const newEntry: ICharAtlasCacheEntry = {
+    atlas: new DynamicCharAtlas(
+      document,
+      newConfig
+    ),
+    config: newConfig,
+    ownedBy: [rendererId]
+  };
+  charAtlasCache.push(newEntry);
+  return newEntry.atlas;
+}
+
+/**
+ * Removes a terminal reference from the cache, allowing its memory to be freed.
+ */
+export function removeTerminalFromCache(rendererId: number): void {
+  for (let i = 0; i < charAtlasCache.length; i++) {
+    const index = charAtlasCache[i].ownedBy.indexOf(rendererId);
+    if (index !== -1) {
+      if (charAtlasCache[i].ownedBy.length === 1) {
+        // Remove the cache entry if it's the only renderer
+        charAtlasCache[i].atlas.dispose();
+        charAtlasCache.splice(i, 1);
+      } else {
+        // Remove the reference from the cache entry
+        charAtlasCache[i].ownedBy.splice(index, 1);
+      }
+      break;
+    }
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts b/node_modules/xterm/src/browser/renderer/atlas/CharAtlasUtils.ts
new file mode 100644 (file)
index 0000000..346b35f
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharAtlasConfig } from 'browser/renderer/atlas/Types';
+import { DEFAULT_COLOR } from 'common/buffer/Constants';
+import { IColorSet, IPartialColorSet } from 'browser/Types';
+import { ITerminalOptions } from 'common/services/Services';
+
+export function generateConfig(scaledCharWidth: number, scaledCharHeight: number, options: ITerminalOptions, colors: IColorSet): ICharAtlasConfig {
+  // null out some fields that don't matter
+  const clonedColors = <IPartialColorSet>{
+    foreground: colors.foreground,
+    background: colors.background,
+    cursor: undefined,
+    cursorAccent: undefined,
+    selection: undefined,
+    // For the static char atlas, we only use the first 16 colors, but we need all 256 for the
+    // dynamic character atlas.
+    ansi: colors.ansi.slice(0, 16)
+  };
+  return {
+    devicePixelRatio: window.devicePixelRatio,
+    scaledCharWidth,
+    scaledCharHeight,
+    fontFamily: options.fontFamily,
+    fontSize: options.fontSize,
+    fontWeight: options.fontWeight,
+    fontWeightBold: options.fontWeightBold,
+    allowTransparency: options.allowTransparency,
+    colors: clonedColors
+  };
+}
+
+export function configEquals(a: ICharAtlasConfig, b: ICharAtlasConfig): boolean {
+  for (let i = 0; i < a.colors.ansi.length; i++) {
+    if (a.colors.ansi[i].rgba !== b.colors.ansi[i].rgba) {
+      return false;
+    }
+  }
+  return a.devicePixelRatio === b.devicePixelRatio &&
+      a.fontFamily === b.fontFamily &&
+      a.fontSize === b.fontSize &&
+      a.fontWeight === b.fontWeight &&
+      a.fontWeightBold === b.fontWeightBold &&
+      a.allowTransparency === b.allowTransparency &&
+      a.scaledCharWidth === b.scaledCharWidth &&
+      a.scaledCharHeight === b.scaledCharHeight &&
+      a.colors.foreground === b.colors.foreground &&
+      a.colors.background === b.colors.background;
+}
+
+export function is256Color(colorCode: number): boolean {
+  return colorCode < DEFAULT_COLOR;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/Constants.ts b/node_modules/xterm/src/browser/renderer/atlas/Constants.ts
new file mode 100644 (file)
index 0000000..150aad8
--- /dev/null
@@ -0,0 +1,9 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export const INVERTED_DEFAULT_COLOR = 257;
+export const DIM_OPACITY = 0.5;
+
+export const CHAR_ATLAS_CELL_SPACING = 1;
diff --git a/node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts b/node_modules/xterm/src/browser/renderer/atlas/DynamicCharAtlas.ts
new file mode 100644 (file)
index 0000000..40103bc
--- /dev/null
@@ -0,0 +1,369 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { DIM_OPACITY, INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { IGlyphIdentifier, ICharAtlasConfig } from 'browser/renderer/atlas/Types';
+import { BaseCharAtlas } from 'browser/renderer/atlas/BaseCharAtlas';
+import { DEFAULT_ANSI_COLORS } from 'browser/ColorManager';
+import { LRUMap } from 'browser/renderer/atlas/LRUMap';
+import { isFirefox, isSafari } from 'common/Platform';
+import { IColor } from 'browser/Types';
+import { throwIfFalsy } from 'browser/renderer/RendererUtils';
+
+// In practice we're probably never going to exhaust a texture this large. For debugging purposes,
+// however, it can be useful to set this to a really tiny value, to verify that LRU eviction works.
+const TEXTURE_WIDTH = 1024;
+const TEXTURE_HEIGHT = 1024;
+
+const TRANSPARENT_COLOR = {
+  css: 'rgba(0, 0, 0, 0)',
+  rgba: 0
+};
+
+// Drawing to the cache is expensive: If we have to draw more than this number of glyphs to the
+// cache in a single frame, give up on trying to cache anything else, and try to finish the current
+// frame ASAP.
+//
+// This helps to limit the amount of damage a program can do when it would otherwise thrash the
+// cache.
+const FRAME_CACHE_DRAW_LIMIT = 100;
+
+/**
+ * The number of milliseconds to wait before generating the ImageBitmap, this is to debounce/batch
+ * the operation as window.createImageBitmap is asynchronous.
+ */
+const GLYPH_BITMAP_COMMIT_DELAY = 100;
+
+interface IGlyphCacheValue {
+  index: number;
+  isEmpty: boolean;
+  inBitmap: boolean;
+}
+
+export function getGlyphCacheKey(glyph: IGlyphIdentifier): number {
+  // Note that this only returns a valid key when code < 256
+  // Layout:
+  // 0b00000000000000000000000000000001: italic (1)
+  // 0b00000000000000000000000000000010: dim (1)
+  // 0b00000000000000000000000000000100: bold (1)
+  // 0b00000000000000000000111111111000: fg (9)
+  // 0b00000000000111111111000000000000: bg (9)
+  // 0b00011111111000000000000000000000: code (8)
+  // 0b11100000000000000000000000000000: unused (3)
+  return glyph.code << 21 | glyph.bg << 12 | glyph.fg << 3 | (glyph.bold ? 0 : 4) + (glyph.dim ? 0 : 2) + (glyph.italic ? 0 : 1);
+}
+
+export class DynamicCharAtlas extends BaseCharAtlas {
+  // An ordered map that we're using to keep track of where each glyph is in the atlas texture.
+  // It's ordered so that we can determine when to remove the old entries.
+  private _cacheMap: LRUMap<IGlyphCacheValue>;
+
+  // The texture that the atlas is drawn to
+  private _cacheCanvas: HTMLCanvasElement;
+  private _cacheCtx: CanvasRenderingContext2D;
+
+  // A temporary context that glyphs are drawn to before being transfered to the atlas.
+  private _tmpCtx: CanvasRenderingContext2D;
+
+  // The number of characters stored in the atlas by width/height
+  private _width: number;
+  private _height: number;
+
+  private _drawToCacheCount: number = 0;
+
+  // An array of glyph keys that are waiting on the bitmap to be generated.
+  private _glyphsWaitingOnBitmap: IGlyphCacheValue[] = [];
+
+  // The timeout that is used to batch bitmap generation so it's not requested for every new glyph.
+  private _bitmapCommitTimeout: number | null = null;
+
+  // The bitmap to draw from, this is much faster on other browsers than others.
+  private _bitmap: ImageBitmap | null = null;
+
+  constructor(document: Document, private _config: ICharAtlasConfig) {
+    super();
+    this._cacheCanvas = document.createElement('canvas');
+    this._cacheCanvas.width = TEXTURE_WIDTH;
+    this._cacheCanvas.height = TEXTURE_HEIGHT;
+    // The canvas needs alpha because we use clearColor to convert the background color to alpha.
+    // It might also contain some characters with transparent backgrounds if allowTransparency is
+    // set.
+    this._cacheCtx = throwIfFalsy(this._cacheCanvas.getContext('2d', {alpha: true}));
+
+    const tmpCanvas = document.createElement('canvas');
+    tmpCanvas.width = this._config.scaledCharWidth;
+    tmpCanvas.height = this._config.scaledCharHeight;
+    this._tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d', {alpha: this._config.allowTransparency}));
+
+    this._width = Math.floor(TEXTURE_WIDTH / this._config.scaledCharWidth);
+    this._height = Math.floor(TEXTURE_HEIGHT / this._config.scaledCharHeight);
+    const capacity = this._width * this._height;
+    this._cacheMap = new LRUMap(capacity);
+    this._cacheMap.prealloc(capacity);
+
+    // This is useful for debugging
+    // document.body.appendChild(this._cacheCanvas);
+  }
+
+  public dispose(): void {
+    if (this._bitmapCommitTimeout !== null) {
+      window.clearTimeout(this._bitmapCommitTimeout);
+      this._bitmapCommitTimeout = null;
+    }
+  }
+
+  public beginFrame(): void {
+    this._drawToCacheCount = 0;
+  }
+
+  public draw(
+    ctx: CanvasRenderingContext2D,
+    glyph: IGlyphIdentifier,
+    x: number,
+    y: number
+  ): boolean {
+    // Space is always an empty cell, special case this as it's so common
+    if (glyph.code === 32) {
+      return true;
+    }
+
+    // Exit early for uncachable glyphs
+    if (!this._canCache(glyph)) {
+      return false;
+    }
+
+    const glyphKey = getGlyphCacheKey(glyph);
+    const cacheValue = this._cacheMap.get(glyphKey);
+    if (cacheValue !== null && cacheValue !== undefined) {
+      this._drawFromCache(ctx, cacheValue, x, y);
+      return true;
+    } else if (this._drawToCacheCount < FRAME_CACHE_DRAW_LIMIT) {
+      let index;
+      if (this._cacheMap.size < this._cacheMap.capacity) {
+        index = this._cacheMap.size;
+      } else {
+        // we're out of space, so our call to set will delete this item
+        index = this._cacheMap.peek()!.index;
+      }
+      const cacheValue = this._drawToCache(glyph, index);
+      this._cacheMap.set(glyphKey, cacheValue);
+      this._drawFromCache(ctx, cacheValue, x, y);
+      return true;
+    }
+    return false;
+  }
+
+  private _canCache(glyph: IGlyphIdentifier): boolean {
+    // Only cache ascii and extended characters for now, to be safe. In the future, we could do
+    // something more complicated to determine the expected width of a character.
+    //
+    // If we switch the renderer over to webgl at some point, we may be able to use blending modes
+    // to draw overlapping glyphs from the atlas:
+    // https://github.com/servo/webrender/issues/464#issuecomment-255632875
+    // https://webglfundamentals.org/webgl/lessons/webgl-text-texture.html
+    return glyph.code < 256;
+  }
+
+  private _toCoordinateX(index: number): number {
+    return (index % this._width) * this._config.scaledCharWidth;
+  }
+
+  private _toCoordinateY(index: number): number {
+    return Math.floor(index / this._width) * this._config.scaledCharHeight;
+  }
+
+  private _drawFromCache(
+    ctx: CanvasRenderingContext2D,
+    cacheValue: IGlyphCacheValue,
+    x: number,
+    y: number
+  ): void {
+    // We don't actually need to do anything if this is whitespace.
+    if (cacheValue.isEmpty) {
+      return;
+    }
+    const cacheX = this._toCoordinateX(cacheValue.index);
+    const cacheY = this._toCoordinateY(cacheValue.index);
+    ctx.drawImage(
+      cacheValue.inBitmap ? this._bitmap! : this._cacheCanvas,
+      cacheX,
+      cacheY,
+      this._config.scaledCharWidth,
+      this._config.scaledCharHeight,
+      x,
+      y,
+      this._config.scaledCharWidth,
+      this._config.scaledCharHeight
+    );
+  }
+
+  private _getColorFromAnsiIndex(idx: number): IColor {
+    if (idx < this._config.colors.ansi.length) {
+      return this._config.colors.ansi[idx];
+    }
+    return DEFAULT_ANSI_COLORS[idx];
+  }
+
+  private _getBackgroundColor(glyph: IGlyphIdentifier): IColor {
+    if (this._config.allowTransparency) {
+      // The background color might have some transparency, so we need to render it as fully
+      // transparent in the atlas. Otherwise we'd end up drawing the transparent background twice
+      // around the anti-aliased edges of the glyph, and it would look too dark.
+      return TRANSPARENT_COLOR;
+    } else if (glyph.bg === INVERTED_DEFAULT_COLOR) {
+      return this._config.colors.foreground;
+    } else if (glyph.bg < 256) {
+      return this._getColorFromAnsiIndex(glyph.bg);
+    }
+    return this._config.colors.background;
+  }
+
+  private _getForegroundColor(glyph: IGlyphIdentifier): IColor {
+    if (glyph.fg === INVERTED_DEFAULT_COLOR) {
+      return this._config.colors.background;
+    } else if (glyph.fg < 256) {
+      // 256 color support
+      return this._getColorFromAnsiIndex(glyph.fg);
+    }
+    return this._config.colors.foreground;
+  }
+
+  // TODO: We do this (or something similar) in multiple places. We should split this off
+  // into a shared function.
+  private _drawToCache(glyph: IGlyphIdentifier, index: number): IGlyphCacheValue {
+    this._drawToCacheCount++;
+
+    this._tmpCtx.save();
+
+    // draw the background
+    const backgroundColor = this._getBackgroundColor(glyph);
+    // Use a 'copy' composite operation to clear any existing glyph out of _tmpCtxWithAlpha, regardless of
+    // transparency in backgroundColor
+    this._tmpCtx.globalCompositeOperation = 'copy';
+    this._tmpCtx.fillStyle = backgroundColor.css;
+    this._tmpCtx.fillRect(0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight);
+    this._tmpCtx.globalCompositeOperation = 'source-over';
+
+    // draw the foreground/glyph
+    const fontWeight = glyph.bold ? this._config.fontWeightBold : this._config.fontWeight;
+    const fontStyle = glyph.italic ? 'italic' : '';
+    this._tmpCtx.font =
+      `${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`;
+    this._tmpCtx.textBaseline = 'middle';
+
+    this._tmpCtx.fillStyle = this._getForegroundColor(glyph).css;
+
+    // Apply alpha to dim the character
+    if (glyph.dim) {
+      this._tmpCtx.globalAlpha = DIM_OPACITY;
+    }
+    // Draw the character
+    this._tmpCtx.fillText(glyph.chars, 0, this._config.scaledCharHeight / 2);
+    this._tmpCtx.restore();
+
+    // clear the background from the character to avoid issues with drawing over the previous
+    // character if it extends past it's bounds
+    const imageData = this._tmpCtx.getImageData(
+      0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight
+    );
+    let isEmpty = false;
+    if (!this._config.allowTransparency) {
+      isEmpty = clearColor(imageData, backgroundColor);
+    }
+
+    // copy the data from imageData to _cacheCanvas
+    const x = this._toCoordinateX(index);
+    const y = this._toCoordinateY(index);
+    // putImageData doesn't do any blending, so it will overwrite any existing cache entry for us
+    this._cacheCtx.putImageData(imageData, x, y);
+
+    // Add the glyph and queue it to the bitmap (if the browser supports it)
+    const cacheValue = {
+      index,
+      isEmpty,
+      inBitmap: false
+    };
+    this._addGlyphToBitmap(cacheValue);
+
+    return cacheValue;
+  }
+
+  private _addGlyphToBitmap(cacheValue: IGlyphCacheValue): void {
+    // Support is patchy for createImageBitmap at the moment, pass a canvas back
+    // if support is lacking as drawImage works there too. Firefox is also
+    // included here as ImageBitmap appears both buggy and has horrible
+    // performance (tested on v55).
+    if (!('createImageBitmap' in window) || isFirefox || isSafari) {
+      return;
+    }
+
+    // Add the glyph to the queue
+    this._glyphsWaitingOnBitmap.push(cacheValue);
+
+    // Check if bitmap generation timeout already exists
+    if (this._bitmapCommitTimeout !== null) {
+      return;
+    }
+
+    this._bitmapCommitTimeout = window.setTimeout(() => this._generateBitmap(), GLYPH_BITMAP_COMMIT_DELAY);
+  }
+
+  private _generateBitmap(): void {
+    const glyphsMovingToBitmap = this._glyphsWaitingOnBitmap;
+    this._glyphsWaitingOnBitmap = [];
+    window.createImageBitmap(this._cacheCanvas).then(bitmap => {
+      // Set bitmap
+      this._bitmap = bitmap;
+
+      // Mark all new glyphs as in bitmap, excluding glyphs that came in after
+      // the bitmap was requested
+      for (let i = 0; i < glyphsMovingToBitmap.length; i++) {
+        const value = glyphsMovingToBitmap[i];
+        // It doesn't matter if the value was already evicted, it will be
+        // released from memory after this block if so.
+        value.inBitmap = true;
+      }
+    });
+    this._bitmapCommitTimeout = null;
+  }
+}
+
+// This is used for debugging the renderer, just swap out `new DynamicCharAtlas` with
+// `new NoneCharAtlas`.
+export class NoneCharAtlas extends BaseCharAtlas {
+  constructor(document: Document, config: ICharAtlasConfig) {
+    super();
+  }
+
+  public draw(
+    ctx: CanvasRenderingContext2D,
+    glyph: IGlyphIdentifier,
+    x: number,
+    y: number
+  ): boolean {
+    return false;
+  }
+}
+
+/**
+ * Makes a partiicular rgb color in an ImageData completely transparent.
+ * @returns True if the result is "empty", meaning all pixels are fully transparent.
+ */
+function clearColor(imageData: ImageData, color: IColor): boolean {
+  let isEmpty = true;
+  const r = color.rgba >>> 24;
+  const g = color.rgba >>> 16 & 0xFF;
+  const b = color.rgba >>> 8 & 0xFF;
+  for (let offset = 0; offset < imageData.data.length; offset += 4) {
+    if (imageData.data[offset] === r &&
+        imageData.data[offset + 1] === g &&
+        imageData.data[offset + 2] === b) {
+      imageData.data[offset + 3] = 0;
+    } else {
+      isEmpty = false;
+    }
+  }
+  return isEmpty;
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts b/node_modules/xterm/src/browser/renderer/atlas/LRUMap.ts
new file mode 100644 (file)
index 0000000..f70962f
--- /dev/null
@@ -0,0 +1,136 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+interface ILinkedListNode<T> {
+  prev: ILinkedListNode<T> | null;
+  next: ILinkedListNode<T> | null;
+  key: number | null;
+  value: T | null;
+}
+
+export class LRUMap<T> {
+  private _map: { [key: number]: ILinkedListNode<T> } = {};
+  private _head: ILinkedListNode<T> | null = null;
+  private _tail: ILinkedListNode<T> | null = null;
+  private _nodePool: ILinkedListNode<T>[] = [];
+  public size: number = 0;
+
+  constructor(public capacity: number) { }
+
+  private _unlinkNode(node: ILinkedListNode<T>): void {
+    const prev = node.prev;
+    const next = node.next;
+    if (node === this._head) {
+      this._head = next;
+    }
+    if (node === this._tail) {
+      this._tail = prev;
+    }
+    if (prev !== null) {
+      prev.next = next;
+    }
+    if (next !== null) {
+      next.prev = prev;
+    }
+  }
+
+  private _appendNode(node: ILinkedListNode<T>): void {
+    const tail = this._tail;
+    if (tail !== null) {
+      tail.next = node;
+    }
+    node.prev = tail;
+    node.next = null;
+    this._tail = node;
+    if (this._head === null) {
+      this._head = node;
+    }
+  }
+
+  /**
+   * Preallocate a bunch of linked-list nodes. Allocating these nodes ahead of time means that
+   * they're more likely to live next to each other in memory, which seems to improve performance.
+   *
+   * Each empty object only consumes about 60 bytes of memory, so this is pretty cheap, even for
+   * large maps.
+   */
+  public prealloc(count: number): void {
+    const nodePool = this._nodePool;
+    for (let i = 0; i < count; i++) {
+      nodePool.push({
+        prev: null,
+        next: null,
+        key: null,
+        value: null
+      });
+    }
+  }
+
+  public get(key: number): T | null {
+    // This is unsafe: We're assuming our keyspace doesn't overlap with Object.prototype. However,
+    // it's faster than calling hasOwnProperty, and in our case, it would never overlap.
+    const node = this._map[key];
+    if (node !== undefined) {
+      this._unlinkNode(node);
+      this._appendNode(node);
+      return node.value;
+    }
+    return null;
+  }
+
+  /**
+   * Gets a value from a key without marking it as the most recently used item.
+   */
+  public peekValue(key: number): T | null {
+    const node = this._map[key];
+    if (node !== undefined) {
+      return node.value;
+    }
+    return null;
+  }
+
+  public peek(): T | null {
+    const head = this._head;
+    return head === null ? null : head.value;
+  }
+
+  public set(key: number, value: T): void {
+    // This is unsafe: See note above.
+    let node = this._map[key];
+    if (node !== undefined) {
+      // already exists, we just need to mutate it and move it to the end of the list
+      node = this._map[key];
+      this._unlinkNode(node);
+      node.value = value;
+    } else if (this.size >= this.capacity) {
+      // we're out of space: recycle the head node, move it to the tail
+      node = this._head!;
+      this._unlinkNode(node);
+      delete this._map[node.key!];
+      node.key = key;
+      node.value = value;
+      this._map[key] = node;
+    } else {
+      // make a new element
+      const nodePool = this._nodePool;
+      if (nodePool.length > 0) {
+        // use a preallocated node if we can
+        node = nodePool.pop()!;
+        node.key = key;
+        node.value = value;
+      } else {
+        node = {
+          prev: null,
+          next: null,
+          key,
+          value
+        };
+      }
+      this._map[key] = node;
+      this.size++;
+    }
+    this._appendNode(node);
+  }
+}
diff --git a/node_modules/xterm/src/browser/renderer/atlas/Types.d.ts b/node_modules/xterm/src/browser/renderer/atlas/Types.d.ts
new file mode 100644 (file)
index 0000000..d8bc54c
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { FontWeight } from 'common/services/Services';
+import { IPartialColorSet } from 'browser/Types';
+
+export interface IGlyphIdentifier {
+  chars: string;
+  code: number;
+  bg: number;
+  fg: number;
+  bold: boolean;
+  dim: boolean;
+  italic: boolean;
+}
+
+export interface ICharAtlasConfig {
+  devicePixelRatio: number;
+  fontSize: number;
+  fontFamily: string;
+  fontWeight: FontWeight;
+  fontWeightBold: FontWeight;
+  scaledCharWidth: number;
+  scaledCharHeight: number;
+  allowTransparency: boolean;
+  colors: IPartialColorSet;
+}
diff --git a/node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts b/node_modules/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts
new file mode 100644 (file)
index 0000000..3e3b5df
--- /dev/null
@@ -0,0 +1,132 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferLine } from 'common/Types';
+import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { AttributeData } from 'common/buffer/AttributeData';
+import { NULL_CELL_CODE, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { IOptionsService } from 'common/services/Services';
+
+export const BOLD_CLASS = 'xterm-bold';
+export const DIM_CLASS = 'xterm-dim';
+export const ITALIC_CLASS = 'xterm-italic';
+export const UNDERLINE_CLASS = 'xterm-underline';
+export const CURSOR_CLASS = 'xterm-cursor';
+export const CURSOR_BLINK_CLASS = 'xterm-cursor-blink';
+export const CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block';
+export const CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar';
+export const CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline';
+
+export class DomRendererRowFactory {
+  private _workCell: CellData = new CellData();
+
+  constructor(
+    private _document: Document,
+    private _optionsService: IOptionsService
+  ) {
+  }
+
+  public createRow(lineData: IBufferLine, isCursorRow: boolean, cursorStyle: string | undefined, cursorX: number, cursorBlink: boolean, cellWidth: number, cols: number): DocumentFragment {
+    const fragment = this._document.createDocumentFragment();
+
+    // Find the line length first, this prevents the need to output a bunch of
+    // empty cells at the end. This cannot easily be integrated into the main
+    // loop below because of the colCount feature (which can be removed after we
+    // properly support reflow and disallow data to go beyond the right-side of
+    // the viewport).
+    let lineLength = 0;
+    for (let x = Math.min(lineData.length, cols) - 1; x >= 0; x--) {
+      if (lineData.loadCell(x, this._workCell).getCode() !== NULL_CELL_CODE || (isCursorRow && x === cursorX)) {
+        lineLength = x + 1;
+        break;
+      }
+    }
+
+    for (let x = 0; x < lineLength; x++) {
+      lineData.loadCell(x, this._workCell);
+      const width = this._workCell.getWidth();
+
+      // The character to the left is a wide character, drawing is owned by the char at x-1
+      if (width === 0) {
+        continue;
+      }
+
+      const charElement = this._document.createElement('span');
+      if (width > 1) {
+        charElement.style.width = `${cellWidth * width}px`;
+      }
+
+      if (isCursorRow && x === cursorX) {
+        charElement.classList.add(CURSOR_CLASS);
+
+        if (cursorBlink) {
+          charElement.classList.add(CURSOR_BLINK_CLASS);
+        }
+
+        switch (cursorStyle) {
+          case 'bar':
+            charElement.classList.add(CURSOR_STYLE_BAR_CLASS);
+            break;
+          case 'underline':
+            charElement.classList.add(CURSOR_STYLE_UNDERLINE_CLASS);
+            break;
+          default:
+            charElement.classList.add(CURSOR_STYLE_BLOCK_CLASS);
+            break;
+        }
+      }
+
+      if (this._workCell.isBold()) {
+        charElement.classList.add(BOLD_CLASS);
+      }
+
+      if (this._workCell.isItalic()) {
+        charElement.classList.add(ITALIC_CLASS);
+      }
+
+      if (this._workCell.isDim()) {
+        charElement.classList.add(DIM_CLASS);
+      }
+
+      if (this._workCell.isUnderline()) {
+        charElement.classList.add(UNDERLINE_CLASS);
+      }
+
+      charElement.textContent = this._workCell.getChars() || WHITESPACE_CELL_CHAR;
+
+      const swapColor = this._workCell.isInverse();
+
+      // fg
+      if (this._workCell.isFgRGB()) {
+        let style = charElement.getAttribute('style') || '';
+        style += `${swapColor ? 'background-' : ''}color:rgb(${(AttributeData.toColorRGB(this._workCell.getFgColor())).join(',')});`;
+        charElement.setAttribute('style', style);
+      } else if (this._workCell.isFgPalette()) {
+        let fg = this._workCell.getFgColor();
+        if (this._workCell.isBold() && fg < 8 && !swapColor && this._optionsService.options.drawBoldTextInBrightColors) {
+          fg += 8;
+        }
+        charElement.classList.add(`xterm-${swapColor ? 'b' : 'f'}g-${fg}`);
+      } else if (swapColor) {
+        charElement.classList.add(`xterm-bg-${INVERTED_DEFAULT_COLOR}`);
+      }
+
+      // bg
+      if (this._workCell.isBgRGB()) {
+        let style = charElement.getAttribute('style') || '';
+        style += `${swapColor ? '' : 'background-'}color:rgb(${(AttributeData.toColorRGB(this._workCell.getBgColor())).join(',')});`;
+        charElement.setAttribute('style', style);
+      } else if (this._workCell.isBgPalette()) {
+        charElement.classList.add(`xterm-${swapColor ? 'f' : 'b'}g-${this._workCell.getBgColor()}`);
+      } else if (swapColor) {
+        charElement.classList.add(`xterm-fg-${INVERTED_DEFAULT_COLOR}`);
+      }
+
+      fragment.appendChild(charElement);
+    }
+    return fragment;
+  }
+}
diff --git a/node_modules/xterm/src/browser/selection/SelectionModel.ts b/node_modules/xterm/src/browser/selection/SelectionModel.ts
new file mode 100644 (file)
index 0000000..1420444
--- /dev/null
@@ -0,0 +1,135 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferService } from 'common/services/Services';
+
+/**
+ * Represents a selection within the buffer. This model only cares about column
+ * and row coordinates, not wide characters.
+ */
+export class SelectionModel {
+  /**
+   * Whether select all is currently active.
+   */
+  public isSelectAllActive: boolean = false;
+
+  /**
+   * The minimal length of the selection from the start position. When double
+   * clicking on a word, the word will be selected which makes the selection
+   * start at the start of the word and makes this variable the length.
+   */
+  public selectionStartLength: number = 0;
+
+  /**
+   * The [x, y] position the selection starts at.
+   */
+  public selectionStart: [number, number] | undefined;
+
+  /**
+   * The [x, y] position the selection ends at.
+   */
+  public selectionEnd: [number, number] | undefined;
+
+  constructor(
+    private _bufferService: IBufferService
+  ) {
+  }
+
+  /**
+   * Clears the current selection.
+   */
+  public clearSelection(): void {
+    this.selectionStart = undefined;
+    this.selectionEnd = undefined;
+    this.isSelectAllActive = false;
+    this.selectionStartLength = 0;
+  }
+
+  /**
+   * The final selection start, taking into consideration select all.
+   */
+  public get finalSelectionStart(): [number, number] | undefined {
+    if (this.isSelectAllActive) {
+      return [0, 0];
+    }
+
+    if (!this.selectionEnd || !this.selectionStart) {
+      return this.selectionStart;
+    }
+
+    return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart;
+  }
+
+  /**
+   * The final selection end, taking into consideration select all, double click
+   * word selection and triple click line selection.
+   */
+  public get finalSelectionEnd(): [number, number] | undefined {
+    if (this.isSelectAllActive) {
+      return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1];
+    }
+
+    if (!this.selectionStart) {
+      return undefined;
+    }
+
+    // Use the selection start + length if the end doesn't exist or they're reversed
+    if (!this.selectionEnd || this.areSelectionValuesReversed()) {
+      const startPlusLength = this.selectionStart[0] + this.selectionStartLength;
+      if (startPlusLength > this._bufferService.cols) {
+        return [startPlusLength % this._bufferService.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._bufferService.cols)];
+      }
+      return [startPlusLength, this.selectionStart[1]];
+    }
+
+    // Ensure the the word/line is selected after a double/triple click
+    if (this.selectionStartLength) {
+      // Select the larger of the two when start and end are on the same line
+      if (this.selectionEnd[1] === this.selectionStart[1]) {
+        return [Math.max(this.selectionStart[0] + this.selectionStartLength, this.selectionEnd[0]), this.selectionEnd[1]];
+      }
+    }
+    return this.selectionEnd;
+  }
+
+  /**
+   * Returns whether the selection start and end are reversed.
+   */
+  public areSelectionValuesReversed(): boolean {
+    const start = this.selectionStart;
+    const end = this.selectionEnd;
+    if (!start || !end) {
+      return false;
+    }
+    return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]);
+  }
+
+  /**
+   * Handle the buffer being trimmed, adjust the selection position.
+   * @param amount The amount the buffer is being trimmed.
+   * @return Whether a refresh is necessary.
+   */
+  public onTrim(amount: number): boolean {
+    // Adjust the selection position based on the trimmed amount.
+    if (this.selectionStart) {
+      this.selectionStart[1] -= amount;
+    }
+    if (this.selectionEnd) {
+      this.selectionEnd[1] -= amount;
+    }
+
+    // The selection has moved off the buffer, clear it.
+    if (this.selectionEnd && this.selectionEnd[1] < 0) {
+      this.clearSelection();
+      return true;
+    }
+
+    // If the selection start is trimmed, ensure the start column is 0.
+    if (this.selectionStart && this.selectionStart[1] < 0) {
+      this.selectionStart[1] = 0;
+    }
+    return false;
+  }
+}
diff --git a/node_modules/xterm/src/browser/selection/Types.d.ts b/node_modules/xterm/src/browser/selection/Types.d.ts
new file mode 100644 (file)
index 0000000..d5a03ec
--- /dev/null
@@ -0,0 +1,10 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export interface ISelectionRedrawRequestEvent {
+  start: [number, number] | undefined;
+  end: [number, number] | undefined;
+  columnSelectMode: boolean;
+}
diff --git a/node_modules/xterm/src/browser/services/CharSizeService.ts b/node_modules/xterm/src/browser/services/CharSizeService.ts
new file mode 100644 (file)
index 0000000..0749a42
--- /dev/null
@@ -0,0 +1,87 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOptionsService } from 'common/services/Services';
+import { IEvent, EventEmitter } from 'common/EventEmitter';
+import { ICharSizeService } from 'browser/services/Services';
+
+export class CharSizeService implements ICharSizeService {
+  serviceBrand: any;
+
+  public width: number = 0;
+  public height: number = 0;
+  private _measureStrategy: IMeasureStrategy;
+
+  public get hasValidSize(): boolean { return this.width > 0 && this.height > 0; }
+
+  private _onCharSizeChange = new EventEmitter<void>();
+  public get onCharSizeChange(): IEvent<void> { return this._onCharSizeChange.event; }
+
+  constructor(
+    readonly document: Document,
+    readonly parentElement: HTMLElement,
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    this._measureStrategy = new DomMeasureStrategy(document, parentElement, this._optionsService);
+  }
+
+  public measure(): void {
+    const result = this._measureStrategy.measure();
+    if (result.width !== this.width || result.height !== this.height) {
+      this.width = result.width;
+      this.height = result.height;
+      this._onCharSizeChange.fire();
+    }
+  }
+}
+
+interface IMeasureStrategy {
+  measure(): IReadonlyMeasureResult;
+}
+
+interface IReadonlyMeasureResult {
+  readonly width: number;
+  readonly height: number;
+}
+
+interface IMeasureResult {
+  width: number;
+  height: number;
+}
+
+// TODO: For supporting browsers we should also provide a CanvasCharDimensionsProvider that uses ctx.measureText
+class DomMeasureStrategy implements IMeasureStrategy {
+  private _result: IMeasureResult = { width: 0, height: 0 };
+  private _measureElement: HTMLElement;
+
+  constructor(
+    private _document: Document,
+    private _parentElement: HTMLElement,
+    private _optionsService: IOptionsService
+  ) {
+    this._measureElement = this._document.createElement('span');
+    this._measureElement.classList.add('xterm-char-measure-element');
+    this._measureElement.textContent = 'W';
+    this._measureElement.setAttribute('aria-hidden', 'true');
+    this._parentElement.appendChild(this._measureElement);
+  }
+
+  public measure(): IReadonlyMeasureResult {
+    this._measureElement.style.fontFamily = this._optionsService.options.fontFamily;
+    this._measureElement.style.fontSize = `${this._optionsService.options.fontSize}px`;
+
+    // Note that this triggers a synchronous layout
+    const geometry = this._measureElement.getBoundingClientRect();
+
+    // If values are 0 then the element is likely currently display:none, in which case we should
+    // retain the previous value.
+    if (geometry.width !== 0 && geometry.height !== 0) {
+      this._result.width = geometry.width;
+      this._result.height = Math.ceil(geometry.height);
+    }
+
+    return this._result;
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/MouseService.ts b/node_modules/xterm/src/browser/services/MouseService.ts
new file mode 100644 (file)
index 0000000..b0f8c35
--- /dev/null
@@ -0,0 +1,35 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharSizeService, IRenderService, IMouseService } from './Services';
+import { getCoords, getRawByteCoords } from 'browser/input/Mouse';
+
+export class MouseService implements IMouseService {
+  serviceBrand: any;
+
+  constructor(
+    @IRenderService private readonly _renderService: IRenderService,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService
+  ) {
+  }
+
+  public getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined {
+    return getCoords(
+      event,
+      element,
+      colCount,
+      rowCount,
+      this._charSizeService.hasValidSize,
+      this._renderService.dimensions.actualCellWidth,
+      this._renderService.dimensions.actualCellHeight,
+      isSelection
+    );
+  }
+
+  public getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined {
+    const coords = this.getCoords(event, element, colCount, rowCount);
+    return getRawByteCoords(coords);
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/RenderService.ts b/node_modules/xterm/src/browser/services/RenderService.ts
new file mode 100644 (file)
index 0000000..63084f5
--- /dev/null
@@ -0,0 +1,172 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { RenderDebouncer } from 'browser/RenderDebouncer';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { Disposable } from 'common/Lifecycle';
+import { ScreenDprMonitor } from 'browser/ScreenDprMonitor';
+import { addDisposableDomListener } from 'browser/Lifecycle';
+import { IColorSet } from 'browser/Types';
+import { IOptionsService } from 'common/services/Services';
+import { ICharSizeService, IRenderService } from 'browser/services/Services';
+
+export class RenderService extends Disposable implements IRenderService {
+  serviceBrand: any;
+
+  private _renderDebouncer: RenderDebouncer;
+  private _screenDprMonitor: ScreenDprMonitor;
+
+  private _isPaused: boolean = false;
+  private _needsFullRefresh: boolean = false;
+  private _canvasWidth: number = 0;
+  private _canvasHeight: number = 0;
+
+  private _onDimensionsChange = new EventEmitter<IRenderDimensions>();
+  public get onDimensionsChange(): IEvent<IRenderDimensions> { return this._onDimensionsChange.event; }
+  private _onRender = new EventEmitter<{ start: number, end: number }>();
+  public get onRender(): IEvent<{ start: number, end: number }> { return this._onRender.event; }
+  private _onRefreshRequest = new EventEmitter<{ start: number, end: number }>();
+  public get onRefreshRequest(): IEvent<{ start: number, end: number }> { return this._onRefreshRequest.event; }
+
+  public get dimensions(): IRenderDimensions { return this._renderer.dimensions; }
+
+  constructor(
+    private _renderer: IRenderer,
+    private _rowCount: number,
+    readonly screenElement: HTMLElement,
+    @IOptionsService readonly optionsService: IOptionsService,
+    @ICharSizeService readonly charSizeService: ICharSizeService
+  ) {
+    super();
+    this._renderDebouncer = new RenderDebouncer((start, end) => this._renderRows(start, end));
+    this.register(this._renderDebouncer);
+
+    this._screenDprMonitor = new ScreenDprMonitor();
+    this._screenDprMonitor.setListener(() => this.onDevicePixelRatioChange());
+    this.register(this._screenDprMonitor);
+
+    this.register(optionsService.onOptionChange(() => this._renderer.onOptionsChanged()));
+    this.register(charSizeService.onCharSizeChange(() => this.onCharSizeChanged()));
+
+    // dprchange should handle this case, we need this as well for browsers that don't support the
+    // matchMedia query.
+    this.register(addDisposableDomListener(window, 'resize', () => this.onDevicePixelRatioChange()));
+
+    // Detect whether IntersectionObserver is detected and enable renderer pause
+    // and resume based on terminal visibility if so
+    if ('IntersectionObserver' in window) {
+      const observer = new IntersectionObserver(e => this._onIntersectionChange(e[e.length - 1]), { threshold: 0 });
+      observer.observe(screenElement);
+      this.register({ dispose: () => observer.disconnect() });
+    }
+  }
+
+  private _onIntersectionChange(entry: IntersectionObserverEntry): void {
+    this._isPaused = entry.intersectionRatio === 0;
+    if (!this._isPaused && this._needsFullRefresh) {
+      this.refreshRows(0, this._rowCount - 1);
+      this._needsFullRefresh = false;
+    }
+  }
+
+  public refreshRows(start: number, end: number): void {
+    if (this._isPaused) {
+      this._needsFullRefresh = true;
+      return;
+    }
+    this._renderDebouncer.refresh(start, end, this._rowCount);
+  }
+
+  private _renderRows(start: number, end: number): void {
+    this._renderer.renderRows(start, end);
+    this._onRender.fire({ start, end });
+  }
+
+  public resize(cols: number, rows: number): void {
+    this._rowCount = rows;
+    this._fireOnCanvasResize();
+  }
+
+  public changeOptions(): void {
+    this._renderer.onOptionsChanged();
+    this._fireOnCanvasResize();
+  }
+
+  private _fireOnCanvasResize(): void {
+    // Don't fire the event if the dimensions haven't changed
+    if (this._renderer.dimensions.canvasWidth === this._canvasWidth && this._renderer.dimensions.canvasHeight === this._canvasHeight) {
+      return;
+    }
+    this._onDimensionsChange.fire(this._renderer.dimensions);
+  }
+
+  public dispose(): void {
+    this._renderer.dispose();
+  }
+
+  public setRenderer(renderer: IRenderer): void {
+    // TODO: RenderService should be the only one to dispose the renderer
+    this._renderer.dispose();
+    this._renderer = renderer;
+    this.refreshRows(0, this._rowCount - 1);
+  }
+
+  private _fullRefresh(): void {
+    if (this._isPaused) {
+      this._needsFullRefresh = true;
+    } else {
+      this.refreshRows(0, this._rowCount - 1);
+    }
+  }
+
+  public setColors(colors: IColorSet): void {
+    this._renderer.setColors(colors);
+    this._fullRefresh();
+  }
+
+  public onDevicePixelRatioChange(): void {
+    this._renderer.onDevicePixelRatioChange();
+    this.refreshRows(0, this._rowCount - 1);
+  }
+
+  public onResize(cols: number, rows: number): void {
+    this._renderer.onResize(cols, rows);
+    this._fullRefresh();
+  }
+
+  // TODO: Is this useful when we have onResize?
+  public onCharSizeChanged(): void {
+    this._renderer.onCharSizeChanged();
+  }
+
+  public onBlur(): void {
+    this._renderer.onBlur();
+  }
+
+  public onFocus(): void {
+    this._renderer.onFocus();
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {
+    this._renderer.onSelectionChanged(start, end, columnSelectMode);
+  }
+
+  public onCursorMove(): void {
+    this._renderer.onCursorMove();
+  }
+
+  public clear(): void {
+    this._renderer.clear();
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
+    return this._renderer.registerCharacterJoiner(handler);
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): boolean {
+    return this._renderer.deregisterCharacterJoiner(joinerId);
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/SelectionService.ts b/node_modules/xterm/src/browser/services/SelectionService.ts
new file mode 100644 (file)
index 0000000..3631bbb
--- /dev/null
@@ -0,0 +1,952 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ISelectionRedrawRequestEvent } from 'browser/selection/Types';
+import { IBuffer } from 'common/buffer/Types';
+import { IBufferLine, IDisposable } from 'common/Types';
+import * as Browser from 'common/Platform';
+import { SelectionModel } from 'browser/selection/SelectionModel';
+import { CellData } from 'common/buffer/CellData';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { ICharSizeService, IMouseService, ISelectionService } from 'browser/services/Services';
+import { IBufferService, IOptionsService, ICoreService } from 'common/services/Services';
+import { getCoordsRelativeToElement } from 'browser/input/Mouse';
+import { moveToCellSequence } from 'browser/input/MoveToCell';
+
+/**
+ * The number of pixels the mouse needs to be above or below the viewport in
+ * order to scroll at the maximum speed.
+ */
+const DRAG_SCROLL_MAX_THRESHOLD = 50;
+
+/**
+ * The maximum scrolling speed
+ */
+const DRAG_SCROLL_MAX_SPEED = 15;
+
+/**
+ * The number of milliseconds between drag scroll updates.
+ */
+const DRAG_SCROLL_INTERVAL = 50;
+
+/**
+ * The maximum amount of time that can have elapsed for an alt click to move the
+ * cursor.
+ */
+const ALT_CLICK_MOVE_CURSOR_TIME = 500;
+
+const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
+const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
+
+/**
+ * Represents a position of a word on a line.
+ */
+interface IWordPosition {
+  start: number;
+  length: number;
+}
+
+/**
+ * A selection mode, this drives how the selection behaves on mouse move.
+ */
+export const enum SelectionMode {
+  NORMAL,
+  WORD,
+  LINE,
+  COLUMN
+}
+
+/**
+ * A class that manages the selection of the terminal. With help from
+ * SelectionModel, SelectionService handles with all logic associated with
+ * dealing with the selection, including handling mouse interaction, wide
+ * characters and fetching the actual text within the selection. Rendering is
+ * not handled by the SelectionService but the onRedrawRequest event is fired
+ * when the selection is ready to be redrawn (on an animation frame).
+ */
+export class SelectionService implements ISelectionService {
+  serviceBrand: any;
+
+  protected _model: SelectionModel;
+
+  /**
+   * The amount to scroll every drag scroll update (depends on how far the mouse
+   * drag is above or below the terminal).
+   */
+  private _dragScrollAmount: number = 0;
+
+  /**
+   * The current selection mode.
+   */
+  protected _activeSelectionMode: SelectionMode;
+
+  /**
+   * A setInterval timer that is active while the mouse is down whose callback
+   * scrolls the viewport when necessary.
+   */
+  private _dragScrollIntervalTimer: number | undefined;
+
+  /**
+   * The animation frame ID used for refreshing the selection.
+   */
+  private _refreshAnimationFrame: number | undefined;
+
+  /**
+   * Whether selection is enabled.
+   */
+  private _enabled = true;
+
+  private _mouseMoveListener: EventListener;
+  private _mouseUpListener: EventListener;
+  private _trimListener: IDisposable;
+  private _workCell: CellData = new CellData();
+
+  private _mouseDownTimeStamp: number = 0;
+
+  private _onLinuxMouseSelection = new EventEmitter<string>();
+  public get onLinuxMouseSelection(): IEvent<string> { return this._onLinuxMouseSelection.event; }
+  private _onRedrawRequest = new EventEmitter<ISelectionRedrawRequestEvent>();
+  public get onRedrawRequest(): IEvent<ISelectionRedrawRequestEvent> { return this._onRedrawRequest.event; }
+  private _onSelectionChange = new EventEmitter<void>();
+  public get onSelectionChange(): IEvent<void> { return this._onSelectionChange.event; }
+
+  constructor(
+    private readonly _scrollLines: (amount: number, suppressEvent: boolean) => void,
+    private readonly _element: HTMLElement,
+    private readonly _screenElement: HTMLElement,
+    @ICharSizeService private readonly _charSizeService: ICharSizeService,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @ICoreService private readonly _coreService: ICoreService,
+    @IMouseService private readonly _mouseService: IMouseService,
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    // Init listeners
+    this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
+    this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
+    this._coreService.onUserInput(() => {
+      if (this.hasSelection) {
+        this.clearSelection();
+      }
+    });
+    this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._onTrim(amount));
+    this._bufferService.buffers.onBufferActivate(e => this._onBufferActivate(e));
+
+    this.enable();
+
+    this._model = new SelectionModel(this._bufferService);
+    this._activeSelectionMode = SelectionMode.NORMAL;
+  }
+
+  public dispose(): void {
+    this._removeMouseDownListeners();
+  }
+
+  public reset(): void {
+    this.clearSelection();
+  }
+
+  /**
+   * Disables the selection manager. This is useful for when terminal mouse
+   * are enabled.
+   */
+  public disable(): void {
+    this.clearSelection();
+    this._enabled = false;
+  }
+
+  /**
+   * Enable the selection manager.
+   */
+  public enable(): void {
+    this._enabled = true;
+  }
+
+  public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }
+  public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }
+
+  /**
+   * Gets whether there is an active text selection.
+   */
+  public get hasSelection(): boolean {
+    const start = this._model.finalSelectionStart;
+    const end = this._model.finalSelectionEnd;
+    if (!start || !end) {
+      return false;
+    }
+    return start[0] !== end[0] || start[1] !== end[1];
+  }
+
+  /**
+   * Gets the text currently selected.
+   */
+  public get selectionText(): string {
+    const start = this._model.finalSelectionStart;
+    const end = this._model.finalSelectionEnd;
+    if (!start || !end) {
+      return '';
+    }
+
+    const buffer = this._bufferService.buffer;
+    const result: string[] = [];
+
+    if (this._activeSelectionMode === SelectionMode.COLUMN) {
+      // Ignore zero width selections
+      if (start[0] === end[0]) {
+        return '';
+      }
+
+      for (let i = start[1]; i <= end[1]; i++) {
+        const lineText = buffer.translateBufferLineToString(i, true, start[0], end[0]);
+        result.push(lineText);
+      }
+    } else {
+      // Get first row
+      const startRowEndCol = start[1] === end[1] ? end[0] : undefined;
+      result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));
+
+      // Get middle rows
+      for (let i = start[1] + 1; i <= end[1] - 1; i++) {
+        const bufferLine = buffer.lines.get(i);
+        const lineText = buffer.translateBufferLineToString(i, true);
+        if (bufferLine && bufferLine.isWrapped) {
+          result[result.length - 1] += lineText;
+        } else {
+          result.push(lineText);
+        }
+      }
+
+      // Get final row
+      if (start[1] !== end[1]) {
+        const bufferLine = buffer.lines.get(end[1]);
+        const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);
+        if (bufferLine && bufferLine!.isWrapped) {
+          result[result.length - 1] += lineText;
+        } else {
+          result.push(lineText);
+        }
+      }
+    }
+
+    // Format string by replacing non-breaking space chars with regular spaces
+    // and joining the array into a multi-line string.
+    const formattedResult = result.map(line => {
+      return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
+    }).join(Browser.isWindows ? '\r\n' : '\n');
+
+    return formattedResult;
+  }
+
+  /**
+   * Clears the current terminal selection.
+   */
+  public clearSelection(): void {
+    this._model.clearSelection();
+    this._removeMouseDownListeners();
+    this.refresh();
+    this._onSelectionChange.fire();
+  }
+
+  /**
+   * Queues a refresh, redrawing the selection on the next opportunity.
+   * @param isLinuxMouseSelection Whether the selection should be registered as a new
+   * selection on Linux.
+   */
+  public refresh(isLinuxMouseSelection?: boolean): void {
+    // Queue the refresh for the renderer
+    if (!this._refreshAnimationFrame) {
+      this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
+    }
+
+    // If the platform is Linux and the refresh call comes from a mouse event,
+    // we need to update the selection for middle click to paste selection.
+    if (Browser.isLinux && isLinuxMouseSelection) {
+      const selectionText = this.selectionText;
+      if (selectionText.length) {
+        this._onLinuxMouseSelection.fire(this.selectionText);
+      }
+    }
+  }
+
+  /**
+   * Fires the refresh event, causing consumers to pick it up and redraw the
+   * selection state.
+   */
+  private _refresh(): void {
+    this._refreshAnimationFrame = undefined;
+    this._onRedrawRequest.fire({
+      start: this._model.finalSelectionStart,
+      end: this._model.finalSelectionEnd,
+      columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN
+    });
+  }
+
+  /**
+   * Checks if the current click was inside the current selection
+   * @param event The mouse event
+   */
+  public isClickInSelection(event: MouseEvent): boolean {
+    const coords = this._getMouseBufferCoords(event);
+    const start = this._model.finalSelectionStart;
+    const end = this._model.finalSelectionEnd;
+
+    if (!start || !end || !coords) {
+      return false;
+    }
+
+    return this._areCoordsInSelection(coords, start, end);
+  }
+
+  protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {
+    return (coords[1] > start[1] && coords[1] < end[1]) ||
+        (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||
+        (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||
+        (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);
+  }
+
+  /**
+   * Selects word at the current mouse event coordinates.
+   * @param event The mouse event.
+   */
+  public selectWordAtCursor(event: MouseEvent): void {
+    const coords = this._getMouseBufferCoords(event);
+    if (coords) {
+      this._selectWordAt(coords, false);
+      this._model.selectionEnd = undefined;
+      this.refresh(true);
+    }
+  }
+
+  /**
+   * Selects all text within the terminal.
+   */
+  public selectAll(): void {
+    this._model.isSelectAllActive = true;
+    this.refresh();
+    this._onSelectionChange.fire();
+  }
+
+  public selectLines(start: number, end: number): void {
+    this._model.clearSelection();
+    start = Math.max(start, 0);
+    end = Math.min(end, this._bufferService.buffer.lines.length - 1);
+    this._model.selectionStart = [0, start];
+    this._model.selectionEnd = [this._bufferService.cols, end];
+    this.refresh();
+    this._onSelectionChange.fire();
+  }
+
+  /**
+   * Handle the buffer being trimmed, adjust the selection position.
+   * @param amount The amount the buffer is being trimmed.
+   */
+  private _onTrim(amount: number): void {
+    const needsRefresh = this._model.onTrim(amount);
+    if (needsRefresh) {
+      this.refresh();
+    }
+  }
+
+  /**
+   * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
+   * @param event The mouse event.
+   */
+  private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {
+    const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);
+    if (!coords) {
+      return undefined;
+    }
+
+    // Convert to 0-based
+    coords[0]--;
+    coords[1]--;
+
+    // Convert viewport coords to buffer coords
+    coords[1] += this._bufferService.buffer.ydisp;
+    return coords;
+  }
+
+  /**
+   * Gets the amount the viewport should be scrolled based on how far out of the
+   * terminal the mouse is.
+   * @param event The mouse event.
+   */
+  private _getMouseEventScrollAmount(event: MouseEvent): number {
+    let offset = getCoordsRelativeToElement(event, this._screenElement)[1];
+    const terminalHeight = this._bufferService.rows * Math.ceil(this._charSizeService.height * this._optionsService.options.lineHeight);
+    if (offset >= 0 && offset <= terminalHeight) {
+      return 0;
+    }
+    if (offset > terminalHeight) {
+      offset -= terminalHeight;
+    }
+
+    offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
+    offset /= DRAG_SCROLL_MAX_THRESHOLD;
+    return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
+  }
+
+  /**
+   * Returns whether the selection manager should force selection, regardless of
+   * whether the terminal is in mouse events mode.
+   * @param event The mouse event.
+   */
+  public shouldForceSelection(event: MouseEvent): boolean {
+    if (Browser.isMac) {
+      return event.altKey && this._optionsService.options.macOptionClickForcesSelection;
+    }
+
+    return event.shiftKey;
+  }
+
+  /**
+   * Handles te mousedown event, setting up for a new selection.
+   * @param event The mousedown event.
+   */
+  public onMouseDown(event: MouseEvent): void {
+    this._mouseDownTimeStamp = event.timeStamp;
+    // If we have selection, we want the context menu on right click even if the
+    // terminal is in mouse mode.
+    if (event.button === 2 && this.hasSelection) {
+      return;
+    }
+
+    // Only action the primary button
+    if (event.button !== 0) {
+      return;
+    }
+
+    // Allow selection when using a specific modifier key, even when disabled
+    if (!this._enabled) {
+      if (!this.shouldForceSelection(event)) {
+        return;
+      }
+
+      // Don't send the mouse down event to the current process, we want to select
+      event.stopPropagation();
+    }
+
+    // Tell the browser not to start a regular selection
+    event.preventDefault();
+
+    // Reset drag scroll state
+    this._dragScrollAmount = 0;
+
+    if (this._enabled && event.shiftKey) {
+      this._onIncrementalClick(event);
+    } else {
+      if (event.detail === 1) {
+        this._onSingleClick(event);
+      } else if (event.detail === 2) {
+        this._onDoubleClick(event);
+      } else if (event.detail === 3) {
+        this._onTripleClick(event);
+      }
+    }
+
+    this._addMouseDownListeners();
+    this.refresh(true);
+  }
+
+  /**
+   * Adds listeners when mousedown is triggered.
+   */
+  private _addMouseDownListeners(): void {
+    // Listen on the document so that dragging outside of viewport works
+    if (this._screenElement.ownerDocument) {
+      this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
+      this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
+    }
+    this._dragScrollIntervalTimer = window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
+  }
+
+  /**
+   * Removes the listeners that are registered when mousedown is triggered.
+   */
+  private _removeMouseDownListeners(): void {
+    if (this._screenElement.ownerDocument) {
+      this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
+      this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
+    }
+    clearInterval(this._dragScrollIntervalTimer);
+    this._dragScrollIntervalTimer = undefined;
+  }
+
+  /**
+   * Performs an incremental click, setting the selection end position to the mouse
+   * position.
+   * @param event The mouse event.
+   */
+  private _onIncrementalClick(event: MouseEvent): void {
+    if (this._model.selectionStart) {
+      this._model.selectionEnd = this._getMouseBufferCoords(event);
+    }
+  }
+
+  /**
+   * Performs a single click, resetting relevant state and setting the selection
+   * start position.
+   * @param event The mouse event.
+   */
+  private _onSingleClick(event: MouseEvent): void {
+    this._model.selectionStartLength = 0;
+    this._model.isSelectAllActive = false;
+    this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;
+
+    // Initialize the new selection
+    this._model.selectionStart = this._getMouseBufferCoords(event);
+    if (!this._model.selectionStart) {
+      return;
+    }
+    this._model.selectionEnd = undefined;
+
+    // Ensure the line exists
+    const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);
+    if (!line) {
+      return;
+    }
+
+    // Return early if the click event is not in the buffer (eg. in scroll bar)
+    if (line.length === this._model.selectionStart[0]) {
+      return;
+    }
+
+    // If the mouse is over the second half of a wide character, adjust the
+    // selection to cover the whole character
+    if (line.hasWidth(this._model.selectionStart[0]) === 0) {
+      this._model.selectionStart[0]++;
+    }
+  }
+
+  /**
+   * Performs a double click, selecting the current work.
+   * @param event The mouse event.
+   */
+  private _onDoubleClick(event: MouseEvent): void {
+    const coords = this._getMouseBufferCoords(event);
+    if (coords) {
+      this._activeSelectionMode = SelectionMode.WORD;
+      this._selectWordAt(coords, true);
+    }
+  }
+
+  /**
+   * Performs a triple click, selecting the current line and activating line
+   * select mode.
+   * @param event The mouse event.
+   */
+  private _onTripleClick(event: MouseEvent): void {
+    const coords = this._getMouseBufferCoords(event);
+    if (coords) {
+      this._activeSelectionMode = SelectionMode.LINE;
+      this._selectLineAt(coords[1]);
+    }
+  }
+
+  /**
+   * Returns whether the selection manager should operate in column select mode
+   * @param event the mouse or keyboard event
+   */
+  public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {
+    return event.altKey && !(Browser.isMac && this._optionsService.options.macOptionClickForcesSelection);
+  }
+
+  /**
+   * Handles the mousemove event when the mouse button is down, recording the
+   * end of the selection and refreshing the selection.
+   * @param event The mousemove event.
+   */
+  private _onMouseMove(event: MouseEvent): void {
+    // If the mousemove listener is active it means that a selection is
+    // currently being made, we should stop propagation to prevent mouse events
+    // to be sent to the pty.
+    event.stopImmediatePropagation();
+
+    // Do nothing if there is no selection start, this can happen if the first
+    // click in the terminal is an incremental click
+    if (!this._model.selectionStart) {
+      return;
+    }
+
+    // Record the previous position so we know whether to redraw the selection
+    // at the end.
+    const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
+
+    // Set the initial selection end based on the mouse coordinates
+    this._model.selectionEnd = this._getMouseBufferCoords(event);
+    if (!this._model.selectionEnd) {
+      this.refresh(true);
+      return;
+    }
+
+    // Select the entire line if line select mode is active.
+    if (this._activeSelectionMode === SelectionMode.LINE) {
+      if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
+        this._model.selectionEnd[0] = 0;
+      } else {
+        this._model.selectionEnd[0] = this._bufferService.cols;
+      }
+    } else if (this._activeSelectionMode === SelectionMode.WORD) {
+      this._selectToWordAt(this._model.selectionEnd);
+    }
+
+    // Determine the amount of scrolling that will happen.
+    this._dragScrollAmount = this._getMouseEventScrollAmount(event);
+
+    // If the cursor was above or below the viewport, make sure it's at the
+    // start or end of the viewport respectively. This should only happen when
+    // NOT in column select mode.
+    if (this._activeSelectionMode !== SelectionMode.COLUMN) {
+      if (this._dragScrollAmount > 0) {
+        this._model.selectionEnd[0] = this._bufferService.cols;
+      } else if (this._dragScrollAmount < 0) {
+        this._model.selectionEnd[0] = 0;
+      }
+    }
+
+    // If the character is a wide character include the cell to the right in the
+    // selection. Note that selections at the very end of the line will never
+    // have a character.
+    const buffer = this._bufferService.buffer;
+    if (this._model.selectionEnd[1] < buffer.lines.length) {
+      const line = buffer.lines.get(this._model.selectionEnd[1]);
+      if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {
+        this._model.selectionEnd[0]++;
+      }
+    }
+
+    // Only draw here if the selection changes.
+    if (!previousSelectionEnd ||
+      previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
+      previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
+      this.refresh(true);
+    }
+  }
+
+  /**
+   * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
+   * scrolling of the viewport.
+   */
+  private _dragScroll(): void {
+    if (!this._model.selectionEnd || !this._model.selectionStart) {
+      return;
+    }
+    if (this._dragScrollAmount) {
+      this._scrollLines(this._dragScrollAmount, false);
+      // Re-evaluate selection
+      // If the cursor was above or below the viewport, make sure it's at the
+      // start or end of the viewport respectively. This should only happen when
+      // NOT in column select mode.
+      const buffer = this._bufferService.buffer;
+      if (this._dragScrollAmount > 0) {
+        if (this._activeSelectionMode !== SelectionMode.COLUMN) {
+          this._model.selectionEnd[0] = this._bufferService.cols;
+        }
+        this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);
+      } else {
+        if (this._activeSelectionMode !== SelectionMode.COLUMN) {
+          this._model.selectionEnd[0] = 0;
+        }
+        this._model.selectionEnd[1] = buffer.ydisp;
+      }
+      this.refresh();
+    }
+  }
+
+  /**
+   * Handles the mouseup event, removing the mousedown listeners.
+   * @param event The mouseup event.
+   */
+  private _onMouseUp(event: MouseEvent): void {
+    const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;
+
+    this._removeMouseDownListeners();
+
+    if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) {
+      if (event.altKey && this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {
+        const coordinates = this._mouseService.getCoords(
+          event,
+          this._element,
+          this._bufferService.cols,
+          this._bufferService.rows,
+          false
+        );
+        if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {
+          const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);
+          this._coreService.triggerDataEvent(sequence, true);
+        }
+      }
+    } else if (this.hasSelection) {
+      this._onSelectionChange.fire();
+    }
+  }
+
+  private _onBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {
+    this.clearSelection();
+    // Only adjust the selection on trim, shiftElements is rarely used (only in
+    // reverseIndex) and delete in a splice is only ever used when the same
+    // number of elements was just added. Given this is could actually be
+    // beneficial to leave the selection as is for these cases.
+    if (this._trimListener) {
+      this._trimListener.dispose();
+    }
+    this._trimListener = e.activeBuffer.lines.onTrim(amount => this._onTrim(amount));
+  }
+
+  /**
+   * Converts a viewport column to the character index on the buffer line, the
+   * latter takes into account wide characters.
+   * @param coords The coordinates to find the 2 index for.
+   */
+  private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, coords: [number, number]): number {
+    let charIndex = coords[0];
+    for (let i = 0; coords[0] >= i; i++) {
+      const length = bufferLine.loadCell(i, this._workCell).getChars().length;
+      if (this._workCell.getWidth() === 0) {
+        // Wide characters aren't included in the line string so decrement the
+        // index so the index is back on the wide character.
+        charIndex--;
+      } else if (length > 1 && coords[0] !== i) {
+        // Emojis take up multiple characters, so adjust accordingly. For these
+        // we don't want ot include the character at the column as we're
+        // returning the start index in the string, not the end index.
+        charIndex += length - 1;
+      }
+    }
+    return charIndex;
+  }
+
+  public setSelection(col: number, row: number, length: number): void {
+    this._model.clearSelection();
+    this._removeMouseDownListeners();
+    this._model.selectionStart = [col, row];
+    this._model.selectionStartLength = length;
+    this.refresh();
+  }
+
+  /**
+   * Gets positional information for the word at the coordinated specified.
+   * @param coords The coordinates to get the word at.
+   */
+  private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {
+    // Ensure coords are within viewport (eg. not within scroll bar)
+    if (coords[0] >= this._bufferService.cols) {
+      return undefined;
+    }
+
+    const buffer = this._bufferService.buffer;
+    const bufferLine = buffer.lines.get(coords[1]);
+    if (!bufferLine) {
+      return undefined;
+    }
+
+    const line = buffer.translateBufferLineToString(coords[1], false);
+
+    // Get actual index, taking into consideration wide characters
+    let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
+    let endIndex = startIndex;
+
+    // Record offset to be used later
+    const charOffset = coords[0] - startIndex;
+    let leftWideCharCount = 0;
+    let rightWideCharCount = 0;
+    let leftLongCharOffset = 0;
+    let rightLongCharOffset = 0;
+
+    if (line.charAt(startIndex) === ' ') {
+      // Expand until non-whitespace is hit
+      while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
+        startIndex--;
+      }
+      while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
+        endIndex++;
+      }
+    } else {
+      // Expand until whitespace is hit. This algorithm works by scanning left
+      // and right from the starting position, keeping both the index format
+      // (line) and the column format (bufferLine) in sync. When a wide
+      // character is hit, it is recorded and the column index is adjusted.
+      let startCol = coords[0];
+      let endCol = coords[0];
+
+      // Consider the initial position, skip it and increment the wide char
+      // variable
+      if (bufferLine.getWidth(startCol) === 0) {
+        leftWideCharCount++;
+        startCol--;
+      }
+      if (bufferLine.getWidth(endCol) === 2) {
+        rightWideCharCount++;
+        endCol++;
+      }
+
+      // Adjust the end index for characters whose length are > 1 (emojis)
+      const length = bufferLine.getString(endCol).length;
+      if (length > 1) {
+        rightLongCharOffset += length - 1;
+        endIndex += length - 1;
+      }
+
+      // Expand the string in both directions until a space is hit
+      while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {
+        bufferLine.loadCell(startCol - 1, this._workCell);
+        const length = this._workCell.getChars().length;
+        if (this._workCell.getWidth() === 0) {
+          // If the next character is a wide char, record it and skip the column
+          leftWideCharCount++;
+          startCol--;
+        } else if (length > 1) {
+          // If the next character's string is longer than 1 char (eg. emoji),
+          // adjust the index
+          leftLongCharOffset += length - 1;
+          startIndex -= length - 1;
+        }
+        startIndex--;
+        startCol--;
+      }
+      while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {
+        bufferLine.loadCell(endCol + 1, this._workCell);
+        const length = this._workCell.getChars().length;
+        if (this._workCell.getWidth() === 2) {
+          // If the next character is a wide char, record it and skip the column
+          rightWideCharCount++;
+          endCol++;
+        } else if (length > 1) {
+          // If the next character's string is longer than 1 char (eg. emoji),
+          // adjust the index
+          rightLongCharOffset += length - 1;
+          endIndex += length - 1;
+        }
+        endIndex++;
+        endCol++;
+      }
+    }
+
+    // Incremenet the end index so it is at the start of the next character
+    endIndex++;
+
+    // Calculate the start _column_, converting the the string indexes back to
+    // column coordinates.
+    let start =
+        startIndex // The index of the selection's start char in the line string
+        + charOffset // The difference between the initial char's column and index
+        - leftWideCharCount // The number of wide chars left of the initial char
+        + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
+
+    // Calculate the length in _columns_, converting the the string indexes back
+    // to column coordinates.
+    let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols
+        endIndex // The index of the selection's end char in the line string
+        - startIndex // The index of the selection's start char in the line string
+        + leftWideCharCount // The number of wide chars left of the initial char
+        + rightWideCharCount // The number of wide chars right of the initial char (inclusive)
+        - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
+        - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)
+
+    if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {
+      return undefined;
+    }
+
+    // Recurse upwards if the line is wrapped and the word wraps to the above line
+    if (followWrappedLinesAbove) {
+      if (start === 0 && bufferLine.getCodePoint(0) !== 32 /*' '*/) {
+        const previousBufferLine = buffer.lines.get(coords[1] - 1);
+        if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {
+          const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);
+          if (previousLineWordPosition) {
+            const offset = this._bufferService.cols - previousLineWordPosition.start;
+            start -= offset;
+            length += offset;
+          }
+        }
+      }
+    }
+
+    // Recurse downwards if the line is wrapped and the word wraps to the next line
+    if (followWrappedLinesBelow) {
+      if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /*' '*/) {
+        const nextBufferLine = buffer.lines.get(coords[1] + 1);
+        if (nextBufferLine && nextBufferLine.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /*' '*/) {
+          const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);
+          if (nextLineWordPosition) {
+            length += nextLineWordPosition.length;
+          }
+        }
+      }
+    }
+
+    return { start, length };
+  }
+
+  /**
+   * Selects the word at the coordinates specified.
+   * @param coords The coordinates to get the word at.
+   * @param allowWhitespaceOnlySelection If whitespace should be selected
+   */
+  protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {
+    const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);
+    if (wordPosition) {
+      // Adjust negative start value
+      while (wordPosition.start < 0) {
+        wordPosition.start += this._bufferService.cols;
+        coords[1]--;
+      }
+      this._model.selectionStart = [wordPosition.start, coords[1]];
+      this._model.selectionStartLength = wordPosition.length;
+    }
+  }
+
+  /**
+   * Sets the selection end to the word at the coordinated specified.
+   * @param coords The coordinates to get the word at.
+   */
+  private _selectToWordAt(coords: [number, number]): void {
+    const wordPosition = this._getWordAt(coords, true);
+    if (wordPosition) {
+      let endRow = coords[1];
+
+      // Adjust negative start value
+      while (wordPosition.start < 0) {
+        wordPosition.start += this._bufferService.cols;
+        endRow--;
+      }
+
+      // Adjust wrapped length value, this only needs to happen when values are reversed as in that
+      // case we're interested in the start of the word, not the end
+      if (!this._model.areSelectionValuesReversed()) {
+        while (wordPosition.start + wordPosition.length > this._bufferService.cols) {
+          wordPosition.length -= this._bufferService.cols;
+          endRow++;
+        }
+      }
+
+      this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];
+    }
+  }
+
+  /**
+   * Gets whether the character is considered a word separator by the select
+   * word logic.
+   * @param char The character to check.
+   */
+  private _isCharWordSeparator(cell: CellData): boolean {
+    // Zero width characters are never separators as they are always to the
+    // right of wide characters
+    if (cell.getWidth() === 0) {
+      return false;
+    }
+    return this._optionsService.options.wordSeparator.indexOf(cell.getChars()) >= 0;
+  }
+
+  /**
+   * Selects the line specified.
+   * @param line The line index.
+   */
+  protected _selectLineAt(line: number): void {
+    const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);
+    this._model.selectionStart = [0, wrappedRange.first];
+    this._model.selectionEnd = [this._bufferService.cols, wrappedRange.last];
+    this._model.selectionStartLength = 0;
+  }
+}
diff --git a/node_modules/xterm/src/browser/services/Services.ts b/node_modules/xterm/src/browser/services/Services.ts
new file mode 100644 (file)
index 0000000..2170a04
--- /dev/null
@@ -0,0 +1,95 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent } from 'common/EventEmitter';
+import { IRenderDimensions, IRenderer, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { IColorSet } from 'browser/Types';
+import { ISelectionRedrawRequestEvent } from 'browser/selection/Types';
+import { createDecorator } from 'common/services/ServiceRegistry';
+import { IDisposable } from 'common/Types';
+
+export const ICharSizeService = createDecorator<ICharSizeService>('CharSizeService');
+export interface ICharSizeService {
+  serviceBrand: any;
+
+  readonly width: number;
+  readonly height: number;
+  readonly hasValidSize: boolean;
+
+  readonly onCharSizeChange: IEvent<void>;
+
+  measure(): void;
+}
+
+export const IMouseService = createDecorator<IMouseService>('MouseService');
+export interface IMouseService {
+  serviceBrand: any;
+
+  getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, isSelection?: boolean): [number, number] | undefined;
+  getRawByteCoords(event: MouseEvent, element: HTMLElement, colCount: number, rowCount: number): { x: number, y: number } | undefined;
+}
+
+export const IRenderService = createDecorator<IRenderService>('RenderService');
+export interface IRenderService extends IDisposable {
+  serviceBrand: any;
+
+  onDimensionsChange: IEvent<IRenderDimensions>;
+  onRender: IEvent<{ start: number, end: number }>;
+  onRefreshRequest: IEvent<{ start: number, end: number }>;
+
+  dimensions: IRenderDimensions;
+
+  refreshRows(start: number, end: number): void;
+  resize(cols: number, rows: number): void;
+  changeOptions(): void;
+  setRenderer(renderer: IRenderer): void;
+  setColors(colors: IColorSet): void;
+  onDevicePixelRatioChange(): void;
+  onResize(cols: number, rows: number): void;
+  // TODO: Is this useful when we have onResize?
+  onCharSizeChanged(): void;
+  onBlur(): void;
+  onFocus(): void;
+  onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void;
+  onCursorMove(): void;
+  clear(): void;
+  registerCharacterJoiner(handler: CharacterJoinerHandler): number;
+  deregisterCharacterJoiner(joinerId: number): boolean;
+}
+
+export const ISelectionService = createDecorator<ISelectionService>('SelectionService');
+export interface ISelectionService {
+  serviceBrand: any;
+
+  readonly selectionText: string;
+  readonly hasSelection: boolean;
+  readonly selectionStart: [number, number] | undefined;
+  readonly selectionEnd: [number, number] | undefined;
+
+  readonly onLinuxMouseSelection: IEvent<string>;
+  readonly onRedrawRequest: IEvent<ISelectionRedrawRequestEvent>;
+  readonly onSelectionChange: IEvent<void>;
+
+  disable(): void;
+  enable(): void;
+  reset(): void;
+  setSelection(row: number, col: number, length: number): void;
+  selectAll(): void;
+  selectLines(start: number, end: number): void;
+  clearSelection(): void;
+  isClickInSelection(event: MouseEvent): boolean;
+  selectWordAtCursor(event: MouseEvent): void;
+  shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean;
+  shouldForceSelection(event: MouseEvent): boolean;
+  refresh(isLinuxMouseSelection?: boolean): void;
+  onMouseDown(event: MouseEvent): void;
+}
+
+export const ISoundService = createDecorator<ISoundService>('SoundService');
+export interface ISoundService {
+  serviceBrand: any;
+
+  playBellSound(): void;
+}
diff --git a/node_modules/xterm/src/browser/services/SoundService.ts b/node_modules/xterm/src/browser/services/SoundService.ts
new file mode 100644 (file)
index 0000000..1772c75
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOptionsService } from 'common/services/Services';
+import { ISoundService } from 'browser/services/Services';
+
+export class SoundService implements ISoundService {
+  serviceBrand: any;
+
+  private static _audioContext: AudioContext;
+
+  static get audioContext(): AudioContext | null {
+    if (!SoundService._audioContext) {
+      const audioContextCtor: typeof AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;
+      if (!audioContextCtor) {
+        console.warn('Web Audio API is not supported by this browser. Consider upgrading to the latest version');
+        return null;
+      }
+      SoundService._audioContext = new audioContextCtor();
+    }
+    return SoundService._audioContext;
+  }
+
+  constructor(
+    @IOptionsService private _optionsService: IOptionsService
+  ) {
+  }
+
+  public playBellSound(): void {
+    const ctx = SoundService.audioContext;
+    if (!ctx) {
+      return;
+    }
+    const bellAudioSource = ctx.createBufferSource();
+    ctx.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)), (buffer) => {
+      bellAudioSource.buffer = buffer;
+      bellAudioSource.connect(ctx.destination);
+      bellAudioSource.start(0);
+    });
+  }
+
+  private _base64ToArrayBuffer(base64: string): ArrayBuffer {
+    const binaryString = window.atob(base64);
+    const len = binaryString.length;
+    const bytes = new Uint8Array(len);
+
+    for (let i = 0; i < len; i++) {
+      bytes[i] = binaryString.charCodeAt(i);
+    }
+
+    return bytes.buffer;
+  }
+
+  private _removeMimeType(dataURI: string): string {
+    // Split the input to get the mime-type and the data itself
+    const splitUri = dataURI.split(',');
+
+    // Return only the data
+    return splitUri[1];
+  }
+}
diff --git a/node_modules/xterm/src/browser/tsconfig.json b/node_modules/xterm/src/browser/tsconfig.json
new file mode 100644 (file)
index 0000000..7465bbd
--- /dev/null
@@ -0,0 +1,21 @@
+{
+  "extends": "../tsconfig-library-base",
+  "compilerOptions": {
+    "lib": [
+      "dom",
+      "es2015",
+    ],
+    "outDir": "../../out",
+    "types": [
+      "../../node_modules/@types/mocha"
+    ],
+    "baseUrl": "..",
+    "paths": {
+      "common/*": [ "./common/*" ]
+    }
+  },
+  "include": [ "./**/*" ],
+  "references": [
+    { "path": "../common" }
+  ]
+}
diff --git a/node_modules/xterm/src/common/CharWidth.ts b/node_modules/xterm/src/common/CharWidth.ts
new file mode 100644 (file)
index 0000000..24f5345
--- /dev/null
@@ -0,0 +1,171 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { fill } from 'common/TypedArrayUtils';
+
+export const wcwidth = (function(opts: {nul: number, control: number}): (ucs: number) => number {
+  // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c
+  // combining characters
+  const COMBINING_BMP = [
+    [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
+    [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
+    [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
+    [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
+    [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
+    [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
+    [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
+    [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
+    [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
+    [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
+    [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
+    [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
+    [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
+    [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
+    [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
+    [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
+    [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
+    [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
+    [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
+    [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
+    [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
+    [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
+    [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
+    [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
+    [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
+    [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
+    [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
+    [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
+    [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
+    [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
+    [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
+    [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
+    [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
+    [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
+    [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
+    [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
+    [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
+    [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
+    [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
+    [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
+    [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
+    [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
+    [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB]
+  ];
+  const COMBINING_HIGH = [
+    [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
+    [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
+    [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
+    [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
+    [0xE0100, 0xE01EF]
+  ];
+  // binary search
+  function bisearch(ucs: number, data: number[][]): boolean {
+    let min = 0;
+    let max = data.length - 1;
+    let mid;
+    if (ucs < data[0][0] || ucs > data[max][1]) {
+      return false;
+    }
+    while (max >= min) {
+      mid = (min + max) >> 1;
+      if (ucs > data[mid][1]) {
+        min = mid + 1;
+      } else if (ucs < data[mid][0]) {
+        max = mid - 1;
+      } else {
+        return true;
+      }
+    }
+    return false;
+  }
+  function wcwidthHigh(ucs: number): 0 | 1 | 2 {
+    if (bisearch(ucs, COMBINING_HIGH)) {
+      return 0;
+    }
+    if ((ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd)) {
+      return 2;
+    }
+    return 1;
+  }
+  const control = opts.control | 0;
+
+  // create lookup table for BMP plane
+  const table = new Uint8Array(65536);
+  fill(table, 1);
+  table[0] = opts.nul;
+  // control chars
+  fill(table, opts.control, 1, 32);
+  fill(table, opts.control, 0x7f, 0xa0);
+
+  // apply wide char rules first
+  // wide chars
+  fill(table, 2, 0x1100, 0x1160);
+  table[0x2329] = 2;
+  table[0x232a] = 2;
+  fill(table, 2, 0x2e80, 0xa4d0);
+  table[0x303f] = 1;  // wrongly in last line
+
+  fill(table, 2, 0xac00, 0xd7a4);
+  fill(table, 2, 0xf900, 0xfb00);
+  fill(table, 2, 0xfe10, 0xfe1a);
+  fill(table, 2, 0xfe30, 0xfe70);
+  fill(table, 2, 0xff00, 0xff61);
+  fill(table, 2, 0xffe0, 0xffe7);
+
+  // apply combining last to ensure we overwrite
+  // wrongly wide set chars:
+  //    the original algo evals combining first and falls
+  //    through to wide check so we simply do here the opposite
+  // combining 0
+  for (let r = 0; r < COMBINING_BMP.length; ++r) {
+    fill(table, 0, COMBINING_BMP[r][0], COMBINING_BMP[r][1] + 1);
+  }
+
+  return function (num: number): number {
+    if (num < 32) {
+      return control | 0;
+    }
+    if (num < 127) {
+      return 1;
+    }
+    if (num < 65536) {
+      return table[num];
+    }
+    // do a full search for high codepoints
+    return wcwidthHigh(num);
+  };
+})({nul: 0, control: 0});  // configurable options
+
+/**
+ * Get the terminal cell width for a string.
+ */
+export function getStringCellWidth(s: string): number {
+  let result = 0;
+  const length = s.length;
+  for (let i = 0; i < length; ++i) {
+    let code = s.charCodeAt(i);
+    // surrogate pair first
+    if (0xD800 <= code && code <= 0xDBFF) {
+      if (++i >= length) {
+        // this should not happen with strings retrieved from
+        // Buffer.translateToString as it converts from UTF-32
+        // and therefore always should contain the second part
+        // for any other string we still have to handle it somehow:
+        // simply treat the lonely surrogate first as a single char (UCS-2 behavior)
+        return result + wcwidth(code);
+      }
+      const second = s.charCodeAt(i);
+      // convert surrogate pair to high codepoint only for valid second part (UTF-16)
+      // otherwise treat them independently (UCS-2 behavior)
+      if (0xDC00 <= second && second <= 0xDFFF) {
+        code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+      } else {
+        result += wcwidth(second);
+      }
+    }
+    result += wcwidth(code);
+  }
+  return result;
+}
diff --git a/node_modules/xterm/src/common/CircularList.ts b/node_modules/xterm/src/common/CircularList.ts
new file mode 100644 (file)
index 0000000..d4ad3fc
--- /dev/null
@@ -0,0 +1,235 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICircularList } from 'common/Types';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+
+export interface IInsertEvent {
+  index: number;
+  amount: number;
+}
+
+export interface IDeleteEvent {
+  index: number;
+  amount: number;
+}
+
+/**
+ * Represents a circular list; a list with a maximum size that wraps around when push is called,
+ * overriding values at the start of the list.
+ */
+export class CircularList<T> implements ICircularList<T> {
+  protected _array: (T | undefined)[];
+  private _startIndex: number;
+  private _length: number;
+
+  public onDeleteEmitter = new EventEmitter<IDeleteEvent>();
+  public get onDelete(): IEvent<IDeleteEvent> { return this.onDeleteEmitter.event; }
+  public onInsertEmitter = new EventEmitter<IInsertEvent>();
+  public get onInsert(): IEvent<IInsertEvent> { return this.onInsertEmitter.event; }
+  public onTrimEmitter = new EventEmitter<number>();
+  public get onTrim(): IEvent<number> { return this.onTrimEmitter.event; }
+
+  constructor(
+    private _maxLength: number
+  ) {
+    this._array = new Array<T>(this._maxLength);
+    this._startIndex = 0;
+    this._length = 0;
+  }
+
+  public get maxLength(): number {
+    return this._maxLength;
+  }
+
+  public set maxLength(newMaxLength: number) {
+    // There was no change in maxLength, return early.
+    if (this._maxLength === newMaxLength) {
+      return;
+    }
+
+    // Reconstruct array, starting at index 0. Only transfer values from the
+    // indexes 0 to length.
+    const newArray = new Array<T | undefined>(newMaxLength);
+    for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {
+      newArray[i] = this._array[this._getCyclicIndex(i)];
+    }
+    this._array = newArray;
+    this._maxLength = newMaxLength;
+    this._startIndex = 0;
+  }
+
+  public get length(): number {
+    return this._length;
+  }
+
+  public set length(newLength: number) {
+    if (newLength > this._length) {
+      for (let i = this._length; i < newLength; i++) {
+        this._array[i] = undefined;
+      }
+    }
+    this._length = newLength;
+  }
+
+  /**
+   * Gets the value at an index.
+   *
+   * Note that for performance reasons there is no bounds checking here, the index reference is
+   * circular so this should always return a value and never throw.
+   * @param index The index of the value to get.
+   * @return The value corresponding to the index.
+   */
+  public get(index: number): T | undefined {
+    return this._array[this._getCyclicIndex(index)];
+  }
+
+  /**
+   * Sets the value at an index.
+   *
+   * Note that for performance reasons there is no bounds checking here, the index reference is
+   * circular so this should always return a value and never throw.
+   * @param index The index to set.
+   * @param value The value to set.
+   */
+  public set(index: number, value: T | undefined): void {
+    this._array[this._getCyclicIndex(index)] = value;
+  }
+
+  /**
+   * Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0
+   * if the maximum length is reached.
+   * @param value The value to push onto the list.
+   */
+  public push(value: T): void {
+    this._array[this._getCyclicIndex(this._length)] = value;
+    if (this._length === this._maxLength) {
+      this._startIndex = ++this._startIndex % this._maxLength;
+      this.onTrimEmitter.fire(1);
+    } else {
+      this._length++;
+    }
+  }
+
+  /**
+   * Advance ringbuffer index and return current element for recycling.
+   * Note: The buffer must be full for this method to work.
+   * @throws When the buffer is not full.
+   */
+  public recycle(): T {
+    if (this._length !== this._maxLength) {
+      throw new Error('Can only recycle when the buffer is full');
+    }
+    this._startIndex = ++this._startIndex % this._maxLength;
+    this.onTrimEmitter.fire(1);
+    return this._array[this._getCyclicIndex(this._length - 1)]!;
+  }
+
+  /**
+   * Ringbuffer is at max length.
+   */
+  public get isFull(): boolean {
+    return this._length === this._maxLength;
+  }
+
+  /**
+   * Removes and returns the last value on the list.
+   * @return The popped value.
+   */
+  public pop(): T | undefined {
+    return this._array[this._getCyclicIndex(this._length-- - 1)];
+  }
+
+  /**
+   * Deletes and/or inserts items at a particular index (in that order). Unlike
+   * Array.prototype.splice, this operation does not return the deleted items as a new array in
+   * order to save creating a new array. Note that this operation may shift all values in the list
+   * in the worst case.
+   * @param start The index to delete and/or insert.
+   * @param deleteCount The number of elements to delete.
+   * @param items The items to insert.
+   */
+  public splice(start: number, deleteCount: number, ...items: T[]): void {
+    // Delete items
+    if (deleteCount) {
+      for (let i = start; i < this._length - deleteCount; i++) {
+        this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];
+      }
+      this._length -= deleteCount;
+    }
+
+    // Add items
+    for (let i = this._length - 1; i >= start; i--) {
+      this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];
+    }
+    for (let i = 0; i < items.length; i++) {
+      this._array[this._getCyclicIndex(start + i)] = items[i];
+    }
+
+    // Adjust length as needed
+    if (this._length + items.length > this._maxLength) {
+      const countToTrim = (this._length + items.length) - this._maxLength;
+      this._startIndex += countToTrim;
+      this._length = this._maxLength;
+      this.onTrimEmitter.fire(countToTrim);
+    } else {
+      this._length += items.length;
+    }
+  }
+
+  /**
+   * Trims a number of items from the start of the list.
+   * @param count The number of items to remove.
+   */
+  public trimStart(count: number): void {
+    if (count > this._length) {
+      count = this._length;
+    }
+    this._startIndex += count;
+    this._length -= count;
+    this.onTrimEmitter.fire(count);
+  }
+
+  public shiftElements(start: number, count: number, offset: number): void {
+    if (count <= 0) {
+      return;
+    }
+    if (start < 0 || start >= this._length) {
+      throw new Error('start argument out of range');
+    }
+    if (start + offset < 0) {
+      throw new Error('Cannot shift elements in list beyond index 0');
+    }
+
+    if (offset > 0) {
+      for (let i = count - 1; i >= 0; i--) {
+        this.set(start + i + offset, this.get(start + i));
+      }
+      const expandListBy = (start + count + offset) - this._length;
+      if (expandListBy > 0) {
+        this._length += expandListBy;
+        while (this._length > this._maxLength) {
+          this._length--;
+          this._startIndex++;
+          this.onTrimEmitter.fire(1);
+        }
+      }
+    } else {
+      for (let i = 0; i < count; i++) {
+        this.set(start + i + offset, this.get(start + i));
+      }
+    }
+  }
+
+  /**
+   * Gets the cyclic index for the specified regular index. The cyclic index can then be used on the
+   * backing array to get the element associated with the regular index.
+   * @param index The regular index.
+   * @returns The cyclic index.
+   */
+  private _getCyclicIndex(index: number): number {
+    return (this._startIndex + index) % this._maxLength;
+  }
+}
diff --git a/node_modules/xterm/src/common/Clone.ts b/node_modules/xterm/src/common/Clone.ts
new file mode 100644 (file)
index 0000000..51c5aba
--- /dev/null
@@ -0,0 +1,23 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/*
+ * A simple utility for cloning values
+ */
+export function clone<T>(val: T, depth: number = 5): T {
+  if (typeof val !== 'object') {
+    return val;
+  }
+
+  // If we're cloning an array, use an array as the base, otherwise use an object
+  const clonedObject: any = Array.isArray(val) ? [] : {};
+
+  for (const key in val) {
+    // Recursively clone eack item unless we're at the maximum depth
+    clonedObject[key] = depth <= 1 ? val[key] : (val[key] ? clone(val[key], depth - 1) : val[key]);
+  }
+
+  return clonedObject as T;
+}
diff --git a/node_modules/xterm/src/common/EventEmitter.ts b/node_modules/xterm/src/common/EventEmitter.ts
new file mode 100644 (file)
index 0000000..34ac190
--- /dev/null
@@ -0,0 +1,54 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+interface IListener<T> {
+  (e: T): void;
+}
+
+export interface IEvent<T> {
+  (listener: (e: T) => any): IDisposable;
+}
+
+export interface IEventEmitter<T> {
+  event: IEvent<T>;
+  fire(data: T): void;
+}
+
+export class EventEmitter<T> implements IEventEmitter<T> {
+  private _listeners: IListener<T>[] = [];
+  private _event?: IEvent<T>;
+
+  public get event(): IEvent<T> {
+    if (!this._event) {
+      this._event = (listener: (e: T) => any) => {
+        this._listeners.push(listener);
+        const disposable = {
+          dispose: () => {
+            for (let i = 0; i < this._listeners.length; i++) {
+              if (this._listeners[i] === listener) {
+                this._listeners.splice(i, 1);
+                return;
+              }
+            }
+          }
+        };
+        return disposable;
+      };
+    }
+    return this._event;
+  }
+
+  public fire(data: T): void {
+    const queue: IListener<T>[] = [];
+    for (let i = 0; i < this._listeners.length; i++) {
+      queue.push(this._listeners[i]);
+    }
+    for (let i = 0; i < queue.length; i++) {
+      queue[i].call(undefined, data);
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/Lifecycle.ts b/node_modules/xterm/src/common/Lifecycle.ts
new file mode 100644 (file)
index 0000000..ad1afa1
--- /dev/null
@@ -0,0 +1,47 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+
+/**
+ * A base class that can be extended to provide convenience methods for managing the lifecycle of an
+ * object and its components.
+ */
+export abstract class Disposable implements IDisposable {
+  protected _disposables: IDisposable[] = [];
+  protected _isDisposed: boolean = false;
+
+  constructor() {
+  }
+
+  /**
+   * Disposes the object, triggering the `dispose` method on all registered IDisposables.
+   */
+  public dispose(): void {
+    this._isDisposed = true;
+    this._disposables.forEach(d => d.dispose());
+    this._disposables.length = 0;
+  }
+
+  /**
+   * Registers a disposable object.
+   * @param d The disposable to register.
+   */
+  public register<T extends IDisposable>(d: T): void {
+    this._disposables.push(d);
+  }
+
+  /**
+   * Unregisters a disposable object if it has been registered, if not do
+   * nothing.
+   * @param d The disposable to unregister.
+   */
+  public unregister<T extends IDisposable>(d: T): void {
+    const index = this._disposables.indexOf(d);
+    if (index !== -1) {
+      this._disposables.splice(index, 1);
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/Platform.ts b/node_modules/xterm/src/common/Platform.ts
new file mode 100644 (file)
index 0000000..aae06c7
--- /dev/null
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+interface INavigator {
+  userAgent: string;
+  language: string;
+  platform: string;
+}
+
+// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but
+// we want this module to live in common.
+declare const navigator: INavigator;
+
+const isNode = (typeof navigator === 'undefined') ? true : false;
+const userAgent = (isNode) ? 'node' : navigator.userAgent;
+const platform = (isNode) ? 'node' : navigator.platform;
+
+export const isFirefox = !!~userAgent.indexOf('Firefox');
+export const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);
+
+// Find the users platform. We use this to interpret the meta key
+// and ISO third level shifts.
+// http://stackoverflow.com/q/19877924/577598
+export const isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);
+export const isIpad = platform === 'iPad';
+export const isIphone = platform === 'iPhone';
+export const isWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);
+export const isLinux = platform.indexOf('Linux') >= 0;
+
+/**
+ * Return if the given array contains the given element
+ * @param arr The array to search for the given element.
+ * @param el The element to look for into the array
+ */
+function contains(arr: any[], el: any): boolean {
+  return arr.indexOf(el) >= 0;
+}
diff --git a/node_modules/xterm/src/common/TypedArrayUtils.ts b/node_modules/xterm/src/common/TypedArrayUtils.ts
new file mode 100644 (file)
index 0000000..5469983
--- /dev/null
@@ -0,0 +1,52 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export type TypedArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray
+  | Int8Array | Int16Array | Int32Array
+  | Float32Array | Float64Array;
+
+
+/**
+ * polyfill for TypedArray.fill
+ * This is needed to support .fill in all safari versions and IE 11.
+ */
+export function fill<T extends TypedArray>(array: T, value: number, start?: number, end?: number): T {
+  // all modern engines that support .fill
+  if (array.fill) {
+    return array.fill(value, start, end) as T;
+  }
+  return fillFallback(array, value, start, end);
+}
+
+export function fillFallback<T extends TypedArray>(array: T, value: number, start: number = 0, end: number = array.length): T {
+  // safari and IE 11
+  // since IE 11 does not support Array.prototype.fill either
+  // we cannot use the suggested polyfill from MDN
+  // instead we simply fall back to looping
+  if (start >= array.length) {
+    return array;
+  }
+  start = (array.length + start) % array.length;
+  if (end >= array.length) {
+    end = array.length;
+  } else {
+    end = (array.length + end) % array.length;
+  }
+  for (let i = start; i < end; ++i) {
+    array[i] = value;
+  }
+  return array;
+}
+
+/**
+ * Concat two typed arrays `a` and `b`.
+ * Returns a new typed array.
+ */
+export function concat<T extends TypedArray>(a: T, b: T): T {
+  const result = new (a.constructor as any)(a.length + b.length);
+  result.set(a);
+  result.set(b, a.length);
+  return result;
+}
diff --git a/node_modules/xterm/src/common/Types.d.ts b/node_modules/xterm/src/common/Types.d.ts
new file mode 100644 (file)
index 0000000..2f74203
--- /dev/null
@@ -0,0 +1,253 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent, IEventEmitter } from 'common/EventEmitter';
+import { IDeleteEvent, IInsertEvent } from 'common/CircularList';
+
+export interface IDisposable {
+  dispose(): void;
+}
+
+export type XtermListener = (...args: any[]) => void;
+
+/**
+ * A keyboard event interface which does not depend on the DOM, KeyboardEvent implicitly extends
+ * this event.
+ */
+export interface IKeyboardEvent {
+  altKey: boolean;
+  ctrlKey: boolean;
+  shiftKey: boolean;
+  metaKey: boolean;
+  keyCode: number;
+  key: string;
+  type: string;
+}
+
+export interface ICircularList<T> {
+  length: number;
+  maxLength: number;
+  isFull: boolean;
+
+  onDeleteEmitter: IEventEmitter<IDeleteEvent>;
+  onDelete: IEvent<IDeleteEvent>;
+  onInsertEmitter: IEventEmitter<IInsertEvent>;
+  onInsert: IEvent<IInsertEvent>;
+  onTrimEmitter: IEventEmitter<number>;
+  onTrim: IEvent<number>;
+
+  get(index: number): T | undefined;
+  set(index: number, value: T): void;
+  push(value: T): void;
+  recycle(): T | undefined;
+  pop(): T | undefined;
+  splice(start: number, deleteCount: number, ...items: T[]): void;
+  trimStart(count: number): void;
+  shiftElements(start: number, count: number, offset: number): void;
+}
+
+export const enum KeyboardResultType {
+  SEND_KEY,
+  SELECT_ALL,
+  PAGE_UP,
+  PAGE_DOWN
+}
+
+export interface IKeyboardResult {
+  type: KeyboardResultType;
+  cancel: boolean;
+  key: string | undefined;
+}
+
+export interface ICharset {
+  [key: string]: string;
+}
+
+export type CharData = [number, string, number, number];
+export type IColorRGB = [number, number, number];
+
+/** Attribute data */
+export interface IAttributeData {
+  fg: number;
+  bg: number;
+
+  clone(): IAttributeData;
+
+  // flags
+  isInverse(): number;
+  isBold(): number;
+  isUnderline(): number;
+  isBlink(): number;
+  isInvisible(): number;
+  isItalic(): number;
+  isDim(): number;
+
+  // color modes
+  getFgColorMode(): number;
+  getBgColorMode(): number;
+  isFgRGB(): boolean;
+  isBgRGB(): boolean;
+  isFgPalette(): boolean;
+  isBgPalette(): boolean;
+  isFgDefault(): boolean;
+  isBgDefault(): boolean;
+
+  // colors
+  getFgColor(): number;
+  getBgColor(): number;
+}
+
+/** Cell data */
+export interface ICellData extends IAttributeData {
+  content: number;
+  combinedData: string;
+  isCombined(): number;
+  getWidth(): number;
+  getChars(): string;
+  getCode(): number;
+  setFromCharData(value: CharData): void;
+  getAsCharData(): CharData;
+}
+
+/**
+ * Interface for a line in the terminal buffer.
+ */
+export interface IBufferLine {
+  length: number;
+  isWrapped: boolean;
+  get(index: number): CharData;
+  set(index: number, value: CharData): void;
+  loadCell(index: number, cell: ICellData): ICellData;
+  setCell(index: number, cell: ICellData): void;
+  setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number): void;
+  addCodepointToCell(index: number, codePoint: number): void;
+  insertCells(pos: number, n: number, ch: ICellData): void;
+  deleteCells(pos: number, n: number, fill: ICellData): void;
+  replaceCells(start: number, end: number, fill: ICellData): void;
+  resize(cols: number, fill: ICellData): void;
+  fill(fillCellData: ICellData): void;
+  copyFrom(line: IBufferLine): void;
+  clone(): IBufferLine;
+  getTrimmedLength(): number;
+  translateToString(trimRight?: boolean, startCol?: number, endCol?: number): string;
+
+  /* direct access to cell attrs */
+  getWidth(index: number): number;
+  hasWidth(index: number): number;
+  getFg(index: number): number;
+  getBg(index: number): number;
+  hasContent(index: number): number;
+  getCodePoint(index: number): number;
+  isCombined(index: number): number;
+  getString(index: number): string;
+}
+
+export interface IMarker extends IDisposable {
+  readonly id: number;
+  readonly isDisposed: boolean;
+  readonly line: number;
+}
+
+export interface IDecPrivateModes {
+  applicationCursorKeys: boolean;
+}
+
+export interface IRowRange {
+  start: number;
+  end: number;
+}
+
+/**
+ * Interface for mouse events in the core.
+ */
+export const enum CoreMouseButton {
+  LEFT = 0,
+  MIDDLE = 1,
+  RIGHT = 2,
+  NONE = 3,
+  WHEEL = 4,
+  // additional buttons 1..8
+  // untested!
+  AUX1 = 8,
+  AUX2 = 9,
+  AUX3 = 10,
+  AUX4 = 11,
+  AUX5 = 12,
+  AUX6 = 13,
+  AUX7 = 14,
+  AUX8 = 15
+}
+
+export const enum CoreMouseAction {
+  UP = 0,     // buttons, wheel
+  DOWN = 1,   // buttons, wheel
+  LEFT = 2,   // wheel only
+  RIGHT = 3,  // wheel only
+  MOVE = 32   // buttons only
+}
+
+export interface ICoreMouseEvent {
+  /** column (zero based). */
+  col: number;
+  /** row (zero based). */
+  row: number;
+  /**
+   * Button the action occured. Due to restrictions of the tracking protocols
+   * it is not possible to report multiple buttons at once.
+   * Wheel is treated as a button.
+   * There are invalid combinations of buttons and actions possible
+   * (like move + wheel), those are silently ignored by the CoreMouseService.
+   */
+  button: CoreMouseButton;
+  action: CoreMouseAction;
+  /**
+   * Modifier states.
+   * Protocols will add/ignore those based on specific restrictions.
+   */
+  ctrl?: boolean;
+  alt?: boolean;
+  shift?: boolean;
+}
+
+/**
+ * CoreMouseEventType
+ * To be reported to the browser component which events a mouse
+ * protocol wants to be catched and forwarded as an ICoreMouseEvent
+ * to CoreMouseService.
+ */
+export const enum CoreMouseEventType {
+  NONE = 0,
+  /** any mousedown event */
+  DOWN = 1,
+  /** any mouseup event */
+  UP = 2,
+  /** any mousemove event while a button is held */
+  DRAG = 4,
+  /** any mousemove event without a button */
+  MOVE = 8,
+  /** any wheel event */
+  WHEEL = 16
+}
+
+/**
+ * Mouse protocol interface.
+ * A mouse protocol can be registered and activated at the CoreMouseService.
+ * `events` should contain a list of needed events as a hint for the browser component
+ * to install/remove the appropriate event handlers.
+ * `restrict` applies further protocol specific restrictions like not allowed
+ * modifiers or filtering invalid event types.
+ */
+export interface ICoreMouseProtocol {
+  events: CoreMouseEventType;
+  restrict: (e: ICoreMouseEvent) => boolean;
+}
+
+/**
+ * CoreMouseEncoding
+ * The tracking encoding can be registered and activated at the CoreMouseService.
+ * If a ICoreMouseEvent passes all procotol restrictions it will be encoded
+ * with the active encoding and sent out.
+ */
+export type CoreMouseEncoding = (event: ICoreMouseEvent) => string;
diff --git a/node_modules/xterm/src/common/buffer/AttributeData.ts b/node_modules/xterm/src/common/buffer/AttributeData.ts
new file mode 100644 (file)
index 0000000..0e7e270
--- /dev/null
@@ -0,0 +1,68 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IAttributeData, IColorRGB } from 'common/Types';
+import { Attributes, FgFlags, BgFlags } from 'common/buffer/Constants';
+
+export class AttributeData implements IAttributeData {
+  static toColorRGB(value: number): IColorRGB {
+    return [
+      value >>> Attributes.RED_SHIFT & 255,
+      value >>> Attributes.GREEN_SHIFT & 255,
+      value & 255
+    ];
+  }
+  static fromColorRGB(value: IColorRGB): number {
+    return (value[0] & 255) << Attributes.RED_SHIFT | (value[1] & 255) << Attributes.GREEN_SHIFT | value[2] & 255;
+  }
+
+  public clone(): IAttributeData {
+    const newObj = new AttributeData();
+    newObj.fg = this.fg;
+    newObj.bg = this.bg;
+    return newObj;
+  }
+
+  // data
+  public fg: number = 0;
+  public bg: number = 0;
+
+  // flags
+  public isInverse(): number   { return this.fg & FgFlags.INVERSE; }
+  public isBold(): number      { return this.fg & FgFlags.BOLD; }
+  public isUnderline(): number { return this.fg & FgFlags.UNDERLINE; }
+  public isBlink(): number     { return this.fg & FgFlags.BLINK; }
+  public isInvisible(): number { return this.fg & FgFlags.INVISIBLE; }
+  public isItalic(): number    { return this.bg & BgFlags.ITALIC; }
+  public isDim(): number       { return this.bg & BgFlags.DIM; }
+
+  // color modes
+  public getFgColorMode(): number { return this.fg & Attributes.CM_MASK; }
+  public getBgColorMode(): number { return this.bg & Attributes.CM_MASK; }
+  public isFgRGB(): boolean       { return (this.fg & Attributes.CM_MASK) === Attributes.CM_RGB; }
+  public isBgRGB(): boolean       { return (this.bg & Attributes.CM_MASK) === Attributes.CM_RGB; }
+  public isFgPalette(): boolean   { return (this.fg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.fg & Attributes.CM_MASK) === Attributes.CM_P256; }
+  public isBgPalette(): boolean   { return (this.bg & Attributes.CM_MASK) === Attributes.CM_P16 || (this.bg & Attributes.CM_MASK) === Attributes.CM_P256; }
+  public isFgDefault(): boolean   { return (this.fg & Attributes.CM_MASK) === 0; }
+  public isBgDefault(): boolean   { return (this.bg & Attributes.CM_MASK) === 0; }
+
+  // colors
+  public getFgColor(): number {
+    switch (this.fg & Attributes.CM_MASK) {
+      case Attributes.CM_P16:
+      case Attributes.CM_P256:  return this.fg & Attributes.PCOLOR_MASK;
+      case Attributes.CM_RGB:   return this.fg & Attributes.RGB_MASK;
+      default:                  return -1;  // CM_DEFAULT defaults to -1
+    }
+  }
+  public getBgColor(): number {
+    switch (this.bg & Attributes.CM_MASK) {
+      case Attributes.CM_P16:
+      case Attributes.CM_P256:  return this.bg & Attributes.PCOLOR_MASK;
+      case Attributes.CM_RGB:   return this.bg & Attributes.RGB_MASK;
+      default:                  return -1;  // CM_DEFAULT defaults to -1
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/Buffer.ts b/node_modules/xterm/src/common/buffer/Buffer.ts
new file mode 100644 (file)
index 0000000..152bab7
--- /dev/null
@@ -0,0 +1,671 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { CircularList, IInsertEvent } from 'common/CircularList';
+import { IBuffer, BufferIndex, IBufferStringIterator, IBufferStringIteratorResult } from 'common/buffer/Types';
+import { IBufferLine, ICellData, IAttributeData, ICharset } from 'common/Types';
+import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
+import { CellData } from 'common/buffer/CellData';
+import { NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_CHAR_INDEX } from 'common/buffer/Constants';
+import { reflowLargerApplyNewLayout, reflowLargerCreateNewLayout, reflowLargerGetLinesToRemove, reflowSmallerGetNewLineLengths, getWrappedLineTrimmedLength } from 'common/buffer/BufferReflow';
+import { Marker } from 'common/buffer/Marker';
+import { IOptionsService, IBufferService } from 'common/services/Services';
+import { DEFAULT_CHARSET } from 'common/data/Charsets';
+
+export const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1
+
+/**
+ * This class represents a terminal buffer (an internal state of the terminal), where the
+ * following information is stored (in high-level):
+ *   - text content of this particular buffer
+ *   - cursor position
+ *   - scroll position
+ */
+export class Buffer implements IBuffer {
+  public lines: CircularList<IBufferLine>;
+  public ydisp: number = 0;
+  public ybase: number = 0;
+  public y: number = 0;
+  public x: number = 0;
+  public scrollBottom: number;
+  public scrollTop: number;
+  // TODO: Type me
+  public tabs: any;
+  public savedY: number = 0;
+  public savedX: number = 0;
+  public savedCurAttrData = DEFAULT_ATTR_DATA.clone();
+  public savedCharset: ICharset | null = DEFAULT_CHARSET;
+  public markers: Marker[] = [];
+  private _nullCell: ICellData = CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);
+  private _whitespaceCell: ICellData = CellData.fromCharData([0, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_WIDTH, WHITESPACE_CELL_CODE]);
+  private _cols: number;
+  private _rows: number;
+
+  constructor(
+    private _hasScrollback: boolean,
+    private _optionsService: IOptionsService,
+    private _bufferService: IBufferService
+  ) {
+    this._cols = this._bufferService.cols;
+    this._rows = this._bufferService.rows;
+    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));
+    this.scrollTop = 0;
+    this.scrollBottom = this._rows - 1;
+    this.setupTabStops();
+  }
+
+  public getNullCell(attr?: IAttributeData): ICellData {
+    if (attr) {
+      this._nullCell.fg = attr.fg;
+      this._nullCell.bg = attr.bg;
+    } else {
+      this._nullCell.fg = 0;
+      this._nullCell.bg = 0;
+    }
+    return this._nullCell;
+  }
+
+  public getWhitespaceCell(attr?: IAttributeData): ICellData {
+    if (attr) {
+      this._whitespaceCell.fg = attr.fg;
+      this._whitespaceCell.bg = attr.bg;
+    } else {
+      this._whitespaceCell.fg = 0;
+      this._whitespaceCell.bg = 0;
+    }
+    return this._whitespaceCell;
+  }
+
+  public getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine {
+    return new BufferLine(this._bufferService.cols, this.getNullCell(attr), isWrapped);
+  }
+
+  public get hasScrollback(): boolean {
+    return this._hasScrollback && this.lines.maxLength > this._rows;
+  }
+
+  public get isCursorInViewport(): boolean {
+    const absoluteY = this.ybase + this.y;
+    const relativeY = absoluteY - this.ydisp;
+    return (relativeY >= 0 && relativeY < this._rows);
+  }
+
+  /**
+   * Gets the correct buffer length based on the rows provided, the terminal's
+   * scrollback and whether this buffer is flagged to have scrollback or not.
+   * @param rows The terminal rows to use in the calculation.
+   */
+  private _getCorrectBufferLength(rows: number): number {
+    if (!this._hasScrollback) {
+      return rows;
+    }
+
+    const correctBufferLength = rows + this._optionsService.options.scrollback;
+
+    return correctBufferLength > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : correctBufferLength;
+  }
+
+  /**
+   * Fills the buffer's viewport with blank lines.
+   */
+  public fillViewportRows(fillAttr?: IAttributeData): void {
+    if (this.lines.length === 0) {
+      if (fillAttr === undefined) {
+        fillAttr = DEFAULT_ATTR_DATA;
+      }
+      let i = this._rows;
+      while (i--) {
+        this.lines.push(this.getBlankLine(fillAttr));
+      }
+    }
+  }
+
+  /**
+   * Clears the buffer to it's initial state, discarding all previous data.
+   */
+  public clear(): void {
+    this.ydisp = 0;
+    this.ybase = 0;
+    this.y = 0;
+    this.x = 0;
+    this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));
+    this.scrollTop = 0;
+    this.scrollBottom = this._rows - 1;
+    this.setupTabStops();
+  }
+
+  /**
+   * Resizes the buffer, adjusting its data accordingly.
+   * @param newCols The new number of columns.
+   * @param newRows The new number of rows.
+   */
+  public resize(newCols: number, newRows: number): void {
+    // store reference to null cell with default attrs
+    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
+
+    // Increase max length if needed before adjustments to allow space to fill
+    // as required.
+    const newMaxLength = this._getCorrectBufferLength(newRows);
+    if (newMaxLength > this.lines.maxLength) {
+      this.lines.maxLength = newMaxLength;
+    }
+
+    // The following adjustments should only happen if the buffer has been
+    // initialized/filled.
+    if (this.lines.length > 0) {
+      // Deal with columns increasing (reducing needs to happen after reflow)
+      if (this._cols < newCols) {
+        for (let i = 0; i < this.lines.length; i++) {
+          this.lines.get(i)!.resize(newCols, nullCell);
+        }
+      }
+
+      // Resize rows in both directions as needed
+      let addToY = 0;
+      if (this._rows < newRows) {
+        for (let y = this._rows; y < newRows; y++) {
+          if (this.lines.length < newRows + this.ybase) {
+            if (this._optionsService.options.windowsMode) {
+              // Just add the new missing rows on Windows as conpty reprints the screen with it's
+              // view of the world. Once a line enters scrollback for conpty it remains there
+              this.lines.push(new BufferLine(newCols, nullCell));
+            } else {
+              if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
+                // There is room above the buffer and there are no empty elements below the line,
+                // scroll up
+                this.ybase--;
+                addToY++;
+                if (this.ydisp > 0) {
+                  // Viewport is at the top of the buffer, must increase downwards
+                  this.ydisp--;
+                }
+              } else {
+                // Add a blank line if there is no buffer left at the top to scroll to, or if there
+                // are blank lines after the cursor
+                this.lines.push(new BufferLine(newCols, nullCell));
+              }
+            }
+          }
+        }
+      } else { // (this._rows >= newRows)
+        for (let y = this._rows; y > newRows; y--) {
+          if (this.lines.length > newRows + this.ybase) {
+            if (this.lines.length > this.ybase + this.y + 1) {
+              // The line is a blank line below the cursor, remove it
+              this.lines.pop();
+            } else {
+              // The line is the cursor, scroll down
+              this.ybase++;
+              this.ydisp++;
+            }
+          }
+        }
+      }
+
+      // Reduce max length if needed after adjustments, this is done after as it
+      // would otherwise cut data from the bottom of the buffer.
+      if (newMaxLength < this.lines.maxLength) {
+        // Trim from the top of the buffer and adjust ybase and ydisp.
+        const amountToTrim = this.lines.length - newMaxLength;
+        if (amountToTrim > 0) {
+          this.lines.trimStart(amountToTrim);
+          this.ybase = Math.max(this.ybase - amountToTrim, 0);
+          this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
+          this.savedY = Math.max(this.savedY - amountToTrim, 0);
+        }
+        this.lines.maxLength = newMaxLength;
+      }
+
+      // Make sure that the cursor stays on screen
+      this.x = Math.min(this.x, newCols - 1);
+      this.y = Math.min(this.y, newRows - 1);
+      if (addToY) {
+        this.y += addToY;
+      }
+      this.savedX = Math.min(this.savedX, newCols - 1);
+
+      this.scrollTop = 0;
+    }
+
+    this.scrollBottom = newRows - 1;
+
+    if (this._isReflowEnabled) {
+      this._reflow(newCols, newRows);
+
+      // Trim the end of the line off if cols shrunk
+      if (this._cols > newCols) {
+        for (let i = 0; i < this.lines.length; i++) {
+          this.lines.get(i)!.resize(newCols, nullCell);
+        }
+      }
+    }
+
+    this._cols = newCols;
+    this._rows = newRows;
+  }
+
+  private get _isReflowEnabled(): boolean {
+    return this._hasScrollback && !this._optionsService.options.windowsMode;
+  }
+
+  private _reflow(newCols: number, newRows: number): void {
+    if (this._cols === newCols) {
+      return;
+    }
+
+    // Iterate through rows, ignore the last one as it cannot be wrapped
+    if (newCols > this._cols) {
+      this._reflowLarger(newCols, newRows);
+    } else {
+      this._reflowSmaller(newCols, newRows);
+    }
+  }
+
+  private _reflowLarger(newCols: number, newRows: number): void {
+    const toRemove: number[] = reflowLargerGetLinesToRemove(this.lines, this._cols, newCols, this.ybase + this.y, this.getNullCell(DEFAULT_ATTR_DATA));
+    if (toRemove.length > 0) {
+      const newLayoutResult = reflowLargerCreateNewLayout(this.lines, toRemove);
+      reflowLargerApplyNewLayout(this.lines, newLayoutResult.layout);
+      this._reflowLargerAdjustViewport(newCols, newRows, newLayoutResult.countRemoved);
+    }
+  }
+
+  private _reflowLargerAdjustViewport(newCols: number, newRows: number, countRemoved: number): void {
+    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
+    // Adjust viewport based on number of items removed
+    let viewportAdjustments = countRemoved;
+    while (viewportAdjustments-- > 0) {
+      if (this.ybase === 0) {
+        if (this.y > 0) {
+          this.y--;
+        }
+        if (this.lines.length < newRows) {
+          // Add an extra row at the bottom of the viewport
+          this.lines.push(new BufferLine(newCols, nullCell));
+        }
+      } else {
+        if (this.ydisp === this.ybase) {
+          this.ydisp--;
+        }
+        this.ybase--;
+      }
+    }
+    this.savedY = Math.max(this.savedY - countRemoved, 0);
+  }
+
+  private _reflowSmaller(newCols: number, newRows: number): void {
+    const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
+    // Gather all BufferLines that need to be inserted into the Buffer here so that they can be
+    // batched up and only committed once
+    const toInsert = [];
+    let countToInsert = 0;
+    // Go backwards as many lines may be trimmed and this will avoid considering them
+    for (let y = this.lines.length - 1; y >= 0; y--) {
+      // Check whether this line is a problem
+      let nextLine = this.lines.get(y) as BufferLine;
+      if (!nextLine || !nextLine.isWrapped && nextLine.getTrimmedLength() <= newCols) {
+        continue;
+      }
+
+      // Gather wrapped lines and adjust y to be the starting line
+      const wrappedLines: BufferLine[] = [nextLine];
+      while (nextLine.isWrapped && y > 0) {
+        nextLine = this.lines.get(--y) as BufferLine;
+        wrappedLines.unshift(nextLine);
+      }
+
+      // If these lines contain the cursor don't touch them, the program will handle fixing up
+      // wrapped lines with the cursor
+      const absoluteY = this.ybase + this.y;
+      if (absoluteY >= y && absoluteY < y + wrappedLines.length) {
+        continue;
+      }
+
+      const lastLineLength = wrappedLines[wrappedLines.length - 1].getTrimmedLength();
+      const destLineLengths = reflowSmallerGetNewLineLengths(wrappedLines, this._cols, newCols);
+      const linesToAdd = destLineLengths.length - wrappedLines.length;
+      let trimmedLines: number;
+      if (this.ybase === 0 && this.y !== this.lines.length - 1) {
+        // If the top section of the buffer is not yet filled
+        trimmedLines = Math.max(0, this.y - this.lines.maxLength + linesToAdd);
+      } else {
+        trimmedLines = Math.max(0, this.lines.length - this.lines.maxLength + linesToAdd);
+      }
+
+      // Add the new lines
+      const newLines: BufferLine[] = [];
+      for (let i = 0; i < linesToAdd; i++) {
+        const newLine = this.getBlankLine(DEFAULT_ATTR_DATA, true) as BufferLine;
+        newLines.push(newLine);
+      }
+      if (newLines.length > 0) {
+        toInsert.push({
+          // countToInsert here gets the actual index, taking into account other inserted items.
+          // using this we can iterate through the list forwards
+          start: y + wrappedLines.length + countToInsert,
+          newLines
+        });
+        countToInsert += newLines.length;
+      }
+      wrappedLines.push(...newLines);
+
+      // Copy buffer data to new locations, this needs to happen backwards to do in-place
+      let destLineIndex = destLineLengths.length - 1; // Math.floor(cellsNeeded / newCols);
+      let destCol = destLineLengths[destLineIndex]; // cellsNeeded % newCols;
+      if (destCol === 0) {
+        destLineIndex--;
+        destCol = destLineLengths[destLineIndex];
+      }
+      let srcLineIndex = wrappedLines.length - linesToAdd - 1;
+      let srcCol = lastLineLength;
+      while (srcLineIndex >= 0) {
+        const cellsToCopy = Math.min(srcCol, destCol);
+        wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);
+        destCol -= cellsToCopy;
+        if (destCol === 0) {
+          destLineIndex--;
+          destCol = destLineLengths[destLineIndex];
+        }
+        srcCol -= cellsToCopy;
+        if (srcCol === 0) {
+          srcLineIndex--;
+          const wrappedLinesIndex = Math.max(srcLineIndex, 0);
+          srcCol = getWrappedLineTrimmedLength(wrappedLines, wrappedLinesIndex, this._cols);
+        }
+      }
+
+      // Null out the end of the line ends if a wide character wrapped to the following line
+      for (let i = 0; i < wrappedLines.length; i++) {
+        if (destLineLengths[i] < newCols) {
+          wrappedLines[i].setCell(destLineLengths[i], nullCell);
+        }
+      }
+
+      // Adjust viewport as needed
+      let viewportAdjustments = linesToAdd - trimmedLines;
+      while (viewportAdjustments-- > 0) {
+        if (this.ybase === 0) {
+          if (this.y < newRows - 1) {
+            this.y++;
+            this.lines.pop();
+          } else {
+            this.ybase++;
+            this.ydisp++;
+          }
+        } else {
+          // Ensure ybase does not exceed its maximum value
+          if (this.ybase < Math.min(this.lines.maxLength, this.lines.length + countToInsert) - newRows) {
+            if (this.ybase === this.ydisp) {
+              this.ydisp++;
+            }
+            this.ybase++;
+          }
+        }
+      }
+      this.savedY = Math.min(this.savedY + linesToAdd, this.ybase + newRows - 1);
+    }
+
+    // Rearrange lines in the buffer if there are any insertions, this is done at the end rather
+    // than earlier so that it's a single O(n) pass through the buffer, instead of O(n^2) from many
+    // costly calls to CircularList.splice.
+    if (toInsert.length > 0) {
+      // Record buffer insert events and then play them back backwards so that the indexes are
+      // correct
+      const insertEvents: IInsertEvent[] = [];
+
+      // Record original lines so they don't get overridden when we rearrange the list
+      const originalLines: BufferLine[] = [];
+      for (let i = 0; i < this.lines.length; i++) {
+        originalLines.push(this.lines.get(i) as BufferLine);
+      }
+      const originalLinesLength = this.lines.length;
+
+      let originalLineIndex = originalLinesLength - 1;
+      let nextToInsertIndex = 0;
+      let nextToInsert = toInsert[nextToInsertIndex];
+      this.lines.length = Math.min(this.lines.maxLength, this.lines.length + countToInsert);
+      let countInsertedSoFar = 0;
+      for (let i = Math.min(this.lines.maxLength - 1, originalLinesLength + countToInsert - 1); i >= 0; i--) {
+        if (nextToInsert && nextToInsert.start > originalLineIndex + countInsertedSoFar) {
+          // Insert extra lines here, adjusting i as needed
+          for (let nextI = nextToInsert.newLines.length - 1; nextI >= 0; nextI--) {
+            this.lines.set(i--, nextToInsert.newLines[nextI]);
+          }
+          i++;
+
+          // Create insert events for later
+          insertEvents.push({
+            index: originalLineIndex + 1,
+            amount: nextToInsert.newLines.length
+          });
+
+          countInsertedSoFar += nextToInsert.newLines.length;
+          nextToInsert = toInsert[++nextToInsertIndex];
+        } else {
+          this.lines.set(i, originalLines[originalLineIndex--]);
+        }
+      }
+
+      // Update markers
+      let insertCountEmitted = 0;
+      for (let i = insertEvents.length - 1; i >= 0; i--) {
+        insertEvents[i].index += insertCountEmitted;
+        this.lines.onInsertEmitter.fire(insertEvents[i]);
+        insertCountEmitted += insertEvents[i].amount;
+      }
+      const amountToTrim = Math.max(0, originalLinesLength + countToInsert - this.lines.maxLength);
+      if (amountToTrim > 0) {
+        this.lines.onTrimEmitter.fire(amountToTrim);
+      }
+    }
+  }
+
+  // private _reflowSmallerGetLinesNeeded()
+
+  /**
+   * Translates a string index back to a BufferIndex.
+   * To get the correct buffer position the string must start at `startCol` 0
+   * (default in translateBufferLineToString).
+   * The method also works on wrapped line strings given rows were not trimmed.
+   * The method operates on the CharData string length, there are no
+   * additional content or boundary checks. Therefore the string and the buffer
+   * should not be altered in between.
+   * TODO: respect trim flag after fixing #1685
+   * @param lineIndex line index the string was retrieved from
+   * @param stringIndex index within the string
+   * @param startCol column offset the string was retrieved from
+   */
+  public stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight: boolean = false): BufferIndex {
+    while (stringIndex) {
+      const line = this.lines.get(lineIndex);
+      if (!line) {
+        return [-1, -1];
+      }
+      const length = (trimRight) ? line.getTrimmedLength() : line.length;
+      for (let i = 0; i < length; ++i) {
+        if (line.get(i)[CHAR_DATA_WIDTH_INDEX]) {
+          // empty cells report a string length of 0, but get replaced
+          // with a whitespace in translateToString, thus replace with 1
+          stringIndex -= line.get(i)[CHAR_DATA_CHAR_INDEX].length || 1;
+        }
+        if (stringIndex < 0) {
+          return [lineIndex, i];
+        }
+      }
+      lineIndex++;
+    }
+    return [lineIndex, 0];
+  }
+
+  /**
+   * Translates a buffer line to a string, with optional start and end columns.
+   * Wide characters will count as two columns in the resulting string. This
+   * function is useful for getting the actual text underneath the raw selection
+   * position.
+   * @param line The line being translated.
+   * @param trimRight Whether to trim whitespace to the right.
+   * @param startCol The column to start at.
+   * @param endCol The column to end at.
+   */
+  public translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol: number = 0, endCol?: number): string {
+    const line = this.lines.get(lineIndex);
+    if (!line) {
+      return '';
+    }
+    return line.translateToString(trimRight, startCol, endCol);
+  }
+
+  public getWrappedRangeForLine(y: number): { first: number, last: number } {
+    let first = y;
+    let last = y;
+    // Scan upwards for wrapped lines
+    while (first > 0 && this.lines.get(first)!.isWrapped) {
+      first--;
+    }
+    // Scan downwards for wrapped lines
+    while (last + 1 < this.lines.length && this.lines.get(last + 1)!.isWrapped) {
+      last++;
+    }
+    return { first, last };
+  }
+
+  /**
+   * Setup the tab stops.
+   * @param i The index to start setting up tab stops from.
+   */
+  public setupTabStops(i?: number): void {
+    if (i !== null && i !== undefined) {
+      if (!this.tabs[i]) {
+        i = this.prevStop(i);
+      }
+    } else {
+      this.tabs = {};
+      i = 0;
+    }
+
+    for (; i < this._cols; i += this._optionsService.options.tabStopWidth) {
+      this.tabs[i] = true;
+    }
+  }
+
+  /**
+   * Move the cursor to the previous tab stop from the given position (default is current).
+   * @param x The position to move the cursor to the previous tab stop.
+   */
+  public prevStop(x?: number): number {
+    if (x === null || x === undefined) {
+      x = this.x;
+    }
+    while (!this.tabs[--x] && x > 0);
+    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;
+  }
+
+  /**
+   * Move the cursor one tab stop forward from the given position (default is current).
+   * @param x The position to move the cursor one tab stop forward.
+   */
+  public nextStop(x?: number): number {
+    if (x === null || x === undefined) {
+      x = this.x;
+    }
+    while (!this.tabs[++x] && x < this._cols);
+    return x >= this._cols ? this._cols - 1 : x < 0 ? 0 : x;
+  }
+
+  public addMarker(y: number): Marker {
+    const marker = new Marker(y);
+    this.markers.push(marker);
+    marker.register(this.lines.onTrim(amount => {
+      marker.line -= amount;
+      // The marker should be disposed when the line is trimmed from the buffer
+      if (marker.line < 0) {
+        marker.dispose();
+      }
+    }));
+    marker.register(this.lines.onInsert(event => {
+      if (marker.line >= event.index) {
+        marker.line += event.amount;
+      }
+    }));
+    marker.register(this.lines.onDelete(event => {
+      // Delete the marker if it's within the range
+      if (marker.line >= event.index && marker.line < event.index + event.amount) {
+        marker.dispose();
+      }
+
+      // Shift the marker if it's after the deleted range
+      if (marker.line > event.index) {
+        marker.line -= event.amount;
+      }
+    }));
+    marker.register(marker.onDispose(() => this._removeMarker(marker)));
+    return marker;
+  }
+
+  private _removeMarker(marker: Marker): void {
+    this.markers.splice(this.markers.indexOf(marker), 1);
+  }
+
+  public iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator {
+    return new BufferStringIterator(this, trimRight, startIndex, endIndex, startOverscan, endOverscan);
+  }
+}
+
+/**
+ * Iterator to get unwrapped content strings from the buffer.
+ * The iterator returns at least the string data between the borders
+ * `startIndex` and `endIndex` (exclusive) and will expand the lines
+ * by `startOverscan` to the top and by `endOverscan` to the bottom,
+ * if no new line was found in between.
+ * It will never read/return string data beyond `startIndex - startOverscan`
+ * or `endIndex + endOverscan`. Therefore the first and last line might be truncated.
+ * It is possible to always get the full string for the first and last line as well
+ * by setting the overscan values to the actual buffer length. This not recommended
+ * since it might return the whole buffer within a single string in a worst case scenario.
+ */
+export class BufferStringIterator implements IBufferStringIterator {
+  private _current: number;
+
+  constructor (
+    private _buffer: IBuffer,
+    private _trimRight: boolean,
+    private _startIndex: number = 0,
+    private _endIndex: number = _buffer.lines.length,
+    private _startOverscan: number = 0,
+    private _endOverscan: number = 0
+  ) {
+    if (this._startIndex < 0) {
+      this._startIndex = 0;
+    }
+    if (this._endIndex > this._buffer.lines.length) {
+      this._endIndex = this._buffer.lines.length;
+    }
+    this._current = this._startIndex;
+  }
+
+  public hasNext(): boolean {
+    return this._current < this._endIndex;
+  }
+
+  public next(): IBufferStringIteratorResult {
+    const range = this._buffer.getWrappedRangeForLine(this._current);
+    // limit search window to overscan value at both borders
+    if (range.first < this._startIndex - this._startOverscan) {
+      range.first = this._startIndex - this._startOverscan;
+    }
+    if (range.last > this._endIndex + this._endOverscan) {
+      range.last = this._endIndex + this._endOverscan;
+    }
+    // limit to current buffer length
+    range.first = Math.max(range.first, 0);
+    range.last = Math.min(range.last, this._buffer.lines.length);
+    let result = '';
+    for (let i = range.first; i <= range.last; ++i) {
+      result += this._buffer.translateBufferLineToString(i, this._trimRight);
+    }
+    this._current = range.last + 1;
+    return {range: range, content: result};
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/BufferLine.ts b/node_modules/xterm/src/common/buffer/BufferLine.ts
new file mode 100644 (file)
index 0000000..1e95e00
--- /dev/null
@@ -0,0 +1,393 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { CharData, IBufferLine, ICellData } from 'common/Types';
+import { stringFromCodePoint } from 'common/input/TextDecoder';
+import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE, WHITESPACE_CELL_CHAR, Content } from 'common/buffer/Constants';
+import { CellData } from 'common/buffer/CellData';
+import { AttributeData } from 'common/buffer/AttributeData';
+
+/**
+ * buffer memory layout:
+ *
+ *   |             uint32_t             |        uint32_t         |        uint32_t         |
+ *   |             `content`            |          `FG`           |          `BG`           |
+ *   | wcwidth(2) comb(1) codepoint(21) | flags(8) R(8) G(8) B(8) | flags(8) R(8) G(8) B(8) |
+ */
+
+
+/** typed array slots taken by one cell */
+const CELL_SIZE = 3;
+
+/**
+ * Cell member indices.
+ *
+ * Direct access:
+ *    `content = data[column * CELL_SIZE + Cell.CONTENT];`
+ *    `fg = data[column * CELL_SIZE + Cell.FG];`
+ *    `bg = data[column * CELL_SIZE + Cell.BG];`
+ */
+const enum Cell {
+  CONTENT = 0,
+  FG = 1, // currently simply holds all known attrs
+  BG = 2  // currently unused
+}
+
+export const DEFAULT_ATTR_DATA = Object.freeze(new AttributeData());
+
+/**
+ * Typed array based bufferline implementation.
+ *
+ * There are 2 ways to insert data into the cell buffer:
+ * - `setCellFromCodepoint` + `addCodepointToCell`
+ *   Use these for data that is already UTF32.
+ *   Used during normal input in `InputHandler` for faster buffer access.
+ * - `setCell`
+ *   This method takes a CellData object and stores the data in the buffer.
+ *   Use `CellData.fromCharData` to create the CellData object (e.g. from JS string).
+ *
+ * To retrieve data from the buffer use either one of the primitive methods
+ * (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop
+ * memory allocs / GC pressure can be greatly reduced by reusing the CellData object.
+ */
+export class BufferLine implements IBufferLine {
+  protected _data: Uint32Array;
+  protected _combined: {[index: number]: string} = {};
+  public length: number;
+
+  constructor(cols: number, fillCellData?: ICellData, public isWrapped: boolean = false) {
+    this._data = new Uint32Array(cols * CELL_SIZE);
+    const cell = fillCellData || CellData.fromCharData([0, NULL_CELL_CHAR, NULL_CELL_WIDTH, NULL_CELL_CODE]);
+    for (let i = 0; i < cols; ++i) {
+      this.setCell(i, cell);
+    }
+    this.length = cols;
+  }
+
+  /**
+   * Get cell data CharData.
+   * @deprecated
+   */
+  public get(index: number): CharData {
+    const content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    const cp = content & Content.CODEPOINT_MASK;
+    return [
+      this._data[index * CELL_SIZE + Cell.FG],
+      (content & Content.IS_COMBINED_MASK)
+        ? this._combined[index]
+        : (cp) ? stringFromCodePoint(cp) : '',
+      content >> Content.WIDTH_SHIFT,
+      (content & Content.IS_COMBINED_MASK)
+        ? this._combined[index].charCodeAt(this._combined[index].length - 1)
+        : cp
+    ];
+  }
+
+  /**
+   * Set cell data from CharData.
+   * @deprecated
+   */
+  public set(index: number, value: CharData): void {
+    this._data[index * CELL_SIZE + Cell.FG] = value[CHAR_DATA_ATTR_INDEX];
+    if (value[CHAR_DATA_CHAR_INDEX].length > 1) {
+      this._combined[index] = value[1];
+      this._data[index * CELL_SIZE + Cell.CONTENT] = index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    } else {
+      this._data[index * CELL_SIZE + Cell.CONTENT] = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    }
+  }
+
+  /**
+   * primitive getters
+   * use these when only one value is needed, otherwise use `loadCell`
+   */
+  public getWidth(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT;
+  }
+
+  /** Test whether content has width. */
+  public hasWidth(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.WIDTH_MASK;
+  }
+
+  /** Get FG cell component. */
+  public getFg(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.FG];
+  }
+
+  /** Get BG cell component. */
+  public getBg(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.BG];
+  }
+
+  /**
+   * Test whether contains any chars.
+   * Basically an empty has no content, but other cells might differ in FG/BG
+   * from real empty cells.
+   * */
+  public hasContent(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK;
+  }
+
+  /**
+   * Get codepoint of the cell.
+   * To be in line with `code` in CharData this either returns
+   * a single UTF32 codepoint or the last codepoint of a combined string.
+   */
+  public getCodePoint(index: number): number {
+    const content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    if (content & Content.IS_COMBINED_MASK) {
+      return this._combined[index].charCodeAt(this._combined[index].length - 1);
+    }
+    return content & Content.CODEPOINT_MASK;
+  }
+
+  /** Test whether the cell contains a combined string. */
+  public isCombined(index: number): number {
+    return this._data[index * CELL_SIZE + Cell.CONTENT] & Content.IS_COMBINED_MASK;
+  }
+
+  /** Returns the string content of the cell. */
+  public getString(index: number): string {
+    const content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    if (content & Content.IS_COMBINED_MASK) {
+      return this._combined[index];
+    }
+    if (content & Content.CODEPOINT_MASK) {
+      return stringFromCodePoint(content & Content.CODEPOINT_MASK);
+    }
+    // return empty string for empty cells
+    return '';
+  }
+
+  /**
+   * Load data at `index` into `cell`. This is used to access cells in a way that's more friendly
+   * to GC as it significantly reduced the amount of new objects/references needed.
+   */
+  public loadCell(index: number, cell: ICellData): ICellData {
+    const startIndex = index * CELL_SIZE;
+    cell.content = this._data[startIndex + Cell.CONTENT];
+    cell.fg = this._data[startIndex + Cell.FG];
+    cell.bg = this._data[startIndex + Cell.BG];
+    if (cell.content & Content.IS_COMBINED_MASK) {
+      cell.combinedData = this._combined[index];
+    }
+    return cell;
+  }
+
+  /**
+   * Set data at `index` to `cell`.
+   */
+  public setCell(index: number, cell: ICellData): void {
+    if (cell.content & Content.IS_COMBINED_MASK) {
+      this._combined[index] = cell.combinedData;
+    }
+    this._data[index * CELL_SIZE + Cell.CONTENT] = cell.content;
+    this._data[index * CELL_SIZE + Cell.FG] = cell.fg;
+    this._data[index * CELL_SIZE + Cell.BG] = cell.bg;
+  }
+
+  /**
+   * Set cell data from input handler.
+   * Since the input handler see the incoming chars as UTF32 codepoints,
+   * it gets an optimized access method.
+   */
+  public setCellFromCodePoint(index: number, codePoint: number, width: number, fg: number, bg: number): void {
+    this._data[index * CELL_SIZE + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);
+    this._data[index * CELL_SIZE + Cell.FG] = fg;
+    this._data[index * CELL_SIZE + Cell.BG] = bg;
+  }
+
+  /**
+   * Add a codepoint to a cell from input handler.
+   * During input stage combining chars with a width of 0 follow and stack
+   * onto a leading char. Since we already set the attrs
+   * by the previous `setDataFromCodePoint` call, we can omit it here.
+   */
+  public addCodepointToCell(index: number, codePoint: number): void {
+    let content = this._data[index * CELL_SIZE + Cell.CONTENT];
+    if (content & Content.IS_COMBINED_MASK) {
+      // we already have a combined string, simply add
+      this._combined[index] += stringFromCodePoint(codePoint);
+    } else {
+      if (content & Content.CODEPOINT_MASK) {
+        // normal case for combining chars:
+        //  - move current leading char + new one into combined string
+        //  - set combined flag
+        this._combined[index] = stringFromCodePoint(content & Content.CODEPOINT_MASK) + stringFromCodePoint(codePoint);
+        content &= ~Content.CODEPOINT_MASK; // set codepoint in buffer to 0
+        content |= Content.IS_COMBINED_MASK;
+      } else {
+        // should not happen - we actually have no data in the cell yet
+        // simply set the data in the cell buffer with a width of 1
+        content = codePoint | (1 << Content.WIDTH_SHIFT);
+      }
+      this._data[index * CELL_SIZE + Cell.CONTENT] = content;
+    }
+  }
+
+  public insertCells(pos: number, n: number, fillCellData: ICellData): void {
+    pos %= this.length;
+    if (n < this.length - pos) {
+      const cell = new CellData();
+      for (let i = this.length - pos - n - 1; i >= 0; --i) {
+        this.setCell(pos + n + i, this.loadCell(pos + i, cell));
+      }
+      for (let i = 0; i < n; ++i) {
+        this.setCell(pos + i, fillCellData);
+      }
+    } else {
+      for (let i = pos; i < this.length; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    }
+  }
+
+  public deleteCells(pos: number, n: number, fillCellData: ICellData): void {
+    pos %= this.length;
+    if (n < this.length - pos) {
+      const cell = new CellData();
+      for (let i = 0; i < this.length - pos - n; ++i) {
+        this.setCell(pos + i, this.loadCell(pos + n + i, cell));
+      }
+      for (let i = this.length - n; i < this.length; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    } else {
+      for (let i = pos; i < this.length; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    }
+  }
+
+  public replaceCells(start: number, end: number, fillCellData: ICellData): void {
+    while (start < end  && start < this.length) {
+      this.setCell(start++, fillCellData);
+    }
+  }
+
+  public resize(cols: number, fillCellData: ICellData): void {
+    if (cols === this.length) {
+      return;
+    }
+    if (cols > this.length) {
+      const data = new Uint32Array(cols * CELL_SIZE);
+      if (this.length) {
+        if (cols * CELL_SIZE < this._data.length) {
+          data.set(this._data.subarray(0, cols * CELL_SIZE));
+        } else {
+          data.set(this._data);
+        }
+      }
+      this._data = data;
+      for (let i = this.length; i < cols; ++i) {
+        this.setCell(i, fillCellData);
+      }
+    } else {
+      if (cols) {
+        const data = new Uint32Array(cols * CELL_SIZE);
+        data.set(this._data.subarray(0, cols * CELL_SIZE));
+        this._data = data;
+        // Remove any cut off combined data
+        const keys = Object.keys(this._combined);
+        for (let i = 0; i < keys.length; i++) {
+          const key = parseInt(keys[i], 10);
+          if (key >= cols) {
+            delete this._combined[key];
+          }
+        }
+      } else {
+        this._data = new Uint32Array(0);
+        this._combined = {};
+      }
+    }
+    this.length = cols;
+  }
+
+  /** fill a line with fillCharData */
+  public fill(fillCellData: ICellData): void {
+    this._combined = {};
+    for (let i = 0; i < this.length; ++i) {
+      this.setCell(i, fillCellData);
+    }
+  }
+
+  /** alter to a full copy of line  */
+  public copyFrom(line: BufferLine): void {
+    if (this.length !== line.length) {
+      this._data = new Uint32Array(line._data);
+    } else {
+      // use high speed copy if lengths are equal
+      this._data.set(line._data);
+    }
+    this.length = line.length;
+    this._combined = {};
+    for (const el in line._combined) {
+      this._combined[el] = line._combined[el];
+    }
+    this.isWrapped = line.isWrapped;
+  }
+
+  /** create a new clone */
+  public clone(): IBufferLine {
+    const newLine = new BufferLine(0);
+    newLine._data = new Uint32Array(this._data);
+    newLine.length = this.length;
+    for (const el in this._combined) {
+      newLine._combined[el] = this._combined[el];
+    }
+    newLine.isWrapped = this.isWrapped;
+    return newLine;
+  }
+
+  public getTrimmedLength(): number {
+    for (let i = this.length - 1; i >= 0; --i) {
+      if ((this._data[i * CELL_SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK)) {
+        return i + (this._data[i * CELL_SIZE + Cell.CONTENT] >> Content.WIDTH_SHIFT);
+      }
+    }
+    return 0;
+  }
+
+  public copyCellsFrom(src: BufferLine, srcCol: number, destCol: number, length: number, applyInReverse: boolean): void {
+    const srcData = src._data;
+    if (applyInReverse) {
+      for (let cell = length - 1; cell >= 0; cell--) {
+        for (let i = 0; i < CELL_SIZE; i++) {
+          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];
+        }
+      }
+    } else {
+      for (let cell = 0; cell < length; cell++) {
+        for (let i = 0; i < CELL_SIZE; i++) {
+          this._data[(destCol + cell) * CELL_SIZE + i] = srcData[(srcCol + cell) * CELL_SIZE + i];
+        }
+      }
+    }
+
+    // Move any combined data over as needed
+    const srcCombinedKeys = Object.keys(src._combined);
+    for (let i = 0; i < srcCombinedKeys.length; i++) {
+      const key = parseInt(srcCombinedKeys[i], 10);
+      if (key >= srcCol) {
+        this._combined[key - srcCol + destCol] = src._combined[key];
+      }
+    }
+  }
+
+  public translateToString(trimRight: boolean = false, startCol: number = 0, endCol: number = this.length): string {
+    if (trimRight) {
+      endCol = Math.min(endCol, this.getTrimmedLength());
+    }
+    let result = '';
+    while (startCol < endCol) {
+      const content = this._data[startCol * CELL_SIZE + Cell.CONTENT];
+      const cp = content & Content.CODEPOINT_MASK;
+      result += (content & Content.IS_COMBINED_MASK) ? this._combined[startCol] : (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;
+      startCol += (content >> Content.WIDTH_SHIFT) || 1; // always advance by 1
+    }
+    return result;
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/BufferReflow.ts b/node_modules/xterm/src/common/buffer/BufferReflow.ts
new file mode 100644 (file)
index 0000000..ece9a96
--- /dev/null
@@ -0,0 +1,220 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { BufferLine } from 'common/buffer/BufferLine';
+import { CircularList } from 'common/CircularList';
+import { IBufferLine, ICellData } from 'common/Types';
+
+export interface INewLayoutResult {
+  layout: number[];
+  countRemoved: number;
+}
+
+/**
+ * Evaluates and returns indexes to be removed after a reflow larger occurs. Lines will be removed
+ * when a wrapped line unwraps.
+ * @param lines The buffer lines.
+ * @param newCols The columns after resize.
+ */
+export function reflowLargerGetLinesToRemove(lines: CircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData): number[] {
+  // Gather all BufferLines that need to be removed from the Buffer here so that they can be
+  // batched up and only committed once
+  const toRemove: number[] = [];
+
+  for (let y = 0; y < lines.length - 1; y++) {
+    // Check if this row is wrapped
+    let i = y;
+    let nextLine = lines.get(++i) as BufferLine;
+    if (!nextLine.isWrapped) {
+      continue;
+    }
+
+    // Check how many lines it's wrapped for
+    const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];
+    while (i < lines.length && nextLine.isWrapped) {
+      wrappedLines.push(nextLine);
+      nextLine = lines.get(++i) as BufferLine;
+    }
+
+    // If these lines contain the cursor don't touch them, the program will handle fixing up wrapped
+    // lines with the cursor
+    if (bufferAbsoluteY >= y && bufferAbsoluteY < i) {
+      y += wrappedLines.length - 1;
+      continue;
+    }
+
+    // Copy buffer data to new locations
+    let destLineIndex = 0;
+    let destCol = getWrappedLineTrimmedLength(wrappedLines, destLineIndex, oldCols);
+    let srcLineIndex = 1;
+    let srcCol = 0;
+    while (srcLineIndex < wrappedLines.length) {
+      const srcTrimmedTineLength = getWrappedLineTrimmedLength(wrappedLines, srcLineIndex, oldCols);
+      const srcRemainingCells = srcTrimmedTineLength - srcCol;
+      const destRemainingCells = newCols - destCol;
+      const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);
+
+      wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);
+
+      destCol += cellsToCopy;
+      if (destCol === newCols) {
+        destLineIndex++;
+        destCol = 0;
+      }
+      srcCol += cellsToCopy;
+      if (srcCol === srcTrimmedTineLength) {
+        srcLineIndex++;
+        srcCol = 0;
+      }
+
+      // Make sure the last cell isn't wide, if it is copy it to the current dest
+      if (destCol === 0 && destLineIndex !== 0) {
+        if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {
+          wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);
+          // Null out the end of the last row
+          wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);
+        }
+      }
+    }
+
+    // Clear out remaining cells or fragments could remain;
+    wrappedLines[destLineIndex].replaceCells(destCol, newCols, nullCell);
+
+    // Work backwards and remove any rows at the end that only contain null cells
+    let countToRemove = 0;
+    for (let i = wrappedLines.length - 1; i > 0; i--) {
+      if (i > destLineIndex || wrappedLines[i].getTrimmedLength() === 0) {
+        countToRemove++;
+      } else {
+        break;
+      }
+    }
+
+    if (countToRemove > 0) {
+      toRemove.push(y + wrappedLines.length - countToRemove); // index
+      toRemove.push(countToRemove);
+    }
+
+    y += wrappedLines.length - 1;
+  }
+  return toRemove;
+}
+
+/**
+ * Creates and return the new layout for lines given an array of indexes to be removed.
+ * @param lines The buffer lines.
+ * @param toRemove The indexes to remove.
+ */
+export function reflowLargerCreateNewLayout(lines: CircularList<IBufferLine>, toRemove: number[]): INewLayoutResult {
+  const layout: number[] = [];
+  // First iterate through the list and get the actual indexes to use for rows
+  let nextToRemoveIndex = 0;
+  let nextToRemoveStart = toRemove[nextToRemoveIndex];
+  let countRemovedSoFar = 0;
+  for (let i = 0; i < lines.length; i++) {
+    if (nextToRemoveStart === i) {
+      const countToRemove = toRemove[++nextToRemoveIndex];
+
+      // Tell markers that there was a deletion
+      lines.onDeleteEmitter.fire({
+        index: i - countRemovedSoFar,
+        amount: countToRemove
+      });
+
+      i += countToRemove - 1;
+      countRemovedSoFar += countToRemove;
+      nextToRemoveStart = toRemove[++nextToRemoveIndex];
+    } else {
+      layout.push(i);
+    }
+  }
+  return {
+    layout,
+    countRemoved: countRemovedSoFar
+  };
+}
+
+/**
+ * Applies a new layout to the buffer. This essentially does the same as many splice calls but it's
+ * done all at once in a single iteration through the list since splice is very expensive.
+ * @param lines The buffer lines.
+ * @param newLayout The new layout to apply.
+ */
+export function reflowLargerApplyNewLayout(lines: CircularList<IBufferLine>, newLayout: number[]): void {
+  // Record original lines so they don't get overridden when we rearrange the list
+  const newLayoutLines: BufferLine[] = [];
+  for (let i = 0; i < newLayout.length; i++) {
+    newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);
+  }
+
+  // Rearrange the list
+  for (let i = 0; i < newLayoutLines.length; i++) {
+    lines.set(i, newLayoutLines[i]);
+  }
+  lines.length = newLayout.length;
+}
+
+/**
+ * Gets the new line lengths for a given wrapped line. The purpose of this function it to pre-
+ * compute the wrapping points since wide characters may need to be wrapped onto the following line.
+ * This function will return an array of numbers of where each line wraps to, the resulting array
+ * will only contain the values `newCols` (when the line does not end with a wide character) and
+ * `newCols - 1` (when the line does end with a wide character), except for the last value which
+ * will contain the remaining items to fill the line.
+ *
+ * Calling this with a `newCols` value of `1` will lock up.
+ *
+ * @param wrappedLines The wrapped lines to evaluate.
+ * @param oldCols The columns before resize.
+ * @param newCols The columns after resize.
+ */
+export function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {
+  const newLineLengths: number[] = [];
+  const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);
+
+  // Use srcCol and srcLine to find the new wrapping point, use that to get the cellsAvailable and
+  // linesNeeded
+  let srcCol = 0;
+  let srcLine = 0;
+  let cellsAvailable = 0;
+  while (cellsAvailable < cellsNeeded) {
+    if (cellsNeeded - cellsAvailable < newCols) {
+      // Add the final line and exit the loop
+      newLineLengths.push(cellsNeeded - cellsAvailable);
+      break;
+    }
+    srcCol += newCols;
+    const oldTrimmedLength = getWrappedLineTrimmedLength(wrappedLines, srcLine, oldCols);
+    if (srcCol > oldTrimmedLength) {
+      srcCol -= oldTrimmedLength;
+      srcLine++;
+    }
+    const endsWithWide = wrappedLines[srcLine].getWidth(srcCol - 1) === 2;
+    if (endsWithWide) {
+      srcCol--;
+    }
+    const lineLength = endsWithWide ? newCols - 1 : newCols;
+    newLineLengths.push(lineLength);
+    cellsAvailable += lineLength;
+  }
+
+  return newLineLengths;
+}
+
+export function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {
+  // If this is the last row in the wrapped line, get the actual trimmed length
+  if (i === lines.length - 1) {
+    return lines[i].getTrimmedLength();
+  }
+  // Detect whether the following line starts with a wide character and the end of the current line
+  // is null, if so then we can be pretty sure the null character should be excluded from the line
+  // length]
+  const endsInNull = !(lines[i].hasContent(cols - 1)) && lines[i].getWidth(cols - 1) === 1;
+  const followingLineStartsWithWide = lines[i + 1].getWidth(0) === 2;
+  if (endsInNull && followingLineStartsWithWide) {
+    return cols - 1;
+  }
+  return cols;
+}
diff --git a/node_modules/xterm/src/common/buffer/BufferSet.ts b/node_modules/xterm/src/common/buffer/BufferSet.ts
new file mode 100644 (file)
index 0000000..50e6e50
--- /dev/null
@@ -0,0 +1,122 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBuffer, IBufferSet } from 'common/buffer/Types';
+import { IAttributeData } from 'common/Types';
+import { Buffer } from 'common/buffer/Buffer';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { IOptionsService, IBufferService } from 'common/services/Services';
+
+/**
+ * The BufferSet represents the set of two buffers used by xterm terminals (normal and alt) and
+ * provides also utilities for working with them.
+ */
+export class BufferSet implements IBufferSet {
+  private _normal: Buffer;
+  private _alt: Buffer;
+  private _activeBuffer: Buffer;
+
+
+  private _onBufferActivate = new EventEmitter<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}>();
+  public get onBufferActivate(): IEvent<{activeBuffer: IBuffer, inactiveBuffer: IBuffer}> { return this._onBufferActivate.event; }
+
+  /**
+   * Create a new BufferSet for the given terminal.
+   * @param _terminal - The terminal the BufferSet will belong to
+   */
+  constructor(
+    readonly optionsService: IOptionsService,
+    readonly bufferService: IBufferService
+  ) {
+    this._normal = new Buffer(true, optionsService, bufferService);
+    this._normal.fillViewportRows();
+
+    // The alt buffer should never have scrollback.
+    // See http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-The-Alternate-Screen-Buffer
+    this._alt = new Buffer(false, optionsService, bufferService);
+    this._activeBuffer = this._normal;
+
+    this.setupTabStops();
+  }
+
+  /**
+   * Returns the alt Buffer of the BufferSet
+   */
+  public get alt(): Buffer {
+    return this._alt;
+  }
+
+  /**
+   * Returns the normal Buffer of the BufferSet
+   */
+  public get active(): Buffer {
+    return this._activeBuffer;
+  }
+
+  /**
+   * Returns the currently active Buffer of the BufferSet
+   */
+  public get normal(): Buffer {
+    return this._normal;
+  }
+
+  /**
+   * Sets the normal Buffer of the BufferSet as its currently active Buffer
+   */
+  public activateNormalBuffer(): void {
+    if (this._activeBuffer === this._normal) {
+      return;
+    }
+    this._normal.x = this._alt.x;
+    this._normal.y = this._alt.y;
+    // The alt buffer should always be cleared when we switch to the normal
+    // buffer. This frees up memory since the alt buffer should always be new
+    // when activated.
+    this._alt.clear();
+    this._activeBuffer = this._normal;
+    this._onBufferActivate.fire({
+      activeBuffer: this._normal,
+      inactiveBuffer: this._alt
+    });
+  }
+
+  /**
+   * Sets the alt Buffer of the BufferSet as its currently active Buffer
+   */
+  public activateAltBuffer(fillAttr?: IAttributeData): void {
+    if (this._activeBuffer === this._alt) {
+      return;
+    }
+    // Since the alt buffer is always cleared when the normal buffer is
+    // activated, we want to fill it when switching to it.
+    this._alt.fillViewportRows(fillAttr);
+    this._alt.x = this._normal.x;
+    this._alt.y = this._normal.y;
+    this._activeBuffer = this._alt;
+    this._onBufferActivate.fire({
+      activeBuffer: this._alt,
+      inactiveBuffer: this._normal
+    });
+  }
+
+  /**
+   * Resizes both normal and alt buffers, adjusting their data accordingly.
+   * @param newCols The new number of columns.
+   * @param newRows The new number of rows.
+   */
+  public resize(newCols: number, newRows: number): void {
+    this._normal.resize(newCols, newRows);
+    this._alt.resize(newCols, newRows);
+  }
+
+  /**
+   * Setup the tab stops.
+   * @param i The index to start setting up tab stops from.
+   */
+  public setupTabStops(i?: number): void {
+    this._normal.setupTabStops(i);
+    this._alt.setupTabStops(i);
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/CellData.ts b/node_modules/xterm/src/common/buffer/CellData.ts
new file mode 100644 (file)
index 0000000..21ad2ee
--- /dev/null
@@ -0,0 +1,93 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { CharData, ICellData } from 'common/Types';
+import { stringFromCodePoint } from 'common/input/TextDecoder';
+import { CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, CHAR_DATA_ATTR_INDEX, Content } from 'common/buffer/Constants';
+import { AttributeData } from 'common/buffer/AttributeData';
+
+/**
+ * CellData - represents a single Cell in the terminal buffer.
+ */
+export class CellData extends AttributeData implements ICellData {
+  /** Helper to create CellData from CharData. */
+  public static fromCharData(value: CharData): CellData {
+    const obj = new CellData();
+    obj.setFromCharData(value);
+    return obj;
+  }
+  /** Primitives from terminal buffer. */
+  public content: number = 0;
+  public fg: number = 0;
+  public bg: number = 0;
+  public combinedData: string = '';
+  /** Whether cell contains a combined string. */
+  public isCombined(): number {
+    return this.content & Content.IS_COMBINED_MASK;
+  }
+  /** Width of the cell. */
+  public getWidth(): number {
+    return this.content >> Content.WIDTH_SHIFT;
+  }
+  /** JS string of the content. */
+  public getChars(): string {
+    if (this.content & Content.IS_COMBINED_MASK) {
+      return this.combinedData;
+    }
+    if (this.content & Content.CODEPOINT_MASK) {
+      return stringFromCodePoint(this.content & Content.CODEPOINT_MASK);
+    }
+    return '';
+  }
+  /**
+   * Codepoint of cell
+   * Note this returns the UTF32 codepoint of single chars,
+   * if content is a combined string it returns the codepoint
+   * of the last char in string to be in line with code in CharData.
+   * */
+  public getCode(): number {
+    return (this.isCombined())
+      ? this.combinedData.charCodeAt(this.combinedData.length - 1)
+      : this.content & Content.CODEPOINT_MASK;
+  }
+  /** Set data from CharData */
+  public setFromCharData(value: CharData): void {
+    this.fg = value[CHAR_DATA_ATTR_INDEX];
+    this.bg = 0;
+    let combined = false;
+    // surrogates and combined strings need special treatment
+    if (value[CHAR_DATA_CHAR_INDEX].length > 2) {
+      combined = true;
+    }
+    else if (value[CHAR_DATA_CHAR_INDEX].length === 2) {
+      const code = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0);
+      // if the 2-char string is a surrogate create single codepoint
+      // everything else is combined
+      if (0xD800 <= code && code <= 0xDBFF) {
+        const second = value[CHAR_DATA_CHAR_INDEX].charCodeAt(1);
+        if (0xDC00 <= second && second <= 0xDFFF) {
+          this.content = ((code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+        }
+        else {
+          combined = true;
+        }
+      }
+      else {
+        combined = true;
+      }
+    }
+    else {
+      this.content = value[CHAR_DATA_CHAR_INDEX].charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    }
+    if (combined) {
+      this.combinedData = value[CHAR_DATA_CHAR_INDEX];
+      this.content = Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT);
+    }
+  }
+  /** Get data as CharData. */
+  public getAsCharData(): CharData {
+    return [this.fg, this.getChars(), this.getWidth(), this.getCode()];
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/Constants.ts b/node_modules/xterm/src/common/buffer/Constants.ts
new file mode 100644 (file)
index 0000000..276a5c5
--- /dev/null
@@ -0,0 +1,128 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+export const DEFAULT_COLOR = 256;
+export const DEFAULT_ATTR = (0 << 18) | (DEFAULT_COLOR << 9) | (256 << 0);
+
+export const CHAR_DATA_ATTR_INDEX = 0;
+export const CHAR_DATA_CHAR_INDEX = 1;
+export const CHAR_DATA_WIDTH_INDEX = 2;
+export const CHAR_DATA_CODE_INDEX = 3;
+
+/**
+ * Null cell - a real empty cell (containing nothing).
+ * Note that code should always be 0 for a null cell as
+ * several test condition of the buffer line rely on this.
+ */
+export const NULL_CELL_CHAR = '';
+export const NULL_CELL_WIDTH = 1;
+export const NULL_CELL_CODE = 0;
+
+/**
+ * Whitespace cell.
+ * This is meant as a replacement for empty cells when needed
+ * during rendering lines to preserve correct aligment.
+ */
+export const WHITESPACE_CELL_CHAR = ' ';
+export const WHITESPACE_CELL_WIDTH = 1;
+export const WHITESPACE_CELL_CODE = 32;
+
+/**
+ * Bitmasks for accessing data in `content`.
+ */
+export const enum Content {
+  /**
+   * bit 1..21    codepoint, max allowed in UTF32 is 0x10FFFF (21 bits taken)
+   *              read:   `codepoint = content & Content.codepointMask;`
+   *              write:  `content |= codepoint & Content.codepointMask;`
+   *                      shortcut if precondition `codepoint <= 0x10FFFF` is met:
+   *                      `content |= codepoint;`
+   */
+  CODEPOINT_MASK = 0x1FFFFF,
+
+  /**
+   * bit 22       flag indication whether a cell contains combined content
+   *              read:   `isCombined = content & Content.isCombined;`
+   *              set:    `content |= Content.isCombined;`
+   *              clear:  `content &= ~Content.isCombined;`
+   */
+  IS_COMBINED_MASK = 0x200000,  // 1 << 21
+
+  /**
+   * bit 1..22    mask to check whether a cell contains any string data
+   *              we need to check for codepoint and isCombined bits to see
+   *              whether a cell contains anything
+   *              read:   `isEmpty = !(content & Content.hasContent)`
+   */
+  HAS_CONTENT_MASK = 0x3FFFFF,
+
+  /**
+   * bit 23..24   wcwidth value of cell, takes 2 bits (ranges from 0..2)
+   *              read:   `width = (content & Content.widthMask) >> Content.widthShift;`
+   *                      `hasWidth = content & Content.widthMask;`
+   *                      as long as wcwidth is highest value in `content`:
+   *                      `width = content >> Content.widthShift;`
+   *              write:  `content |= (width << Content.widthShift) & Content.widthMask;`
+   *                      shortcut if precondition `0 <= width <= 3` is met:
+   *                      `content |= width << Content.widthShift;`
+   */
+  WIDTH_MASK = 0xC00000,   // 3 << 22
+  WIDTH_SHIFT = 22
+}
+
+export const enum Attributes {
+  /**
+   * bit 1..8     blue in RGB, color in P256 and P16
+   */
+  BLUE_MASK = 0xFF,
+  BLUE_SHIFT = 0,
+  PCOLOR_MASK = 0xFF,
+  PCOLOR_SHIFT = 0,
+
+  /**
+   * bit 9..16    green in RGB
+   */
+  GREEN_MASK = 0xFF00,
+  GREEN_SHIFT = 8,
+
+  /**
+   * bit 17..24   red in RGB
+   */
+  RED_MASK = 0xFF0000,
+  RED_SHIFT = 16,
+
+  /**
+   * bit 25..26   color mode: DEFAULT (0) | P16 (1) | P256 (2) | RGB (3)
+   */
+  CM_MASK = 0x3000000,
+  CM_DEFAULT = 0,
+  CM_P16 = 0x1000000,
+  CM_P256 = 0x2000000,
+  CM_RGB = 0x3000000,
+
+  /**
+   * bit 1..24  RGB room
+   */
+  RGB_MASK = 0xFFFFFF
+}
+
+export const enum FgFlags {
+  /**
+   * bit 27..31 (32th bit unused)
+   */
+  INVERSE = 0x4000000,
+  BOLD = 0x8000000,
+  UNDERLINE = 0x10000000,
+  BLINK = 0x20000000,
+  INVISIBLE = 0x40000000
+}
+
+export const enum BgFlags {
+  /**
+   * bit 27..32 (upper 4 unused)
+   */
+  ITALIC = 0x4000000,
+  DIM = 0x8000000
+}
diff --git a/node_modules/xterm/src/common/buffer/Marker.ts b/node_modules/xterm/src/common/buffer/Marker.ts
new file mode 100644 (file)
index 0000000..9a4256d
--- /dev/null
@@ -0,0 +1,36 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { Disposable } from 'common/Lifecycle';
+import { IMarker } from 'common/Types';
+
+export class Marker extends Disposable implements IMarker {
+  private static _nextId = 1;
+
+  private _id: number = Marker._nextId++;
+  public isDisposed: boolean = false;
+
+  public get id(): number { return this._id; }
+
+  private _onDispose = new EventEmitter<void>();
+  public get onDispose(): IEvent<void> { return this._onDispose.event; }
+
+  constructor(
+    public line: number
+  ) {
+    super();
+  }
+
+  public dispose(): void {
+    if (this.isDisposed) {
+      return;
+    }
+    this.isDisposed = true;
+    this.line = -1;
+    // Emit before super.dispose such that dispose listeners get a change to react
+    this._onDispose.fire();
+  }
+}
diff --git a/node_modules/xterm/src/common/buffer/Types.d.ts b/node_modules/xterm/src/common/buffer/Types.d.ts
new file mode 100644 (file)
index 0000000..e229d69
--- /dev/null
@@ -0,0 +1,61 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IAttributeData, ICircularList, IBufferLine, ICellData, IMarker, ICharset } from 'common/Types';
+import { IEvent } from 'common/EventEmitter';
+
+// BufferIndex denotes a position in the buffer: [rowIndex, colIndex]
+export type BufferIndex = [number, number];
+
+export interface IBufferStringIteratorResult {
+  range: {first: number, last: number};
+  content: string;
+}
+
+export interface IBufferStringIterator {
+  hasNext(): boolean;
+  next(): IBufferStringIteratorResult;
+}
+
+export interface IBuffer {
+  readonly lines: ICircularList<IBufferLine>;
+  ydisp: number;
+  ybase: number;
+  y: number;
+  x: number;
+  tabs: any;
+  scrollBottom: number;
+  scrollTop: number;
+  hasScrollback: boolean;
+  savedY: number;
+  savedX: number;
+  savedCharset: ICharset | null;
+  savedCurAttrData: IAttributeData;
+  isCursorInViewport: boolean;
+  markers: IMarker[];
+  translateBufferLineToString(lineIndex: number, trimRight: boolean, startCol?: number, endCol?: number): string;
+  getWrappedRangeForLine(y: number): { first: number, last: number };
+  nextStop(x?: number): number;
+  prevStop(x?: number): number;
+  getBlankLine(attr: IAttributeData, isWrapped?: boolean): IBufferLine;
+  stringIndexToBufferIndex(lineIndex: number, stringIndex: number, trimRight?: boolean): number[];
+  iterator(trimRight: boolean, startIndex?: number, endIndex?: number, startOverscan?: number, endOverscan?: number): IBufferStringIterator;
+  getNullCell(attr?: IAttributeData): ICellData;
+  getWhitespaceCell(attr?: IAttributeData): ICellData;
+  addMarker(y: number): IMarker;
+}
+
+export interface IBufferSet {
+  alt: IBuffer;
+  normal: IBuffer;
+  active: IBuffer;
+
+  onBufferActivate: IEvent<{ activeBuffer: IBuffer, inactiveBuffer: IBuffer }>;
+
+  activateNormalBuffer(): void;
+  activateAltBuffer(fillAttr?: IAttributeData): void;
+  resize(newCols: number, newRows: number): void;
+  setupTabStops(i?: number): void;
+}
diff --git a/node_modules/xterm/src/common/data/Charsets.ts b/node_modules/xterm/src/common/data/Charsets.ts
new file mode 100644 (file)
index 0000000..56ca679
--- /dev/null
@@ -0,0 +1,255 @@
+/**
+ * Copyright (c) 2016 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICharset } from 'common/Types';
+
+/**
+ * The character sets supported by the terminal. These enable several languages
+ * to be represented within the terminal with only 8-bit encoding. See ISO 2022
+ * for a discussion on character sets. Only VT100 character sets are supported.
+ */
+export const CHARSETS: { [key: string]: ICharset | null } = {};
+
+/**
+ * The default character set, US.
+ */
+export const DEFAULT_CHARSET: ICharset | null = CHARSETS['B'];
+
+/**
+ * DEC Special Character and Line Drawing Set.
+ * Reference: http://vt100.net/docs/vt102-ug/table5-13.html
+ * A lot of curses apps use this if they see TERM=xterm.
+ * testing: echo -e '\e(0a\e(B'
+ * The xterm output sometimes seems to conflict with the
+ * reference above. xterm seems in line with the reference
+ * when running vttest however.
+ * The table below now uses xterm's output from vttest.
+ */
+CHARSETS['0'] = {
+  '`': '\u25c6', // '◆'
+  'a': '\u2592', // '▒'
+  'b': '\u0009', // '\t'
+  'c': '\u000c', // '\f'
+  'd': '\u000d', // '\r'
+  'e': '\u000a', // '\n'
+  'f': '\u00b0', // '°'
+  'g': '\u00b1', // '±'
+  'h': '\u2424', // '\u2424' (NL)
+  'i': '\u000b', // '\v'
+  'j': '\u2518', // '┘'
+  'k': '\u2510', // '┐'
+  'l': '\u250c', // '┌'
+  'm': '\u2514', // '└'
+  'n': '\u253c', // '┼'
+  'o': '\u23ba', // '⎺'
+  'p': '\u23bb', // '⎻'
+  'q': '\u2500', // '─'
+  'r': '\u23bc', // '⎼'
+  's': '\u23bd', // '⎽'
+  't': '\u251c', // '├'
+  'u': '\u2524', // '┤'
+  'v': '\u2534', // '┴'
+  'w': '\u252c', // '┬'
+  'x': '\u2502', // '│'
+  'y': '\u2264', // '≤'
+  'z': '\u2265', // '≥'
+  '{': '\u03c0', // 'π'
+  '|': '\u2260', // '≠'
+  '}': '\u00a3', // '£'
+  '~': '\u00b7'  // '·'
+};
+
+/**
+ * British character set
+ * ESC (A
+ * Reference: http://vt100.net/docs/vt220-rm/table2-5.html
+ */
+CHARSETS['A'] = {
+  '#': '£'
+};
+
+/**
+ * United States character set
+ * ESC (B
+ */
+CHARSETS['B'] = null;
+
+/**
+ * Dutch character set
+ * ESC (4
+ * Reference: http://vt100.net/docs/vt220-rm/table2-6.html
+ */
+CHARSETS['4'] = {
+  '#': '£',
+  '@': '¾',
+  '[': 'ij',
+  '\\': '½',
+  ']': '|',
+  '{': '¨',
+  '|': 'f',
+  '}': '¼',
+  '~': '´'
+};
+
+/**
+ * Finnish character set
+ * ESC (C or ESC (5
+ * Reference: http://vt100.net/docs/vt220-rm/table2-7.html
+ */
+CHARSETS['C'] =
+CHARSETS['5'] = {
+  '[': 'Ä',
+  '\\': 'Ö',
+  ']': 'Å',
+  '^': 'Ü',
+  '`': 'é',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'å',
+  '~': 'ü'
+};
+
+/**
+ * French character set
+ * ESC (R
+ * Reference: http://vt100.net/docs/vt220-rm/table2-8.html
+ */
+CHARSETS['R'] = {
+  '#': '£',
+  '@': 'à',
+  '[': '°',
+  '\\': 'ç',
+  ']': '§',
+  '{': 'é',
+  '|': 'ù',
+  '}': 'è',
+  '~': '¨'
+};
+
+/**
+ * French Canadian character set
+ * ESC (Q
+ * Reference: http://vt100.net/docs/vt220-rm/table2-9.html
+ */
+CHARSETS['Q'] = {
+  '@': 'à',
+  '[': 'â',
+  '\\': 'ç',
+  ']': 'ê',
+  '^': 'î',
+  '`': 'ô',
+  '{': 'é',
+  '|': 'ù',
+  '}': 'è',
+  '~': 'û'
+};
+
+/**
+ * German character set
+ * ESC (K
+ * Reference: http://vt100.net/docs/vt220-rm/table2-10.html
+ */
+CHARSETS['K'] = {
+  '@': '§',
+  '[': 'Ä',
+  '\\': 'Ö',
+  ']': 'Ü',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'ü',
+  '~': 'ß'
+};
+
+/**
+ * Italian character set
+ * ESC (Y
+ * Reference: http://vt100.net/docs/vt220-rm/table2-11.html
+ */
+CHARSETS['Y'] = {
+  '#': '£',
+  '@': '§',
+  '[': '°',
+  '\\': 'ç',
+  ']': 'é',
+  '`': 'ù',
+  '{': 'à',
+  '|': 'ò',
+  '}': 'è',
+  '~': 'ì'
+};
+
+/**
+ * Norwegian/Danish character set
+ * ESC (E or ESC (6
+ * Reference: http://vt100.net/docs/vt220-rm/table2-12.html
+ */
+CHARSETS['E'] =
+CHARSETS['6'] = {
+  '@': 'Ä',
+  '[': 'Æ',
+  '\\': 'Ø',
+  ']': 'Å',
+  '^': 'Ü',
+  '`': 'ä',
+  '{': 'æ',
+  '|': 'ø',
+  '}': 'å',
+  '~': 'ü'
+};
+
+/**
+ * Spanish character set
+ * ESC (Z
+ * Reference: http://vt100.net/docs/vt220-rm/table2-13.html
+ */
+CHARSETS['Z'] = {
+  '#': '£',
+  '@': '§',
+  '[': '¡',
+  '\\': 'Ñ',
+  ']': '¿',
+  '{': '°',
+  '|': 'ñ',
+  '}': 'ç'
+};
+
+/**
+ * Swedish character set
+ * ESC (H or ESC (7
+ * Reference: http://vt100.net/docs/vt220-rm/table2-14.html
+ */
+CHARSETS['H'] =
+CHARSETS['7'] = {
+  '@': 'É',
+  '[': 'Ä',
+  '\\': 'Ö',
+  ']': 'Å',
+  '^': 'Ü',
+  '`': 'é',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'å',
+  '~': 'ü'
+};
+
+/**
+ * Swiss character set
+ * ESC (=
+ * Reference: http://vt100.net/docs/vt220-rm/table2-15.html
+ */
+CHARSETS['='] = {
+  '#': 'ù',
+  '@': 'à',
+  '[': 'é',
+  '\\': 'ç',
+  ']': 'ê',
+  '^': 'î',
+  '_': 'è',
+  '`': 'ô',
+  '{': 'ä',
+  '|': 'ö',
+  '}': 'ü',
+  '~': 'û'
+};
diff --git a/node_modules/xterm/src/common/data/EscapeSequences.ts b/node_modules/xterm/src/common/data/EscapeSequences.ts
new file mode 100644 (file)
index 0000000..e35f01d
--- /dev/null
@@ -0,0 +1,150 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/**
+ * C0 control codes
+ * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes
+ */
+export namespace C0 {
+  /** Null (Caret = ^@, C = \0) */
+  export const NUL = '\x00';
+  /** Start of Heading (Caret = ^A) */
+  export const SOH = '\x01';
+  /** Start of Text (Caret = ^B) */
+  export const STX = '\x02';
+  /** End of Text (Caret = ^C) */
+  export const ETX = '\x03';
+  /** End of Transmission (Caret = ^D) */
+  export const EOT = '\x04';
+  /** Enquiry (Caret = ^E) */
+  export const ENQ = '\x05';
+  /** Acknowledge (Caret = ^F) */
+  export const ACK = '\x06';
+  /** Bell (Caret = ^G, C = \a) */
+  export const BEL = '\x07';
+  /** Backspace (Caret = ^H, C = \b) */
+  export const BS  = '\x08';
+  /** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \t) */
+  export const HT  = '\x09';
+  /** Line Feed (Caret = ^J, C = \n) */
+  export const LF  = '\x0a';
+  /** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \v) */
+  export const VT  = '\x0b';
+  /** Form Feed (Caret = ^L, C = \f) */
+  export const FF  = '\x0c';
+  /** Carriage Return (Caret = ^M, C = \r) */
+  export const CR  = '\x0d';
+  /** Shift Out (Caret = ^N) */
+  export const SO  = '\x0e';
+  /** Shift In (Caret = ^O) */
+  export const SI  = '\x0f';
+  /** Data Link Escape (Caret = ^P) */
+  export const DLE = '\x10';
+  /** Device Control One (XON) (Caret = ^Q) */
+  export const DC1 = '\x11';
+  /** Device Control Two (Caret = ^R) */
+  export const DC2 = '\x12';
+  /** Device Control Three (XOFF) (Caret = ^S) */
+  export const DC3 = '\x13';
+  /** Device Control Four (Caret = ^T) */
+  export const DC4 = '\x14';
+  /** Negative Acknowledge (Caret = ^U) */
+  export const NAK = '\x15';
+  /** Synchronous Idle (Caret = ^V) */
+  export const SYN = '\x16';
+  /** End of Transmission Block (Caret = ^W) */
+  export const ETB = '\x17';
+  /** Cancel (Caret = ^X) */
+  export const CAN = '\x18';
+  /** End of Medium (Caret = ^Y) */
+  export const EM  = '\x19';
+  /** Substitute (Caret = ^Z) */
+  export const SUB = '\x1a';
+  /** Escape (Caret = ^[, C = \e) */
+  export const ESC = '\x1b';
+  /** File Separator (Caret = ^\) */
+  export const FS  = '\x1c';
+  /** Group Separator (Caret = ^]) */
+  export const GS  = '\x1d';
+  /** Record Separator (Caret = ^^) */
+  export const RS  = '\x1e';
+  /** Unit Separator (Caret = ^_) */
+  export const US  = '\x1f';
+  /** Space */
+  export const SP  = '\x20';
+  /** Delete (Caret = ^?) */
+  export const DEL = '\x7f';
+}
+
+/**
+ * C1 control codes
+ * See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes
+ */
+export namespace C1 {
+  /** padding character */
+  export const PAD = '\x80';
+  /** High Octet Preset */
+  export const HOP = '\x81';
+  /** Break Permitted Here */
+  export const BPH = '\x82';
+  /** No Break Here */
+  export const NBH = '\x83';
+  /** Index */
+  export const IND = '\x84';
+  /** Next Line */
+  export const NEL = '\x85';
+  /** Start of Selected Area */
+  export const SSA = '\x86';
+  /** End of Selected Area */
+  export const ESA = '\x87';
+  /** Horizontal Tabulation Set */
+  export const HTS = '\x88';
+  /** Horizontal Tabulation With Justification */
+  export const HTJ = '\x89';
+  /** Vertical Tabulation Set */
+  export const VTS = '\x8a';
+  /** Partial Line Down */
+  export const PLD = '\x8b';
+  /** Partial Line Up */
+  export const PLU = '\x8c';
+  /** Reverse Index */
+  export const RI = '\x8d';
+  /** Single-Shift 2 */
+  export const SS2 = '\x8e';
+  /** Single-Shift 3 */
+  export const SS3 = '\x8f';
+  /** Device Control String */
+  export const DCS = '\x90';
+  /** Private Use 1 */
+  export const PU1 = '\x91';
+  /** Private Use 2 */
+  export const PU2 = '\x92';
+  /** Set Transmit State */
+  export const STS = '\x93';
+  /** Destructive backspace, intended to eliminate ambiguity about meaning of BS. */
+  export const CCH = '\x94';
+  /** Message Waiting */
+  export const MW = '\x95';
+  /** Start of Protected Area */
+  export const SPA = '\x96';
+  /** End of Protected Area */
+  export const EPA = '\x97';
+  /** Start of String */
+  export const SOS = '\x98';
+  /** Single Graphic Character Introducer */
+  export const SGCI = '\x99';
+  /** Single Character Introducer */
+  export const SCI = '\x9a';
+  /** Control Sequence Introducer */
+  export const CSI = '\x9b';
+  /** String Terminator */
+  export const ST = '\x9c';
+  /** Operating System Command */
+  export const OSC = '\x9d';
+  /** Privacy Message */
+  export const PM = '\x9e';
+  /** Application Program Command */
+  export const APC = '\x9f';
+}
diff --git a/node_modules/xterm/src/common/input/Keyboard.ts b/node_modules/xterm/src/common/input/Keyboard.ts
new file mode 100644 (file)
index 0000000..1bf378c
--- /dev/null
@@ -0,0 +1,372 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * @license MIT
+ */
+
+import { IKeyboardEvent, IKeyboardResult, KeyboardResultType } from 'common/Types';
+import { C0 } from 'common/data/EscapeSequences';
+
+// reg + shift key mappings for digits and special chars
+const KEYCODE_KEY_MAPPINGS: { [key: number]: [string, string]} = {
+  // digits 0-9
+  48: ['0', ')'],
+  49: ['1', '!'],
+  50: ['2', '@'],
+  51: ['3', '#'],
+  52: ['4', '$'],
+  53: ['5', '%'],
+  54: ['6', '^'],
+  55: ['7', '&'],
+  56: ['8', '*'],
+  57: ['9', '('],
+
+  // special chars
+  186: [';', ':'],
+  187: ['=', '+'],
+  188: [',', '<'],
+  189: ['-', '_'],
+  190: ['.', '>'],
+  191: ['/', '?'],
+  192: ['`', '~'],
+  219: ['[', '{'],
+  220: ['\\', '|'],
+  221: [']', '}'],
+  222: ['\'', '"']
+};
+
+export function evaluateKeyboardEvent(
+  ev: IKeyboardEvent,
+  applicationCursorMode: boolean,
+  isMac: boolean,
+  macOptionIsMeta: boolean
+): IKeyboardResult {
+  const result: IKeyboardResult = {
+    type: KeyboardResultType.SEND_KEY,
+    // Whether to cancel event propagation (NOTE: this may not be needed since the event is
+    // canceled at the end of keyDown
+    cancel: false,
+    // The new key even to emit
+    key: undefined
+  };
+  const modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0);
+  switch (ev.keyCode) {
+    case 0:
+      if (ev.key === 'UIKeyInputUpArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OA';
+        } else {
+          result.key = C0.ESC + '[A';
+        }
+      }
+      else if (ev.key === 'UIKeyInputLeftArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OD';
+        } else {
+          result.key = C0.ESC + '[D';
+        }
+      }
+      else if (ev.key === 'UIKeyInputRightArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OC';
+        } else {
+          result.key = C0.ESC + '[C';
+        }
+      }
+      else if (ev.key === 'UIKeyInputDownArrow') {
+        if (applicationCursorMode) {
+          result.key = C0.ESC + 'OB';
+        } else {
+          result.key = C0.ESC + '[B';
+        }
+      }
+      break;
+    case 8:
+      // backspace
+      if (ev.shiftKey) {
+        result.key = C0.BS; // ^H
+        break;
+      } else if (ev.altKey) {
+        result.key = C0.ESC + C0.DEL; // \e ^?
+        break;
+      }
+      result.key = C0.DEL; // ^?
+      break;
+    case 9:
+      // tab
+      if (ev.shiftKey) {
+        result.key = C0.ESC + '[Z';
+        break;
+      }
+      result.key = C0.HT;
+      result.cancel = true;
+      break;
+    case 13:
+      // return/enter
+      result.key = C0.CR;
+      result.cancel = true;
+      break;
+    case 27:
+      // escape
+      result.key = C0.ESC;
+      result.cancel = true;
+      break;
+    case 37:
+      // left-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
+        // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (result.key === C0.ESC + '[1;3D') {
+          result.key = C0.ESC + (isMac ? 'b' : '[1;5D');
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OD';
+      } else {
+        result.key = C0.ESC + '[D';
+      }
+      break;
+    case 39:
+      // right-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
+        // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (result.key === C0.ESC + '[1;3C') {
+          result.key = C0.ESC + (isMac ? 'f' : '[1;5C');
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OC';
+      } else {
+        result.key = C0.ESC + '[C';
+      }
+      break;
+    case 38:
+      // up-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
+        // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (!isMac && result.key === C0.ESC + '[1;3A') {
+          result.key = C0.ESC + '[1;5A';
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OA';
+      } else {
+        result.key = C0.ESC + '[A';
+      }
+      break;
+    case 40:
+      // down-arrow
+      if (ev.metaKey) {
+        break;
+      }
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
+        // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
+        // http://unix.stackexchange.com/a/108106
+        // macOS uses different escape sequences than linux
+        if (!isMac && result.key === C0.ESC + '[1;3B') {
+          result.key = C0.ESC + '[1;5B';
+        }
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OB';
+      } else {
+        result.key = C0.ESC + '[B';
+      }
+      break;
+    case 45:
+      // insert
+      if (!ev.shiftKey && !ev.ctrlKey) {
+        // <Ctrl> or <Shift> + <Insert> are used to
+        // copy-paste on some systems.
+        result.key = C0.ESC + '[2~';
+      }
+      break;
+    case 46:
+      // delete
+      if (modifiers) {
+        result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[3~';
+      }
+      break;
+    case 36:
+      // home
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OH';
+      } else {
+        result.key = C0.ESC + '[H';
+      }
+      break;
+    case 35:
+      // end
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
+      } else if (applicationCursorMode) {
+        result.key = C0.ESC + 'OF';
+      } else {
+        result.key = C0.ESC + '[F';
+      }
+      break;
+    case 33:
+      // page up
+      if (ev.shiftKey) {
+        result.type = KeyboardResultType.PAGE_UP;
+      } else {
+        result.key = C0.ESC + '[5~';
+      }
+      break;
+    case 34:
+      // page down
+      if (ev.shiftKey) {
+        result.type = KeyboardResultType.PAGE_DOWN;
+      } else {
+        result.key = C0.ESC + '[6~';
+      }
+      break;
+    case 112:
+      // F1-F12
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
+      } else {
+        result.key = C0.ESC + 'OP';
+      }
+      break;
+    case 113:
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
+      } else {
+        result.key = C0.ESC + 'OQ';
+      }
+      break;
+    case 114:
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
+      } else {
+        result.key = C0.ESC + 'OR';
+      }
+      break;
+    case 115:
+      if (modifiers) {
+        result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
+      } else {
+        result.key = C0.ESC + 'OS';
+      }
+      break;
+    case 116:
+      if (modifiers) {
+        result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[15~';
+      }
+      break;
+    case 117:
+      if (modifiers) {
+        result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[17~';
+      }
+      break;
+    case 118:
+      if (modifiers) {
+        result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[18~';
+      }
+      break;
+    case 119:
+      if (modifiers) {
+        result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[19~';
+      }
+      break;
+    case 120:
+      if (modifiers) {
+        result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[20~';
+      }
+      break;
+    case 121:
+      if (modifiers) {
+        result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[21~';
+      }
+      break;
+    case 122:
+      if (modifiers) {
+        result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[23~';
+      }
+      break;
+    case 123:
+      if (modifiers) {
+        result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
+      } else {
+        result.key = C0.ESC + '[24~';
+      }
+      break;
+    default:
+      // a-z and space
+      if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
+        if (ev.keyCode >= 65 && ev.keyCode <= 90) {
+          result.key = String.fromCharCode(ev.keyCode - 64);
+        } else if (ev.keyCode === 32) {
+          result.key = C0.NUL;
+        } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
+          // escape, file sep, group sep, record sep, unit sep
+          result.key = String.fromCharCode(ev.keyCode - 51 + 27);
+        } else if (ev.keyCode === 56) {
+          result.key = C0.DEL;
+        } else if (ev.keyCode === 219) {
+          result.key = C0.ESC;
+        } else if (ev.keyCode === 220) {
+          result.key = C0.FS;
+        } else if (ev.keyCode === 221) {
+          result.key = C0.GS;
+        }
+      } else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) {
+        // On macOS this is a third level shift when !macOptionIsMeta. Use <Esc> instead.
+        const keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode];
+        const key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1];
+        if (key) {
+          result.key = C0.ESC + key;
+        } else if (ev.keyCode >= 65 && ev.keyCode <= 90) {
+          const keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32;
+          result.key = C0.ESC + String.fromCharCode(keyCode);
+        }
+      } else if (isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) {
+        if (ev.keyCode === 65) { // cmd + a
+          result.type = KeyboardResultType.SELECT_ALL;
+        }
+      } else if (ev.key && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.keyCode >= 48 && ev.key.length === 1) {
+        // Include only keys that that result in a _single_ character; don't include num lock, volume up, etc.
+        result.key = ev.key;
+      } else if (ev.key && ev.ctrlKey) {
+        if (ev.key === '_') { // ^_
+          result.key = C0.US;
+        }
+      }
+      break;
+  }
+
+  return result;
+}
diff --git a/node_modules/xterm/src/common/input/TextDecoder.ts b/node_modules/xterm/src/common/input/TextDecoder.ts
new file mode 100644 (file)
index 0000000..397d25a
--- /dev/null
@@ -0,0 +1,342 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/**
+ * Polyfill - Convert UTF32 codepoint into JS string.
+ * Note: The built-in String.fromCodePoint happens to be much slower
+ *       due to additional sanity checks. We can avoid them since
+ *       we always operate on legal UTF32 (granted by the input decoders)
+ *       and use this faster version instead.
+ */
+export function stringFromCodePoint(codePoint: number): string {
+  if (codePoint > 0xFFFF) {
+    codePoint -= 0x10000;
+    return String.fromCharCode((codePoint >> 10) + 0xD800) + String.fromCharCode((codePoint % 0x400) + 0xDC00);
+  }
+  return String.fromCharCode(codePoint);
+}
+
+/**
+ * Convert UTF32 char codes into JS string.
+ * Basically the same as `stringFromCodePoint` but for multiple codepoints
+ * in a loop (which is a lot faster).
+ */
+export function utf32ToString(data: Uint32Array, start: number = 0, end: number = data.length): string {
+  let result = '';
+  for (let i = start; i < end; ++i) {
+    let codepoint = data[i];
+    if (codepoint > 0xFFFF) {
+      // JS strings are encoded as UTF16, thus a non BMP codepoint gets converted into a surrogate pair
+      // conversion rules:
+      //  - subtract 0x10000 from code point, leaving a 20 bit number
+      //  - add high 10 bits to 0xD800  --> first surrogate
+      //  - add low 10 bits to 0xDC00   --> second surrogate
+      codepoint -= 0x10000;
+      result += String.fromCharCode((codepoint >> 10) + 0xD800) + String.fromCharCode((codepoint % 0x400) + 0xDC00);
+    } else {
+      result += String.fromCharCode(codepoint);
+    }
+  }
+  return result;
+}
+
+/**
+ * StringToUtf32 - decodes UTF16 sequences into UTF32 codepoints.
+ * To keep the decoder in line with JS strings it handles single surrogates as UCS2.
+ */
+export class StringToUtf32 {
+  private _interim: number = 0;
+
+  /**
+   * Clears interim and resets decoder to clean state.
+   */
+  public clear(): void {
+    this._interim = 0;
+  }
+
+  /**
+   * Decode JS string to UTF32 codepoints.
+   * The methods assumes stream input and will store partly transmitted
+   * surrogate pairs and decode them with the next data chunk.
+   * Note: The method does no bound checks for target, therefore make sure
+   * the provided input data does not exceed the size of `target`.
+   * Returns the number of written codepoints in `target`.
+   */
+  decode(input: string, target: Uint32Array): number {
+    const length = input.length;
+
+    if (!length) {
+      return 0;
+    }
+
+    let size = 0;
+    let startPos = 0;
+
+    // handle leftover surrogate high
+    if (this._interim) {
+      const second = input.charCodeAt(startPos++);
+      if (0xDC00 <= second && second <= 0xDFFF) {
+        target[size++] = (this._interim - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+      } else {
+        // illegal codepoint (USC2 handling)
+        target[size++] = this._interim;
+        target[size++] = second;
+      }
+      this._interim = 0;
+    }
+
+    for (let i = startPos; i < length; ++i) {
+      const code = input.charCodeAt(i);
+      // surrogate pair first
+      if (0xD800 <= code && code <= 0xDBFF) {
+        if (++i >= length) {
+          this._interim = code;
+          return size;
+        }
+        const second = input.charCodeAt(i);
+        if (0xDC00 <= second && second <= 0xDFFF) {
+          target[size++] = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+        } else {
+          // illegal codepoint (USC2 handling)
+          target[size++] = code;
+          target[size++] = second;
+        }
+        continue;
+      }
+      target[size++] = code;
+    }
+    return size;
+  }
+}
+
+/**
+ * Utf8Decoder - decodes UTF8 byte sequences into UTF32 codepoints.
+ */
+export class Utf8ToUtf32 {
+  public interim: Uint8Array = new Uint8Array(3);
+
+  /**
+   * Clears interim bytes and resets decoder to clean state.
+   */
+  public clear(): void {
+    this.interim.fill(0);
+  }
+
+  /**
+   * Decodes UTF8 byte sequences in `input` to UTF32 codepoints in `target`.
+   * The methods assumes stream input and will store partly transmitted bytes
+   * and decode them with the next data chunk.
+   * Note: The method does no bound checks for target, therefore make sure
+   * the provided data chunk does not exceed the size of `target`.
+   * Returns the number of written codepoints in `target`.
+   */
+  decode(input: Uint8Array, target: Uint32Array): number {
+    const length = input.length;
+
+    if (!length) {
+      return 0;
+    }
+
+    let size = 0;
+    let byte1: number;
+    let byte2: number;
+    let byte3: number;
+    let byte4: number;
+    let codepoint = 0;
+    let startPos = 0;
+
+    // handle leftover bytes
+    if (this.interim[0]) {
+      let discardInterim = false;
+      let cp = this.interim[0];
+      cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);
+      let pos = 0;
+      let tmp: number;
+      while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {
+        cp <<= 6;
+        cp |= tmp;
+      }
+      // missing bytes - read ahead from input
+      const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;
+      const missing = type - pos;
+      while (startPos < missing) {
+        if (startPos >= length) {
+          return 0;
+        }
+        tmp = input[startPos++];
+        if ((tmp & 0xC0) !== 0x80) {
+          // wrong continuation, discard interim bytes completely
+          startPos--;
+          discardInterim = true;
+          break;
+        } else {
+          // need to save so we can continue short inputs in next call
+          this.interim[pos++] = tmp;
+          cp <<= 6;
+          cp |= tmp & 0x3F;
+        }
+      }
+      if (!discardInterim) {
+        // final test is type dependent
+        if (type === 2) {
+          if (cp < 0x80) {
+            // wrong starter byte
+            startPos--;
+          } else {
+            target[size++] = cp;
+          }
+        } else if (type === 3) {
+          if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF)) {
+            // illegal codepoint
+          } else {
+            target[size++] = cp;
+          }
+        } else {
+          if (cp < 0x010000 || cp > 0x10FFFF) {
+            // illegal codepoint
+          } else {
+            target[size++] = cp;
+          }
+        }
+      }
+      this.interim.fill(0);
+    }
+
+    // loop through input
+    const fourStop = length - 4;
+    let i = startPos;
+    while (i < length) {
+      /**
+       * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.
+       * This is a compromise between speed gain for ASCII
+       * and penalty for non ASCII:
+       * For best ASCII performance the char should be stored directly into target,
+       * but even a single attempt to write to target and compare afterwards
+       * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,
+       * which reduces ASCII performance by ~15%.
+       * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible
+       * compared to the gains.
+       * Note that this optimization only takes place for 4 consecutive ASCII chars,
+       * for any shorter it bails out. Worst case - all 4 bytes being read but
+       * thrown away due to the last being a non ASCII char (-10% performance).
+       */
+      while (i < fourStop
+        && !((byte1 = input[i]) & 0x80)
+        && !((byte2 = input[i + 1]) & 0x80)
+        && !((byte3 = input[i + 2]) & 0x80)
+        && !((byte4 = input[i + 3]) & 0x80))
+      {
+        target[size++] = byte1;
+        target[size++] = byte2;
+        target[size++] = byte3;
+        target[size++] = byte4;
+        i += 4;
+      }
+
+      // reread byte1
+      byte1 = input[i++];
+
+      // 1 byte
+      if (byte1 < 0x80) {
+        target[size++] = byte1;
+
+        // 2 bytes
+      } else if ((byte1 & 0xE0) === 0xC0) {
+        if (i >= length) {
+          this.interim[0] = byte1;
+          return size;
+        }
+        byte2 = input[i++];
+        if ((byte2 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);
+        if (codepoint < 0x80) {
+          // wrong starter byte
+          i--;
+          continue;
+        }
+        target[size++] = codepoint;
+
+        // 3 bytes
+      } else if ((byte1 & 0xF0) === 0xE0) {
+        if (i >= length) {
+          this.interim[0] = byte1;
+          return size;
+        }
+        byte2 = input[i++];
+        if ((byte2 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        if (i >= length) {
+          this.interim[0] = byte1;
+          this.interim[1] = byte2;
+          return size;
+        }
+        byte3 = input[i++];
+        if ((byte3 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);
+        if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
+          // illegal codepoint, no i-- here
+          continue;
+        }
+        target[size++] = codepoint;
+
+        // 4 bytes
+      } else if ((byte1 & 0xF8) === 0xF0) {
+        if (i >= length) {
+          this.interim[0] = byte1;
+          return size;
+        }
+        byte2 = input[i++];
+        if ((byte2 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        if (i >= length) {
+          this.interim[0] = byte1;
+          this.interim[1] = byte2;
+          return size;
+        }
+        byte3 = input[i++];
+        if ((byte3 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        if (i >= length) {
+          this.interim[0] = byte1;
+          this.interim[1] = byte2;
+          this.interim[2] = byte3;
+          return size;
+        }
+        byte4 = input[i++];
+        if ((byte4 & 0xC0) !== 0x80) {
+          // wrong continuation
+          i--;
+          continue;
+        }
+        codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);
+        if (codepoint < 0x010000 || codepoint > 0x10FFFF) {
+          // illegal codepoint, no i-- here
+          continue;
+        }
+        target[size++] = codepoint;
+      } else {
+        // illegal byte, just skip
+      }
+    }
+    return size;
+  }
+}
diff --git a/node_modules/xterm/src/common/input/WriteBuffer.ts b/node_modules/xterm/src/common/input/WriteBuffer.ts
new file mode 100644 (file)
index 0000000..c7d8245
--- /dev/null
@@ -0,0 +1,110 @@
+
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+declare const setTimeout: (handler: () => void, timeout?: number) => void;
+
+/**
+ * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.
+ * Enable flow control to avoid this limit and make sure that your backend correctly
+ * propagates this to the underlying pty. (see docs for further instructions)
+ * Since this limit is meant as a safety parachute to prevent browser crashs,
+ * it is set to a very high number. Typically xterm.js gets unresponsive with
+ * a 100 times lower number (>500 kB).
+ */
+const DISCARD_WATERMARK = 50000000; // ~50 MB
+
+/**
+ * The max number of ms to spend on writes before allowing the renderer to
+ * catch up with a 0ms setTimeout. A value of < 33 to keep us close to
+ * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS
+ * depends on the time it takes for the renderer to draw the frame.
+ */
+const WRITE_TIMEOUT_MS = 12;
+
+/**
+ * Threshold of max held chunks in the write buffer, that were already processed.
+ * This is a tradeoff between extensive write buffer shifts (bad runtime) and high
+ * memory consumption by data thats not used anymore.
+ */
+const WRITE_BUFFER_LENGTH_THRESHOLD = 50;
+
+export class WriteBuffer {
+  private _writeBuffer: (string | Uint8Array)[] = [];
+  private _callbacks: ((() => void) | undefined)[] = [];
+  private _pendingData = 0;
+  private _bufferOffset = 0;
+
+  constructor(private _action: (data: string | Uint8Array) => void) { }
+
+  public writeSync(data: string | Uint8Array): void {
+    // force sync processing on pending data chunks to avoid in-band data scrambling
+    // does the same as innerWrite but without event loop
+    if (this._writeBuffer.length) {
+      for (let i = this._bufferOffset; i < this._writeBuffer.length; ++i) {
+        const data = this._writeBuffer[i];
+        const cb = this._callbacks[i];
+        this._action(data);
+        if (cb) cb();
+      }
+      // reset all to avoid reprocessing of chunks with scheduled innerWrite call
+      this._writeBuffer = [];
+      this._callbacks = [];
+      this._pendingData = 0;
+      // stop scheduled innerWrite by offset > length condition
+      this._bufferOffset = 0x7FFFFFFF;
+    }
+    // handle current data chunk
+    this._action(data);
+  }
+
+  public write(data: string | Uint8Array, callback?: () => void): void {
+    if (this._pendingData > DISCARD_WATERMARK) {
+      throw new Error('write data discarded, use flow control to avoid losing data');
+    }
+
+    // schedule chunk processing for next event loop run
+    if (!this._writeBuffer.length) {
+      this._bufferOffset = 0;
+      setTimeout(() => this._innerWrite());
+    }
+
+    this._pendingData += data.length;
+    this._writeBuffer.push(data);
+    this._callbacks.push(callback);
+  }
+
+  protected _innerWrite(): void {
+    const startTime = Date.now();
+    while (this._writeBuffer.length > this._bufferOffset) {
+      const data = this._writeBuffer[this._bufferOffset];
+      const cb = this._callbacks[this._bufferOffset];
+      this._bufferOffset++;
+
+      this._action(data);
+      this._pendingData -= data.length;
+      if (cb) cb();
+
+      if (Date.now() - startTime >= WRITE_TIMEOUT_MS) {
+        break;
+      }
+    }
+    if (this._writeBuffer.length > this._bufferOffset) {
+      // Allow renderer to catch up before processing the next batch
+      // trim already processed chunks if we are above threshold
+      if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {
+        this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);
+        this._callbacks = this._callbacks.slice(this._bufferOffset);
+        this._bufferOffset = 0;
+      }
+      setTimeout(() => this._innerWrite(), 0);
+    } else {
+      this._writeBuffer = [];
+      this._callbacks = [];
+      this._pendingData = 0;
+      this._bufferOffset = 0;
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/Constants.ts b/node_modules/xterm/src/common/parser/Constants.ts
new file mode 100644 (file)
index 0000000..85156c3
--- /dev/null
@@ -0,0 +1,58 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+/**
+ * Internal states of EscapeSequenceParser.
+ */
+export const enum ParserState {
+  GROUND = 0,
+  ESCAPE = 1,
+  ESCAPE_INTERMEDIATE = 2,
+  CSI_ENTRY = 3,
+  CSI_PARAM = 4,
+  CSI_INTERMEDIATE = 5,
+  CSI_IGNORE = 6,
+  SOS_PM_APC_STRING = 7,
+  OSC_STRING = 8,
+  DCS_ENTRY = 9,
+  DCS_PARAM = 10,
+  DCS_IGNORE = 11,
+  DCS_INTERMEDIATE = 12,
+  DCS_PASSTHROUGH = 13
+}
+
+/**
+* Internal actions of EscapeSequenceParser.
+*/
+export const enum ParserAction {
+  IGNORE = 0,
+  ERROR = 1,
+  PRINT = 2,
+  EXECUTE = 3,
+  OSC_START = 4,
+  OSC_PUT = 5,
+  OSC_END = 6,
+  CSI_DISPATCH = 7,
+  PARAM = 8,
+  COLLECT = 9,
+  ESC_DISPATCH = 10,
+  CLEAR = 11,
+  DCS_HOOK = 12,
+  DCS_PUT = 13,
+  DCS_UNHOOK = 14
+}
+
+/**
+ * Internal states of OscParser.
+ */
+export const enum OscState {
+  START = 0,
+  ID = 1,
+  PAYLOAD = 2,
+  ABORT = 3
+}
+
+// payload limit for OSC and DCS
+export const PAYLOAD_LIMIT = 10000000;
diff --git a/node_modules/xterm/src/common/parser/DcsParser.ts b/node_modules/xterm/src/common/parser/DcsParser.ts
new file mode 100644 (file)
index 0000000..4622c4a
--- /dev/null
@@ -0,0 +1,146 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+import { IDcsHandler, IParams, IHandlerCollection, IDcsParser, DcsFallbackHandlerType } from 'common/parser/Types';
+import { utf32ToString } from 'common/input/TextDecoder';
+import { Params } from 'common/parser/Params';
+import { PAYLOAD_LIMIT } from 'common/parser/Constants';
+
+const EMPTY_HANDLERS: IDcsHandler[] = [];
+
+export class DcsParser implements IDcsParser {
+  private _handlers: IHandlerCollection<IDcsHandler> = Object.create(null);
+  private _active: IDcsHandler[] = EMPTY_HANDLERS;
+  private _ident: number = 0;
+  private _handlerFb: DcsFallbackHandlerType = () => {};
+
+  public dispose(): void {
+    this._handlers = Object.create(null);
+    this._handlerFb = () => {};
+  }
+
+  public addHandler(ident: number, handler: IDcsHandler): IDisposable {
+    if (this._handlers[ident] === undefined) {
+      this._handlers[ident] = [];
+    }
+    const handlerList = this._handlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+
+  public setHandler(ident: number, handler: IDcsHandler): void {
+    this._handlers[ident] = [handler];
+  }
+
+  public clearHandler(ident: number): void {
+    if (this._handlers[ident]) delete this._handlers[ident];
+  }
+
+  public setHandlerFallback(handler: DcsFallbackHandlerType): void {
+    this._handlerFb = handler;
+  }
+
+  public reset(): void {
+    if (this._active.length) {
+      this.unhook(false);
+    }
+    this._active = EMPTY_HANDLERS;
+    this._ident = 0;
+  }
+
+  public hook(ident: number, params: IParams): void {
+    // always reset leftover handlers
+    this.reset();
+    this._ident = ident;
+    this._active = this._handlers[ident] || EMPTY_HANDLERS;
+    if (!this._active.length) {
+      this._handlerFb(this._ident, 'HOOK', params);
+    } else {
+      for (let j = this._active.length - 1; j >= 0; j--) {
+        this._active[j].hook(params);
+      }
+    }
+  }
+
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (!this._active.length) {
+      this._handlerFb(this._ident, 'PUT', utf32ToString(data, start, end));
+    } else {
+      for (let j = this._active.length - 1; j >= 0; j--) {
+        this._active[j].put(data, start, end);
+      }
+    }
+  }
+
+  public unhook(success: boolean): void {
+    if (!this._active.length) {
+      this._handlerFb(this._ident, 'UNHOOK', success);
+    } else {
+      let j = this._active.length - 1;
+      for (; j >= 0; j--) {
+        if (this._active[j].unhook(success) !== false) {
+          break;
+        }
+      }
+      j--;
+      // cleanup left over handlers
+      for (; j >= 0; j--) {
+        this._active[j].unhook(false);
+      }
+    }
+    this._active = EMPTY_HANDLERS;
+    this._ident = 0;
+  }
+}
+
+/**
+ * Convenient class to create a DCS handler from a single callback function.
+ * Note: The payload is currently limited to 50 MB (hardcoded).
+ */
+export class DcsHandler implements IDcsHandler {
+  private _data = '';
+  private _params: IParams | undefined;
+  private _hitLimit: boolean = false;
+
+  constructor(private _handler: (data: string, params: IParams) => any) {}
+
+  public hook(params: IParams): void {
+    this._params = params.clone();
+    this._data = '';
+    this._hitLimit = false;
+  }
+
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (this._hitLimit) {
+      return;
+    }
+    this._data += utf32ToString(data, start, end);
+    if (this._data.length > PAYLOAD_LIMIT) {
+      this._data = '';
+      this._hitLimit = true;
+    }
+  }
+
+  public unhook(success: boolean): any {
+    let ret;
+    if (this._hitLimit) {
+      ret = false;
+    } else if (success) {
+      ret = this._handler(this._data, this._params ? this._params : new Params());
+    }
+    this._params = undefined;
+    this._data = '';
+    this._hitLimit = false;
+    return ret;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts b/node_modules/xterm/src/common/parser/EscapeSequenceParser.ts
new file mode 100644 (file)
index 0000000..bc0b620
--- /dev/null
@@ -0,0 +1,636 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType } from 'common/parser/Types';
+import { ParserState, ParserAction } from 'common/parser/Constants';
+import { Disposable } from 'common/Lifecycle';
+import { IDisposable } from 'common/Types';
+import { fill } from 'common/TypedArrayUtils';
+import { Params } from 'common/parser/Params';
+import { OscParser } from 'common/parser/OscParser';
+import { DcsParser } from 'common/parser/DcsParser';
+
+/**
+ * Table values are generated like this:
+ *    index:  currentState << TableValue.INDEX_STATE_SHIFT | charCode
+ *    value:  action << TableValue.TRANSITION_ACTION_SHIFT | nextState
+ */
+const enum TableAccess {
+  TRANSITION_ACTION_SHIFT = 4,
+  TRANSITION_STATE_MASK = 15,
+  INDEX_STATE_SHIFT = 8
+}
+
+/**
+ * Transition table for EscapeSequenceParser.
+ */
+export class TransitionTable {
+  public table: Uint8Array;
+
+  constructor(length: number) {
+    this.table = new Uint8Array(length);
+  }
+
+  /**
+   * Set default transition.
+   * @param action default action
+   * @param next default next state
+   */
+  public setDefault(action: ParserAction, next: ParserState): void {
+    fill(this.table, action << TableAccess.TRANSITION_ACTION_SHIFT | next);
+  }
+
+  /**
+   * Add a transition to the transition table.
+   * @param code input character code
+   * @param state current parser state
+   * @param action parser action to be done
+   * @param next next parser state
+   */
+  public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {
+    this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
+  }
+
+  /**
+   * Add transitions for multiple input character codes.
+   * @param codes input character code array
+   * @param state current parser state
+   * @param action parser action to be done
+   * @param next next parser state
+   */
+  public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {
+    for (let i = 0; i < codes.length; i++) {
+      this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
+    }
+  }
+}
+
+
+// Pseudo-character placeholder for printable non-ascii characters (unicode).
+const NON_ASCII_PRINTABLE = 0xA0;
+
+
+/**
+ * VT500 compatible transition table.
+ * Taken from https://vt100.net/emu/dec_ansi_parser.
+ */
+export const VT500_TRANSITION_TABLE = (function (): TransitionTable {
+  const table: TransitionTable = new TransitionTable(4095);
+
+  // range macro for byte
+  const BYTE_VALUES = 256;
+  const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);
+  const r = (start: number, end: number) => blueprint.slice(start, end);
+
+  // Default definitions.
+  const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded
+  const EXECUTABLES = r(0x00, 0x18);
+  EXECUTABLES.push(0x19);
+  EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));
+
+  const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);
+  let state: any;
+
+  // set default transition
+  table.setDefault(ParserAction.ERROR, ParserState.GROUND);
+  // printables
+  table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
+  // global anywhere rules
+  for (state in states) {
+    table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);
+    table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);
+    table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);
+    table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator
+    table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE);  // ESC
+    table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING);  // OSC
+    table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+    table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY);  // CSI
+    table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY);  // DCS
+  }
+  // rules for executables and 7f
+  table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);
+  table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);
+  table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);
+  table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
+  table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);
+  table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);
+  table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);
+  table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);
+  table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);
+  table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);
+  table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);
+  table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);
+  table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);
+  // osc
+  table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);
+  table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
+  table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
+  table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);
+  table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
+  // sos/pm/apc does nothing
+  table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);
+  table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
+  // csi entries
+  table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);
+  table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);
+  table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
+  table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
+  table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
+  // esc_intermediate
+  table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
+  table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
+  table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
+  // dcs entry
+  table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);
+  table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
+  table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
+  table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);
+  table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
+  table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
+  table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);
+  table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
+  table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
+  table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
+  table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
+  table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
+  table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
+  table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
+  table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
+  table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);
+  table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);
+  // special handling of unicode chars
+  table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
+  table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
+  table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
+  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
+  table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
+  return table;
+})();
+
+
+/**
+ * EscapeSequenceParser.
+ * This class implements the ANSI/DEC compatible parser described by
+ * Paul Williams (https://vt100.net/emu/dec_ansi_parser).
+ *
+ * To implement custom ANSI compliant escape sequences it is not needed to
+ * alter this parser, instead consider registering a custom handler.
+ * For non ANSI compliant sequences change the transition table with
+ * the optional `transitions` constructor argument and
+ * reimplement the `parse` method.
+ *
+ * This parser is currently hardcoded to operate in ZDM (Zero Default Mode)
+ * as suggested by the original parser, thus empty parameters are set to 0.
+ * This this is not in line with the latest ECMA-48 specification
+ * (ZDM was part of the early specs and got completely removed later on).
+ *
+ * Other than the original parser from vt100.net this parser supports
+ * sub parameters in digital parameters separated by colons. Empty sub parameters
+ * are set to -1 (no ZDM for sub parameters).
+ *
+ * About prefix and intermediate bytes:
+ * This parser follows the assumptions of the vt100.net parser with these restrictions:
+ * - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f
+ * - max. two intermediates are respected, byte range 0x20 .. 0x2f
+ * Note that this is not in line with ECMA-48 which does not limit either of those.
+ * Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently
+ * there are no known sequences that follow the broader definition of the specification.
+ *
+ * TODO: implement error recovery hook via error handler return values
+ */
+export class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {
+  public initialState: number;
+  public currentState: number;
+  public precedingCodepoint: number;
+
+  // buffers over several parse calls
+  protected _params: Params;
+  protected _collect: number;
+
+  // handler lookup containers
+  protected _printHandler: PrintHandlerType;
+  protected _executeHandlers: {[flag: number]: ExecuteHandlerType};
+  protected _csiHandlers: IHandlerCollection<CsiHandlerType>;
+  protected _escHandlers: IHandlerCollection<EscHandlerType>;
+  protected _oscParser: IOscParser;
+  protected _dcsParser: IDcsParser;
+  protected _errorHandler: (state: IParsingState) => IParsingState;
+
+  // fallback handlers
+  protected _printHandlerFb: PrintFallbackHandlerType;
+  protected _executeHandlerFb: ExecuteFallbackHandlerType;
+  protected _csiHandlerFb: CsiFallbackHandlerType;
+  protected _escHandlerFb: EscFallbackHandlerType;
+  protected _errorHandlerFb: (state: IParsingState) => IParsingState;
+
+  constructor(readonly TRANSITIONS: TransitionTable = VT500_TRANSITION_TABLE) {
+    super();
+
+    this.initialState = ParserState.GROUND;
+    this.currentState = this.initialState;
+    this._params = new Params(); // defaults to 32 storable params/subparams
+    this._params.addParam(0);    // ZDM
+    this._collect = 0;
+    this.precedingCodepoint = 0;
+
+    // set default fallback handlers and handler lookup containers
+    this._printHandlerFb = (data, start, end): void => { };
+    this._executeHandlerFb = (code: number): void => { };
+    this._csiHandlerFb = (ident: number, params: IParams): void => { };
+    this._escHandlerFb = (ident: number): void => { };
+    this._errorHandlerFb = (state: IParsingState): IParsingState => state;
+    this._printHandler = this._printHandlerFb;
+    this._executeHandlers = Object.create(null);
+    this._csiHandlers = Object.create(null);
+    this._escHandlers = Object.create(null);
+    this._oscParser = new OscParser();
+    this._dcsParser = new DcsParser();
+    this._errorHandler = this._errorHandlerFb;
+
+    // swallow 7bit ST (ESC+\)
+    this.setEscHandler({final: '\\'}, () => {});
+  }
+
+  protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {
+    let res = 0;
+    if (id.prefix) {
+      if (id.prefix.length > 1) {
+        throw new Error('only one byte as prefix supported');
+      }
+      res = id.prefix.charCodeAt(0);
+      if (res && 0x3c > res || res > 0x3f) {
+        throw new Error('prefix must be in range 0x3c .. 0x3f');
+      }
+    }
+    if (id.intermediates) {
+      if (id.intermediates.length > 2) {
+        throw new Error('only two bytes as intermediates are supported');
+      }
+      for (let i = 0; i < id.intermediates.length; ++i) {
+        const intermediate = id.intermediates.charCodeAt(i);
+        if (0x20 > intermediate || intermediate > 0x2f) {
+          throw new Error('intermediate must be in range 0x20 .. 0x2f');
+        }
+        res <<= 8;
+        res |= intermediate;
+      }
+    }
+    if (id.final.length !== 1) {
+      throw new Error('final must be a single byte');
+    }
+    const finalCode = id.final.charCodeAt(0);
+    if (finalRange[0] > finalCode || finalCode > finalRange[1]) {
+      throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);
+    }
+    res <<= 8;
+    res |= finalCode;
+
+    return res;
+  }
+
+  public identToString(ident: number): string {
+    const res: string[] = [];
+    while (ident) {
+      res.push(String.fromCharCode(ident & 0xFF));
+      ident >>= 8;
+    }
+    return res.reverse().join('');
+  }
+
+  public dispose(): void {
+    this._csiHandlers = Object.create(null);
+    this._executeHandlers = Object.create(null);
+    this._escHandlers = Object.create(null);
+    this._oscParser.dispose();
+    this._dcsParser.dispose();
+  }
+
+  public setPrintHandler(handler: PrintHandlerType): void {
+    this._printHandler = handler;
+  }
+  public clearPrintHandler(): void {
+    this._printHandler = this._printHandlerFb;
+  }
+
+  public addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {
+    const ident = this._identifier(id, [0x30, 0x7e]);
+    if (this._escHandlers[ident] === undefined) {
+      this._escHandlers[ident] = [];
+    }
+    const handlerList = this._escHandlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+  public setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void {
+    this._escHandlers[this._identifier(id, [0x30, 0x7e])] = [handler];
+  }
+  public clearEscHandler(id: IFunctionIdentifier): void {
+    if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];
+  }
+  public setEscHandlerFallback(handler: EscFallbackHandlerType): void {
+    this._escHandlerFb = handler;
+  }
+
+  public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {
+    this._executeHandlers[flag.charCodeAt(0)] = handler;
+  }
+  public clearExecuteHandler(flag: string): void {
+    if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];
+  }
+  public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {
+    this._executeHandlerFb = handler;
+  }
+
+  public addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {
+    const ident = this._identifier(id);
+    if (this._csiHandlers[ident] === undefined) {
+      this._csiHandlers[ident] = [];
+    }
+    const handlerList = this._csiHandlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+  public setCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): void {
+    this._csiHandlers[this._identifier(id)] = [handler];
+  }
+  public clearCsiHandler(id: IFunctionIdentifier): void {
+    if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];
+  }
+  public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {
+    this._csiHandlerFb = callback;
+  }
+
+  public addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {
+    return this._dcsParser.addHandler(this._identifier(id), handler);
+  }
+  public setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void {
+    this._dcsParser.setHandler(this._identifier(id), handler);
+  }
+  public clearDcsHandler(id: IFunctionIdentifier): void {
+    this._dcsParser.clearHandler(this._identifier(id));
+  }
+  public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {
+    this._dcsParser.setHandlerFallback(handler);
+  }
+
+  public addOscHandler(ident: number, handler: IOscHandler): IDisposable {
+    return this._oscParser.addHandler(ident, handler);
+  }
+  public setOscHandler(ident: number, handler: IOscHandler): void {
+    this._oscParser.setHandler(ident, handler);
+  }
+  public clearOscHandler(ident: number): void {
+    this._oscParser.clearHandler(ident);
+  }
+  public setOscHandlerFallback(handler: OscFallbackHandlerType): void {
+    this._oscParser.setHandlerFallback(handler);
+  }
+
+  public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {
+    this._errorHandler = callback;
+  }
+  public clearErrorHandler(): void {
+    this._errorHandler = this._errorHandlerFb;
+  }
+
+  public reset(): void {
+    this.currentState = this.initialState;
+    this._oscParser.reset();
+    this._dcsParser.reset();
+    this._params.reset();
+    this._params.addParam(0); // ZDM
+    this._collect = 0;
+    this.precedingCodepoint = 0;
+  }
+
+
+
+  /**
+   * Parse UTF32 codepoints in `data` up to `length`.
+   *
+   * Note: For several actions with high data load the parsing is optimized
+   * by using local read ahead loops with hardcoded conditions to
+   * avoid costly table lookups. Make sure that any change of table values
+   * will be reflected in the loop conditions as well and vice versa.
+   * Affected states/actions:
+   * - GROUND:PRINT
+   * - CSI_PARAM:PARAM
+   * - DCS_PARAM:PARAM
+   * - OSC_STRING:OSC_PUT
+   * - DCS_PASSTHROUGH:DCS_PUT
+   */
+  public parse(data: Uint32Array, length: number): void {
+    let code = 0;
+    let transition = 0;
+    let currentState = this.currentState;
+    const osc = this._oscParser;
+    const dcs = this._dcsParser;
+    let collect = this._collect;
+    const params = this._params;
+    const table: Uint8Array = this.TRANSITIONS.table;
+
+    // process input string
+    for (let i = 0; i < length; ++i) {
+      code = data[i];
+
+      // normal transition & action lookup
+      transition = table[currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];
+      switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {
+        case ParserAction.PRINT:
+          // read ahead with loop unrolling
+          // Note: 0x20 (SP) is included, 0x7F (DEL) is excluded
+          for (let j = i + 1; ; ++j) {
+            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+            if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
+              this._printHandler(data, i, j);
+              i = j - 1;
+              break;
+            }
+          }
+          break;
+        case ParserAction.EXECUTE:
+          if (this._executeHandlers[code]) this._executeHandlers[code]();
+          else this._executeHandlerFb(code);
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.IGNORE:
+          break;
+        case ParserAction.ERROR:
+          const inject: IParsingState = this._errorHandler(
+            {
+              position: i,
+              code,
+              currentState,
+              collect,
+              params,
+              abort: false
+            });
+          if (inject.abort) return;
+          // inject values: currently not implemented
+          break;
+        case ParserAction.CSI_DISPATCH:
+          // Trigger CSI Handler
+          const handlers = this._csiHandlers[collect << 8 | code];
+          let j = handlers ? handlers.length - 1 : -1;
+          for (; j >= 0; j--) {
+            // undefined or true means success and to stop bubbling
+            if (handlers[j](params) !== false) {
+              break;
+            }
+          }
+          if (j < 0) {
+            this._csiHandlerFb(collect << 8 | code, params);
+          }
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.PARAM:
+          // inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)
+          do {
+            switch (code) {
+              case 0x3b:
+                params.addParam(0);  // ZDM
+                break;
+              case 0x3a:
+                params.addSubParam(-1);
+                break;
+              default:  // 0x30 - 0x39
+                params.addDigit(code - 48);
+            }
+          } while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);
+          i--;
+          break;
+        case ParserAction.COLLECT:
+          collect <<= 8;
+          collect |= code;
+          break;
+        case ParserAction.ESC_DISPATCH:
+          const handlersEsc = this._escHandlers[collect << 8 | code];
+          let jj = handlersEsc ? handlersEsc.length - 1 : -1;
+          for (; jj >= 0; jj--) {
+            // undefined or true means success and to stop bubbling
+            if (handlersEsc[jj]() !== false) {
+              break;
+            }
+          }
+          if (jj < 0) {
+            this._escHandlerFb(collect << 8 | code);
+          }
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.CLEAR:
+          params.reset();
+          params.addParam(0); // ZDM
+          collect = 0;
+          break;
+        case ParserAction.DCS_HOOK:
+          dcs.hook(collect << 8 | code, params);
+          break;
+        case ParserAction.DCS_PUT:
+          // inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f
+          // unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)
+          for (let j = i + 1; ; ++j) {
+            if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {
+              dcs.put(data, i, j);
+              i = j - 1;
+              break;
+            }
+          }
+          break;
+        case ParserAction.DCS_UNHOOK:
+          dcs.unhook(code !== 0x18 && code !== 0x1a);
+          if (code === 0x1b) transition |= ParserState.ESCAPE;
+          params.reset();
+          params.addParam(0); // ZDM
+          collect = 0;
+          this.precedingCodepoint = 0;
+          break;
+        case ParserAction.OSC_START:
+          osc.start();
+          break;
+        case ParserAction.OSC_PUT:
+          // inner loop: 0x20 (SP) included, 0x7F (DEL) included
+          for (let j = i + 1; ; j++) {
+            if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code <= 0x9f)) {
+              osc.put(data, i, j);
+              i = j - 1;
+              break;
+            }
+          }
+          break;
+        case ParserAction.OSC_END:
+          osc.end(code !== 0x18 && code !== 0x1a);
+          if (code === 0x1b) transition |= ParserState.ESCAPE;
+          params.reset();
+          params.addParam(0); // ZDM
+          collect = 0;
+          this.precedingCodepoint = 0;
+          break;
+      }
+      currentState = transition & TableAccess.TRANSITION_STATE_MASK;
+    }
+
+    // save collected intermediates
+    this._collect = collect;
+
+    // save state
+    this.currentState = currentState;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/OscParser.ts b/node_modules/xterm/src/common/parser/OscParser.ts
new file mode 100644 (file)
index 0000000..e8c5a80
--- /dev/null
@@ -0,0 +1,203 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOscHandler, IHandlerCollection, OscFallbackHandlerType, IOscParser } from 'common/parser/Types';
+import { OscState, PAYLOAD_LIMIT } from 'common/parser/Constants';
+import { utf32ToString } from 'common/input/TextDecoder';
+import { IDisposable } from 'common/Types';
+
+
+export class OscParser implements IOscParser {
+  private _state = OscState.START;
+  private _id = -1;
+  private _handlers: IHandlerCollection<IOscHandler> = Object.create(null);
+  private _handlerFb: OscFallbackHandlerType = () => { };
+
+  public addHandler(ident: number, handler: IOscHandler): IDisposable {
+    if (this._handlers[ident] === undefined) {
+      this._handlers[ident] = [];
+    }
+    const handlerList = this._handlers[ident];
+    handlerList.push(handler);
+    return {
+      dispose: () => {
+        const handlerIndex = handlerList.indexOf(handler);
+        if (handlerIndex !== -1) {
+          handlerList.splice(handlerIndex, 1);
+        }
+      }
+    };
+  }
+  public setHandler(ident: number, handler: IOscHandler): void {
+    this._handlers[ident] = [handler];
+  }
+  public clearHandler(ident: number): void {
+    if (this._handlers[ident]) delete this._handlers[ident];
+  }
+  public setHandlerFallback(handler: OscFallbackHandlerType): void {
+    this._handlerFb = handler;
+  }
+
+  public dispose(): void {
+    this._handlers = Object.create(null);
+    this._handlerFb = () => {};
+  }
+
+  public reset(): void {
+    // cleanup handlers if payload was already sent
+    if (this._state === OscState.PAYLOAD) {
+      this.end(false);
+    }
+    this._id = -1;
+    this._state = OscState.START;
+  }
+
+  private _start(): void {
+    const handlers = this._handlers[this._id];
+    if (!handlers) {
+      this._handlerFb(this._id, 'START');
+    } else {
+      for (let j = handlers.length - 1; j >= 0; j--) {
+        handlers[j].start();
+      }
+    }
+  }
+
+  private _put(data: Uint32Array, start: number, end: number): void {
+    const handlers = this._handlers[this._id];
+    if (!handlers) {
+      this._handlerFb(this._id, 'PUT', utf32ToString(data, start, end));
+    } else {
+      for (let j = handlers.length - 1; j >= 0; j--) {
+        handlers[j].put(data, start, end);
+      }
+    }
+  }
+
+  private _end(success: boolean): void {
+    // other than the old code we always have to call .end
+    // to keep the bubbling we use `success` to indicate
+    // whether a handler should execute
+    const handlers = this._handlers[this._id];
+    if (!handlers) {
+      this._handlerFb(this._id, 'END', success);
+    } else {
+      let j = handlers.length - 1;
+      for (; j >= 0; j--) {
+        if (handlers[j].end(success) !== false) {
+          break;
+        }
+      }
+      j--;
+      // cleanup left over handlers
+      for (; j >= 0; j--) {
+        handlers[j].end(false);
+      }
+    }
+  }
+
+  public start(): void {
+    // always reset leftover handlers
+    this.reset();
+    this._id = -1;
+    this._state = OscState.ID;
+  }
+
+  /**
+   * Put data to current OSC command.
+   * Expects the identifier of the OSC command in the form
+   * OSC id ; payload ST/BEL
+   * Payload chunks are not further processed and get
+   * directly passed to the handlers.
+   */
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (this._state === OscState.ABORT) {
+      return;
+    }
+    if (this._state === OscState.ID) {
+      while (start < end) {
+        const code = data[start++];
+        if (code === 0x3b) {
+          this._state = OscState.PAYLOAD;
+          this._start();
+          break;
+        }
+        if (code < 0x30 || 0x39 < code) {
+          this._state = OscState.ABORT;
+          return;
+        }
+        if (this._id === -1) {
+          this._id = 0;
+        }
+        this._id = this._id * 10 + code - 48;
+      }
+    }
+    if (this._state === OscState.PAYLOAD && end - start > 0) {
+      this._put(data, start, end);
+    }
+  }
+
+  /**
+   * Indicates end of an OSC command.
+   * Whether the OSC got aborted or finished normally
+   * is indicated by `success`.
+   */
+  public end(success: boolean): void {
+    if (this._state === OscState.START) {
+      return;
+    }
+    // do nothing if command was faulty
+    if (this._state !== OscState.ABORT) {
+      // if we are still in ID state and get an early end
+      // means that the command has no payload thus we still have
+      // to announce START and send END right after
+      if (this._state === OscState.ID) {
+        this._start();
+      }
+      this._end(success);
+    }
+    this._id = -1;
+    this._state = OscState.START;
+  }
+}
+
+/**
+ * Convenient class to allow attaching string based handler functions
+ * as OSC handlers.
+ */
+export class OscHandler implements IOscHandler {
+  private _data = '';
+  private _hitLimit: boolean = false;
+
+  constructor(private _handler: (data: string) => any) {}
+
+  public start(): void {
+    this._data = '';
+    this._hitLimit = false;
+  }
+
+  public put(data: Uint32Array, start: number, end: number): void {
+    if (this._hitLimit) {
+      return;
+    }
+    this._data += utf32ToString(data, start, end);
+    if (this._data.length > PAYLOAD_LIMIT) {
+      this._data = '';
+      this._hitLimit = true;
+    }
+  }
+
+  public end(success: boolean): any {
+    let ret;
+    if (this._hitLimit) {
+      ret = false;
+    } else if (success) {
+      ret = this._handler(this._data);
+    }
+    this._data = '';
+    this._hitLimit = false;
+    return ret;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/Params.ts b/node_modules/xterm/src/common/parser/Params.ts
new file mode 100644 (file)
index 0000000..47ee129
--- /dev/null
@@ -0,0 +1,229 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+import { IParams, ParamsArray } from 'common/parser/Types';
+
+// max value supported for a single param/subparam (clamped to positive int32 range)
+const MAX_VALUE = 0x7FFFFFFF;
+// max allowed subparams for a single sequence (hardcoded limitation)
+const MAX_SUBPARAMS = 256;
+
+/**
+ * Params storage class.
+ * This type is used by the parser to accumulate sequence parameters and sub parameters
+ * and transmit them to the input handler actions.
+ *
+ * NOTES:
+ *  - params object for action handlers is borrowed, use `.toArray` or `.clone` to get a copy
+ *  - never read beyond `params.length - 1` (likely to contain arbitrary data)
+ *  - `.getSubParams` returns a borrowed typed array, use `.getSubParamsAll` for cloned sub params
+ *  - hardcoded limitations:
+ *    - max. value for a single (sub) param is 2^31 - 1 (greater values are clamped to that)
+ *    - max. 256 sub params possible
+ *    - negative values are not allowed beside -1 (placeholder for default value)
+ *
+ * About ZDM (Zero Default Mode):
+ * ZDM is not orchestrated by this class. If the parser is in ZDM,
+ * it should add 0 for empty params, otherwise -1. This does not apply
+ * to subparams, empty subparams should always be added with -1.
+ */
+export class Params implements IParams {
+  // params store and length
+  public params: Int32Array;
+  public length: number;
+
+  // sub params store and length
+  protected _subParams: Int32Array;
+  protected _subParamsLength: number;
+
+  // sub params offsets from param: param idx --> [start, end] offset
+  private _subParamsIdx: Uint16Array;
+  private _rejectDigits: boolean;
+  private _rejectSubDigits: boolean;
+  private _digitIsSub: boolean;
+
+  /**
+   * Create a `Params` type from JS array representation.
+   */
+  public static fromArray(values: ParamsArray): Params {
+    const params = new Params();
+    if (!values.length) {
+      return params;
+    }
+    // skip leading sub params
+    for (let i = (values[0] instanceof Array) ? 1 : 0; i < values.length; ++i) {
+      const value = values[i];
+      if (value instanceof Array) {
+        for (let k = 0; k < value.length; ++k) {
+          params.addSubParam(value[k]);
+        }
+      } else {
+        params.addParam(value);
+      }
+    }
+    return params;
+  }
+
+  /**
+   * @param maxLength max length of storable parameters
+   * @param maxSubParamsLength max length of storable sub parameters
+   */
+  constructor(public maxLength: number = 32, public maxSubParamsLength: number = 32) {
+    if (maxSubParamsLength > MAX_SUBPARAMS) {
+      throw new Error('maxSubParamsLength must not be greater than 256');
+    }
+    this.params = new Int32Array(maxLength);
+    this.length = 0;
+    this._subParams = new Int32Array(maxSubParamsLength);
+    this._subParamsLength = 0;
+    this._subParamsIdx = new Uint16Array(maxLength);
+    this._rejectDigits = false;
+    this._rejectSubDigits = false;
+    this._digitIsSub = false;
+  }
+
+  /**
+   * Clone object.
+   */
+  public clone(): Params {
+    const newParams = new Params(this.maxLength, this.maxSubParamsLength);
+    newParams.params.set(this.params);
+    newParams.length = this.length;
+    newParams._subParams.set(this._subParams);
+    newParams._subParamsLength = this._subParamsLength;
+    newParams._subParamsIdx.set(this._subParamsIdx);
+    newParams._rejectDigits = this._rejectDigits;
+    newParams._rejectSubDigits = this._rejectSubDigits;
+    newParams._digitIsSub = this._digitIsSub;
+    return newParams;
+  }
+
+  /**
+   * Get a JS array representation of the current parameters and sub parameters.
+   * The array is structured as follows:
+   *    sequence: "1;2:3:4;5::6"
+   *    array   : [1, 2, [3, 4], 5, [-1, 6]]
+   */
+  public toArray(): ParamsArray {
+    const res: ParamsArray = [];
+    for (let i = 0; i < this.length; ++i) {
+      res.push(this.params[i]);
+      const start = this._subParamsIdx[i] >> 8;
+      const end = this._subParamsIdx[i] & 0xFF;
+      if (end - start > 0) {
+        res.push(Array.prototype.slice.call(this._subParams, start, end));
+      }
+    }
+    return res;
+  }
+
+  /**
+   * Reset to initial empty state.
+   */
+  public reset(): void {
+    this.length = 0;
+    this._subParamsLength = 0;
+    this._rejectDigits = false;
+    this._rejectSubDigits = false;
+    this._digitIsSub = false;
+  }
+
+  /**
+   * Add a parameter value.
+   * `Params` only stores up to `maxLength` parameters, any later
+   * parameter will be ignored.
+   * Note: VT devices only stored up to 16 values, xterm seems to
+   * store up to 30.
+   */
+  public addParam(value: number): void {
+    this._digitIsSub = false;
+    if (this.length >= this.maxLength) {
+      this._rejectDigits = true;
+      return;
+    }
+    if (value < -1) {
+      throw new Error('values lesser than -1 are not allowed');
+    }
+    this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength;
+    this.params[this.length++] = value > MAX_VALUE ? MAX_VALUE : value;
+  }
+
+  /**
+   * Add a sub parameter value.
+   * The sub parameter is automatically associated with the last parameter value.
+   * Thus it is not possible to add a subparameter without any parameter added yet.
+   * `Params` only stores up to `subParamsLength` sub parameters, any later
+   * sub parameter will be ignored.
+   */
+  public addSubParam(value: number): void {
+    this._digitIsSub = true;
+    if (!this.length) {
+      return;
+    }
+    if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) {
+      this._rejectSubDigits = true;
+      return;
+    }
+    if (value < -1) {
+      throw new Error('values lesser than -1 are not allowed');
+    }
+    this._subParams[this._subParamsLength++] = value > MAX_VALUE ? MAX_VALUE : value;
+    this._subParamsIdx[this.length - 1]++;
+  }
+
+  /**
+   * Whether parameter at index `idx` has sub parameters.
+   */
+  public hasSubParams(idx: number): boolean {
+    return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);
+  }
+
+  /**
+   * Return sub parameters for parameter at index `idx`.
+   * Note: The values are borrowed, thus you need to copy
+   * the values if you need to hold them in nonlocal scope.
+   */
+  public getSubParams(idx: number): Int32Array | null {
+    const start = this._subParamsIdx[idx] >> 8;
+    const end = this._subParamsIdx[idx] & 0xFF;
+    if (end - start > 0) {
+      return this._subParams.subarray(start, end);
+    }
+    return null;
+  }
+
+  /**
+   * Return all sub parameters as {idx: subparams} mapping.
+   * Note: The values are not borrowed.
+   */
+  public getSubParamsAll(): {[idx: number]: Int32Array} {
+    const result: {[idx: number]: Int32Array} = {};
+    for (let i = 0; i < this.length; ++i) {
+      const start = this._subParamsIdx[i] >> 8;
+      const end = this._subParamsIdx[i] & 0xFF;
+      if (end - start > 0) {
+        result[i] = this._subParams.slice(start, end);
+      }
+    }
+    return result;
+  }
+
+  /**
+   * Add a single digit value to current parameter.
+   * This is used by the parser to account digits on a char by char basis.
+   */
+  public addDigit(value: number): void {
+    let length;
+    if (this._rejectDigits
+      || !(length = this._digitIsSub ? this._subParamsLength : this.length)
+      || (this._digitIsSub && this._rejectSubDigits)
+    ) {
+      return;
+    }
+
+    const store = this._digitIsSub ? this._subParams : this.params;
+    const cur = store[length - 1];
+    store[length - 1] = ~cur ? Math.min(cur * 10 + value, MAX_VALUE) : value;
+  }
+}
diff --git a/node_modules/xterm/src/common/parser/Types.d.ts b/node_modules/xterm/src/common/parser/Types.d.ts
new file mode 100644 (file)
index 0000000..e2fac89
--- /dev/null
@@ -0,0 +1,244 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IDisposable } from 'common/Types';
+import { ParserState } from 'common/parser/Constants';
+
+/** sequence params serialized to js arrays */
+export type ParamsArray = (number | number[])[];
+
+/** Params constructor type. */
+export interface IParamsConstructor {
+  new(maxLength: number, maxSubParamsLength: number): IParams;
+
+  /** create params from ParamsArray */
+  fromArray(values: ParamsArray): IParams;
+}
+
+/** Interface of Params storage class. */
+export interface IParams {
+  /** from ctor */
+  maxLength: number;
+  maxSubParamsLength: number;
+
+  /** param values and its length */
+  params: Int32Array;
+  length: number;
+
+  /** methods */
+  clone(): IParams;
+  toArray(): ParamsArray;
+  reset(): void;
+  addParam(value: number): void;
+  addSubParam(value: number): void;
+  hasSubParams(idx: number): boolean;
+  getSubParams(idx: number): Int32Array | null;
+  getSubParamsAll(): {[idx: number]: Int32Array};
+}
+
+/**
+ * Internal state of EscapeSequenceParser.
+ * Used as argument of the error handler to allow
+ * introspection at runtime on parse errors.
+ * Return it with altered values to recover from
+ * faulty states (not yet supported).
+ * Set `abort` to `true` to abort the current parsing.
+ */
+export interface IParsingState {
+  // position in parse string
+  position: number;
+  // actual character code
+  code: number;
+  // current parser state
+  currentState: ParserState;
+  // collect buffer with intermediate characters
+  collect: number;
+  // params buffer
+  params: IParams;
+  // should abort (default: false)
+  abort: boolean;
+}
+
+/**
+ * Command handler interfaces.
+ */
+
+/**
+ * CSI handler types.
+ * Note: `params` is borrowed.
+ */
+export type CsiHandlerType = (params: IParams) => boolean | void;
+export type CsiFallbackHandlerType = (ident: number, params: IParams) => void;
+
+/**
+ * DCS handler types.
+ */
+export interface IDcsHandler {
+  /**
+   * Called when a DCS command starts.
+   * Prepare needed data structures here.
+   * Note: `params` is borrowed.
+   */
+  hook(params: IParams): void;
+  /**
+   * Incoming payload chunk.
+   * Note: `params` is borrowed.
+   */
+  put(data: Uint32Array, start: number, end: number): void;
+  /**
+   * End of DCS command. `success` indicates whether the
+   * command finished normally or got aborted, thus final
+   * execution of the command should depend on `success`.
+   * To save memory also cleanup data structures here.
+   */
+  unhook(success: boolean): void | boolean;
+}
+export type DcsFallbackHandlerType = (ident: number, action: 'HOOK' | 'PUT' | 'UNHOOK', payload?: any) => void;
+
+/**
+ * ESC handler types.
+ */
+export type EscHandlerType = () => boolean | void;
+export type EscFallbackHandlerType = (identifier: number) => void;
+
+/**
+ * EXECUTE handler types.
+ */
+export type ExecuteHandlerType = () => boolean | void;
+export type ExecuteFallbackHandlerType = (ident: number) => void;
+
+/**
+ * OSC handler types.
+ */
+export interface IOscHandler {
+  /**
+   * Announces start of this OSC command.
+   * Prepare needed data structures here.
+   */
+  start(): void;
+  /**
+   * Incoming data chunk.
+   * Note: Data is borrowed.
+   */
+  put(data: Uint32Array, start: number, end: number): void;
+  /**
+   * End of OSC command. `success` indicates whether the
+   * command finished normally or got aborted, thus final
+   * execution of the command should depend on `success`.
+   * To save memory also cleanup data structures here.
+   */
+  end(success: boolean): void | boolean;
+}
+export type OscFallbackHandlerType = (ident: number, action: 'START' | 'PUT' | 'END', payload?: any) => void;
+
+/**
+ * PRINT handler types.
+ */
+export type PrintHandlerType = (data: Uint32Array, start: number, end: number) => void;
+export type PrintFallbackHandlerType = PrintHandlerType;
+
+
+/**
+* EscapeSequenceParser interface.
+*/
+export interface IEscapeSequenceParser extends IDisposable {
+  /**
+   * Preceding codepoint to get REP working correctly.
+   * This must be set by the print handler as last action.
+   * It gets reset by the parser for any valid sequence beside REP itself.
+   */
+  precedingCodepoint: number;
+
+  /**
+   * Reset the parser to its initial state (handlers are kept).
+   */
+  reset(): void;
+
+  /**
+   * Parse UTF32 codepoints in `data` up to `length`.
+   * @param data The data to parse.
+   */
+  parse(data: Uint32Array, length: number): void;
+
+  /**
+   * Get string from numercial function identifier `ident`.
+   * Useful in fallback handlers which expose the low level
+   * numcerical function identifier for debugging purposes.
+   * Note: A full back translation to `IFunctionIdentifier`
+   * is not implemented.
+   */
+  identToString(ident: number): string;
+
+  setPrintHandler(handler: PrintHandlerType): void;
+  clearPrintHandler(): void;
+
+  setEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): void;
+  clearEscHandler(id: IFunctionIdentifier): void;
+  setEscHandlerFallback(handler: EscFallbackHandlerType): void;
+  addEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable;
+
+  setExecuteHandler(flag: string, handler: ExecuteHandlerType): void;
+  clearExecuteHandler(flag: string): void;
+  setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void;
+
+  setCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): void;
+  clearCsiHandler(id: IFunctionIdentifier): void;
+  setCsiHandlerFallback(callback: CsiFallbackHandlerType): void;
+  addCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable;
+
+  setDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): void;
+  clearDcsHandler(id: IFunctionIdentifier): void;
+  setDcsHandlerFallback(handler: DcsFallbackHandlerType): void;
+  addDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable;
+
+  setOscHandler(ident: number, handler: IOscHandler): void;
+  clearOscHandler(ident: number): void;
+  setOscHandlerFallback(handler: OscFallbackHandlerType): void;
+  addOscHandler(ident: number, handler: IOscHandler): IDisposable;
+
+  setErrorHandler(handler: (state: IParsingState) => IParsingState): void;
+  clearErrorHandler(): void;
+}
+
+/**
+ * Subparser interfaces.
+ * The subparsers are instantiated in `EscapeSequenceParser` and
+ * called during `EscapeSequenceParser.parse`.
+ */
+export interface ISubParser<T, U> extends IDisposable {
+  reset(): void;
+  addHandler(ident: number, handler: T): IDisposable;
+  setHandler(ident: number, handler: T): void;
+  clearHandler(ident: number): void;
+  setHandlerFallback(handler: U): void;
+  put(data: Uint32Array, start: number, end: number): void;
+}
+
+export interface IOscParser extends ISubParser<IOscHandler, OscFallbackHandlerType> {
+  start(): void;
+  end(success: boolean): void;
+}
+
+export interface IDcsParser extends ISubParser<IDcsHandler, DcsFallbackHandlerType> {
+  hook(ident: number, params: IParams): void;
+  unhook(success: boolean): void;
+}
+
+/**
+ * Interface to denote a specific ESC, CSI or DCS handler slot.
+ * The values are used to create an integer respresentation during handler
+ * regristation before passed to the subparsers as `ident`.
+ * The integer translation is made to allow a faster handler access
+ * in `EscapeSequenceParser.parse`.
+ */
+export interface IFunctionIdentifier {
+  prefix?: string;
+  intermediates?: string;
+  final: string;
+}
+
+export interface IHandlerCollection<T> {
+  [key: string]: T[];
+}
diff --git a/node_modules/xterm/src/common/services/BufferService.ts b/node_modules/xterm/src/common/services/BufferService.ts
new file mode 100644 (file)
index 0000000..c7b6afc
--- /dev/null
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferService, IOptionsService } from 'common/services/Services';
+import { BufferSet } from 'common/buffer/BufferSet';
+import { IBufferSet, IBuffer } from 'common/buffer/Types';
+
+export const MINIMUM_COLS = 2; // Less than 2 can mess with wide chars
+export const MINIMUM_ROWS = 1;
+
+export class BufferService implements IBufferService {
+  serviceBrand: any;
+
+  public cols: number;
+  public rows: number;
+  public buffers: IBufferSet;
+
+  public get buffer(): IBuffer { return this.buffers.active; }
+
+  constructor(
+    @IOptionsService private _optionsService: IOptionsService
+  ) {
+    this.cols = Math.max(_optionsService.options.cols, MINIMUM_COLS);
+    this.rows = Math.max(_optionsService.options.rows, MINIMUM_ROWS);
+    this.buffers = new BufferSet(_optionsService, this);
+  }
+
+  public resize(cols: number, rows: number): void {
+    this.cols = cols;
+    this.rows = rows;
+  }
+
+  public reset(): void {
+    this.buffers = new BufferSet(this._optionsService, this);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/CoreMouseService.ts b/node_modules/xterm/src/common/services/CoreMouseService.ts
new file mode 100644 (file)
index 0000000..500655b
--- /dev/null
@@ -0,0 +1,296 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+import { IBufferService, ICoreService, ICoreMouseService } from 'common/services/Services';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { ICoreMouseProtocol, ICoreMouseEvent, CoreMouseEncoding, CoreMouseEventType, CoreMouseButton, CoreMouseAction } from 'common/Types';
+
+/**
+ * Supported default protocols.
+ */
+const DEFAULT_PROTOCOLS: {[key: string]: ICoreMouseProtocol} = {
+  /**
+   * NONE
+   * Events: none
+   * Modifiers: none
+   */
+  NONE: {
+    events: CoreMouseEventType.NONE,
+    restrict: () => false
+  },
+  /**
+   * X10
+   * Events: mousedown
+   * Modifiers: none
+   */
+  X10: {
+    events: CoreMouseEventType.DOWN,
+    restrict: (e: ICoreMouseEvent) => {
+      // no wheel, no move, no up
+      if (e.button === CoreMouseButton.WHEEL || e.action !== CoreMouseAction.DOWN) {
+        return false;
+      }
+      // no modifiers
+      e.ctrl = false;
+      e.alt = false;
+      e.shift = false;
+      return true;
+    }
+  },
+  /**
+   * VT200
+   * Events: mousedown / mouseup / wheel
+   * Modifiers: all
+   */
+  VT200: {
+    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL,
+    restrict: (e: ICoreMouseEvent) => {
+      // no move
+      if (e.action === CoreMouseAction.MOVE) {
+        return false;
+      }
+      return true;
+    }
+  },
+  /**
+   * DRAG
+   * Events: mousedown / mouseup / wheel / mousedrag
+   * Modifiers: all
+   */
+  DRAG: {
+    events: CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL | CoreMouseEventType.DRAG,
+    restrict: (e: ICoreMouseEvent) => {
+      // no move without button
+      if (e.action === CoreMouseAction.MOVE && e.button === CoreMouseButton.NONE) {
+        return false;
+      }
+      return true;
+    }
+  },
+  /**
+   * ANY
+   * Events: all mouse related events
+   * Modifiers: all
+   */
+  ANY: {
+    events:
+      CoreMouseEventType.DOWN | CoreMouseEventType.UP | CoreMouseEventType.WHEEL
+      | CoreMouseEventType.DRAG | CoreMouseEventType.MOVE,
+    restrict: (e: ICoreMouseEvent) => true
+  }
+};
+
+const enum Modifiers {
+  SHIFT = 4,
+  ALT = 8,
+  CTRL = 16
+}
+
+// helper for default encoders to generate the event code.
+function eventCode(e: ICoreMouseEvent, isSGR: boolean): number {
+  let code = (e.ctrl ? Modifiers.CTRL : 0) | (e.shift ? Modifiers.SHIFT : 0) | (e.alt ? Modifiers.ALT : 0);
+  if (e.button === CoreMouseButton.WHEEL) {
+    code |= 64;
+    code |= e.action;
+  } else {
+    code |= e.button & 3;
+    if (e.button & 4) {
+      code |= 64;
+    }
+    if (e.button & 8) {
+      code |= 128;
+    }
+    if (e.action === CoreMouseAction.MOVE) {
+      code |= CoreMouseAction.MOVE;
+    } else if (e.action === CoreMouseAction.UP && !isSGR) {
+      // special case - only SGR can report button on release
+      // all others have to go with NONE
+      code |= CoreMouseButton.NONE;
+    }
+  }
+  return code;
+}
+
+const S = String.fromCharCode;
+
+/**
+ * Supported default encodings.
+ */
+const DEFAULT_ENCODINGS: {[key: string]: CoreMouseEncoding} = {
+  /**
+   * DEFAULT - CSI M Pb Px Py
+   * Single byte encoding for coords and event code.
+   * Can encode values up to 223. The Encoding of higher
+   * values is not UTF-8 compatible (and currently limited
+   * to 95 in xterm.js).
+   */
+  DEFAULT: (e: ICoreMouseEvent) => {
+    let params = [eventCode(e, false) + 32, e.col + 32, e.row + 32];
+    // FIXME: we are currently limited to ASCII range
+    params = params.map(v => (v > 127) ? 127 : v);
+    // FIXED: params = params.map(v => (v > 255) ? 0 : value);
+    return `\x1b[M${S(params[0])}${S(params[1])}${S(params[2])}`;
+  },
+  /**
+   * SGR - CSI < Pb ; Px ; Py M|m
+   * No encoding limitation.
+   * Can report button on release and works with a well formed sequence.
+   */
+  SGR: (e: ICoreMouseEvent) => {
+    const final = (e.action === CoreMouseAction.UP && e.button !== CoreMouseButton.WHEEL) ? 'm' : 'M';
+    return `\x1b[<${eventCode(e, true)};${e.col};${e.row}${final}`;
+  }
+};
+
+/**
+ * CoreMouseService
+ *
+ * Provides mouse tracking reports with different protocols and encodings.
+ *  - protocols: NONE (default), X10, VT200, DRAG, ANY
+ *  - encodings: DEFAULT, SGR (UTF8, URXVT removed in #2507)
+ *
+ * Custom protocols/encodings can be added by `addProtocol` / `addEncoding`.
+ * To activate a protocol/encoding, set `activeProtocol` / `activeEncoding`.
+ * Switching a protocol will send a notification event `onProtocolChange`
+ * with a list of needed events to track.
+ *
+ * The service handles the mouse tracking state and decides whether to send
+ * a tracking report to the backend based on protocol and encoding limitations.
+ * To send a mouse event call `triggerMouseEvent`.
+ */
+export class CoreMouseService implements ICoreMouseService {
+  private _protocols: {[name: string]: ICoreMouseProtocol} = {};
+  private _encodings: {[name: string]: CoreMouseEncoding} = {};
+  private _activeProtocol: string = '';
+  private _activeEncoding: string = '';
+  private _onProtocolChange = new EventEmitter<CoreMouseEventType>();
+  private _lastEvent: ICoreMouseEvent | null = null;
+
+  constructor(
+    @IBufferService private readonly _bufferService: IBufferService,
+    @ICoreService private readonly _coreService: ICoreService
+  ) {
+    // register default protocols and encodings
+    Object.keys(DEFAULT_PROTOCOLS).forEach(name => this.addProtocol(name, DEFAULT_PROTOCOLS[name]));
+    Object.keys(DEFAULT_ENCODINGS).forEach(name => this.addEncoding(name, DEFAULT_ENCODINGS[name]));
+    // call reset to set defaults
+    this.reset();
+  }
+
+  public addProtocol(name: string, protocol: ICoreMouseProtocol): void {
+    this._protocols[name] = protocol;
+  }
+
+  public addEncoding(name: string, encoding: CoreMouseEncoding): void {
+    this._encodings[name] = encoding;
+  }
+
+  public get activeProtocol(): string {
+    return this._activeProtocol;
+  }
+
+  public set activeProtocol(name: string) {
+    if (!this._protocols[name]) {
+      throw new Error(`unknown protocol "${name}"`);
+    }
+    this._activeProtocol = name;
+    this._onProtocolChange.fire(this._protocols[name].events);
+  }
+
+  public get activeEncoding(): string {
+    return this._activeEncoding;
+  }
+
+  public set activeEncoding(name: string) {
+    if (!this._encodings[name]) {
+      throw new Error(`unknown encoding "${name}"`);
+    }
+    this._activeEncoding = name;
+  }
+
+  public reset(): void {
+    this.activeProtocol = 'NONE';
+    this.activeEncoding = 'DEFAULT';
+    this._lastEvent = null;
+  }
+
+  /**
+   * Event to announce changes in mouse tracking.
+   */
+  public get onProtocolChange(): IEvent<CoreMouseEventType> {
+    return this._onProtocolChange.event;
+  }
+
+  /**
+   * Triggers a mouse event to be sent.
+   *
+   * Returns true if the event passed all protocol restrictions and a report
+   * was sent, otherwise false. The return value may be used to decide whether
+   * the default event action in the bowser component should be omitted.
+   *
+   * Note: The method will change values of the given event object
+   * to fullfill protocol and encoding restrictions.
+   */
+  public triggerMouseEvent(e: ICoreMouseEvent): boolean {
+    // range check for col/row
+    if (e.col < 0 || e.col >= this._bufferService.cols
+        || e.row < 0 || e.row >= this._bufferService.rows) {
+      return false;
+    }
+
+    // filter nonsense combinations of button + action
+    if (e.button === CoreMouseButton.WHEEL && e.action === CoreMouseAction.MOVE) {
+      return false;
+    }
+    if (e.button === CoreMouseButton.NONE && e.action !== CoreMouseAction.MOVE) {
+      return false;
+    }
+    if (e.button !== CoreMouseButton.WHEEL && (e.action === CoreMouseAction.LEFT || e.action === CoreMouseAction.RIGHT)) {
+      return false;
+    }
+
+    // report 1-based coords
+    e.col++;
+    e.row++;
+
+    // debounce move at grid level
+    if (e.action === CoreMouseAction.MOVE && this._lastEvent && this._compareEvents(this._lastEvent, e)) {
+      return false;
+    }
+
+    // apply protocol restrictions
+    if (!this._protocols[this._activeProtocol].restrict(e)) {
+      return false;
+    }
+
+    // encode report and send
+    const report = this._encodings[this._activeEncoding](e);
+    this._coreService.triggerDataEvent(report, true);
+
+    this._lastEvent = e;
+
+    return true;
+  }
+
+  public explainEvents(events: CoreMouseEventType): {[event: string]: boolean} {
+    return {
+      DOWN: !!(events & CoreMouseEventType.DOWN),
+      UP: !!(events & CoreMouseEventType.UP),
+      DRAG: !!(events & CoreMouseEventType.DRAG),
+      MOVE: !!(events & CoreMouseEventType.MOVE),
+      WHEEL: !!(events & CoreMouseEventType.WHEEL)
+    };
+  }
+
+  private _compareEvents(e1: ICoreMouseEvent, e2: ICoreMouseEvent): boolean {
+    if (e1.col !== e2.col) return false;
+    if (e1.row !== e2.row) return false;
+    if (e1.button !== e2.button) return false;
+    if (e1.action !== e2.action) return false;
+    if (e1.ctrl !== e2.ctrl) return false;
+    if (e1.alt !== e2.alt) return false;
+    if (e1.shift !== e2.shift) return false;
+    return true;
+  }
+}
diff --git a/node_modules/xterm/src/common/services/CoreService.ts b/node_modules/xterm/src/common/services/CoreService.ts
new file mode 100644 (file)
index 0000000..0e0ba60
--- /dev/null
@@ -0,0 +1,60 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ICoreService, ILogService, IOptionsService, IBufferService } from 'common/services/Services';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { IDecPrivateModes } from 'common/Types';
+import { clone } from 'common/Clone';
+
+const DEFAULT_DEC_PRIVATE_MODES: IDecPrivateModes = Object.freeze({
+  applicationCursorKeys: false
+});
+
+export class CoreService implements ICoreService {
+  serviceBrand: any;
+
+  public decPrivateModes: IDecPrivateModes;
+
+  private _onData = new EventEmitter<string>();
+  public get onData(): IEvent<string> { return this._onData.event; }
+  private _onUserInput = new EventEmitter<void>();
+  public get onUserInput(): IEvent<void> { return this._onUserInput.event; }
+
+  constructor(
+    // TODO: Move this into a service
+    private readonly _scrollToBottom: () => void,
+    @IBufferService private readonly _bufferService: IBufferService,
+    @ILogService private readonly _logService: ILogService,
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);
+  }
+
+  public reset(): void {
+    this.decPrivateModes = clone(DEFAULT_DEC_PRIVATE_MODES);
+  }
+
+  public triggerDataEvent(data: string, wasUserInput: boolean = false): void {
+    // Prevents all events to pty process if stdin is disabled
+    if (this._optionsService.options.disableStdin) {
+      return;
+    }
+
+    // Input is being sent to the terminal, the terminal should focus the prompt.
+    const buffer = this._bufferService.buffer;
+    if (buffer.ybase !== buffer.ydisp) {
+      this._scrollToBottom();
+    }
+
+    // Fire onUserInput so listeners can react as well (eg. clear selection)
+    if (wasUserInput) {
+      this._onUserInput.fire();
+    }
+
+    // Fire onData API
+    this._logService.debug(`sending data "${data}"`, () => data.split('').map(e => e.charCodeAt(0)));
+    this._onData.fire(data);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/DirtyRowService.ts b/node_modules/xterm/src/common/services/DirtyRowService.ts
new file mode 100644 (file)
index 0000000..0f2f14f
--- /dev/null
@@ -0,0 +1,53 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IBufferService, IDirtyRowService } from 'common/services/Services';
+
+export class DirtyRowService implements IDirtyRowService {
+  serviceBrand: any;
+
+  private _start!: number;
+  private _end!: number;
+
+  public get start(): number { return this._start; }
+  public get end(): number { return this._end; }
+
+  constructor(
+    @IBufferService private readonly _bufferService: IBufferService
+  ) {
+    this.clearRange();
+  }
+
+  public clearRange(): void {
+    this._start = this._bufferService.buffer.y;
+    this._end = this._bufferService.buffer.y;
+  }
+
+  public markDirty(y: number): void {
+    if (y < this._start) {
+      this._start = y;
+    } else if (y > this._end) {
+      this._end = y;
+    }
+  }
+
+  public markRangeDirty(y1: number, y2: number): void {
+    if (y1 > y2) {
+      const temp = y1;
+      y1 = y2;
+      y2 = temp;
+    }
+    if (y1 < this._start) {
+      this._start = y1;
+    }
+    if (y2 > this._end) {
+      this._end = y2;
+    }
+  }
+
+  public markAllDirty(): void {
+    this.markRangeDirty(0, this._bufferService.rows - 1);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/InstantiationService.ts b/node_modules/xterm/src/common/services/InstantiationService.ts
new file mode 100644 (file)
index 0000000..abce8ac
--- /dev/null
@@ -0,0 +1,77 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ *
+ * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).
+ */
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *  Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+
+import { IInstantiationService, IServiceIdentifier } from 'common/services/Services';
+import { getServiceDependencies } from 'common/services/ServiceRegistry';
+
+export class ServiceCollection {
+
+  private _entries = new Map<IServiceIdentifier<any>, any>();
+
+  constructor(...entries: [IServiceIdentifier<any>, any][]) {
+    for (const [id, service] of entries) {
+      this.set(id, service);
+    }
+  }
+
+  set<T>(id: IServiceIdentifier<T>, instance: T): T {
+    const result = this._entries.get(id);
+    this._entries.set(id, instance);
+    return result;
+  }
+
+  forEach(callback: (id: IServiceIdentifier<any>, instance: any) => any): void {
+    this._entries.forEach((value, key) => callback(key, value));
+  }
+
+  has(id: IServiceIdentifier<any>): boolean {
+    return this._entries.has(id);
+  }
+
+  get<T>(id: IServiceIdentifier<T>): T {
+    return this._entries.get(id);
+  }
+}
+
+export class InstantiationService implements IInstantiationService {
+  private readonly _services: ServiceCollection = new ServiceCollection();
+
+  constructor() {
+    this._services.set(IInstantiationService, this);
+  }
+
+  public setService<T>(id: IServiceIdentifier<T>, instance: T): void {
+    this._services.set(id, instance);
+  }
+
+  public createInstance<T>(ctor: any, ...args: any[]): any {
+    const serviceDependencies = getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
+
+    const serviceArgs: any[] = [];
+    for (const dependency of serviceDependencies) {
+      const service = this._services.get(dependency.id);
+      if (!service) {
+        throw new Error(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`);
+      }
+      serviceArgs.push(service);
+    }
+
+    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
+
+    // check for argument mismatches, adjust static args if needed
+    if (args.length !== firstServiceArgPos) {
+      throw new Error(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
+    }
+
+    // now create the instance
+    return <T>new ctor(...[...args, ...serviceArgs]);
+  }
+}
diff --git a/node_modules/xterm/src/common/services/LogService.ts b/node_modules/xterm/src/common/services/LogService.ts
new file mode 100644 (file)
index 0000000..4f48d8f
--- /dev/null
@@ -0,0 +1,97 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ILogService, IOptionsService } from 'common/services/Services';
+
+type LogType = (message?: any, ...optionalParams: any[]) => void;
+
+interface IConsole {
+  log: LogType;
+  error: LogType;
+  info: LogType;
+  trace: LogType;
+  warn: LogType;
+}
+
+// console is available on both node.js and browser contexts but the common
+// module doesn't depend on them so we need to explicitly declare it.
+declare const console: IConsole;
+
+
+export enum LogLevel {
+  DEBUG = 0,
+  INFO = 1,
+  WARN = 2,
+  ERROR = 3,
+  OFF = 4
+}
+
+const optionsKeyToLogLevel: { [key: string]: LogLevel } = {
+  debug: LogLevel.DEBUG,
+  info: LogLevel.INFO,
+  warn: LogLevel.WARN,
+  error: LogLevel.ERROR,
+  off: LogLevel.OFF
+};
+
+const LOG_PREFIX = 'xterm.js: ';
+
+export class LogService implements ILogService {
+  serviceBrand: any;
+
+  private _logLevel!: LogLevel;
+
+  constructor(
+    @IOptionsService private readonly _optionsService: IOptionsService
+  ) {
+    this._updateLogLevel();
+    this._optionsService.onOptionChange(key => {
+      if (key === 'logLevel') {
+        this._updateLogLevel();
+      }
+    });
+  }
+
+  private _updateLogLevel(): void {
+    this._logLevel = optionsKeyToLogLevel[this._optionsService.options.logLevel];
+  }
+
+  private _evalLazyOptionalParams(optionalParams: any[]): void {
+    for (let i = 0; i < optionalParams.length; i++) {
+      if (typeof optionalParams[i] === 'function') {
+        optionalParams[i] = optionalParams[i]();
+      }
+    }
+  }
+
+  private _log(type: LogType, message: string, optionalParams: any[]): void {
+    this._evalLazyOptionalParams(optionalParams);
+    type.call(console, LOG_PREFIX + message, ...optionalParams);
+  }
+
+  debug(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.DEBUG) {
+      this._log(console.log, message, optionalParams);
+    }
+  }
+
+  info(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.INFO) {
+      this._log(console.info, message, optionalParams);
+    }
+  }
+
+  warn(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.WARN) {
+      this._log(console.warn, message, optionalParams);
+    }
+  }
+
+  error(message: string, ...optionalParams: any[]): void {
+    if (this._logLevel <= LogLevel.ERROR) {
+      this._log(console.error, message, optionalParams);
+    }
+  }
+}
diff --git a/node_modules/xterm/src/common/services/OptionsService.ts b/node_modules/xterm/src/common/services/OptionsService.ts
new file mode 100644 (file)
index 0000000..d9ea60d
--- /dev/null
@@ -0,0 +1,141 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IOptionsService, ITerminalOptions, IPartialTerminalOptions } from 'common/services/Services';
+import { EventEmitter, IEvent } from 'common/EventEmitter';
+import { isMac } from 'common/Platform';
+import { clone } from 'common/Clone';
+
+// Source: https://freesound.org/people/altemark/sounds/45759/
+// This sound is released under the Creative Commons Attribution 3.0 Unported
+// (CC BY 3.0) license. It was created by 'altemark'. No modifications have been
+// made, apart from the conversion to base64.
+export const DEFAULT_BELL_SOUND = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';
+
+// TODO: Freeze?
+export const DEFAULT_OPTIONS: ITerminalOptions = Object.freeze({
+  cols: 80,
+  rows: 24,
+  cursorBlink: false,
+  cursorStyle: 'block',
+  bellSound:  DEFAULT_BELL_SOUND,
+  bellStyle: 'none',
+  drawBoldTextInBrightColors: true,
+  fastScrollModifier: 'alt',
+  fastScrollSensitivity: 5,
+  fontFamily: 'courier-new, courier, monospace',
+  fontSize: 15,
+  fontWeight: 'normal',
+  fontWeightBold: 'bold',
+  lineHeight: 1.0,
+  letterSpacing: 0,
+  logLevel: 'info',
+  scrollback: 1000,
+  scrollSensitivity: 1,
+  screenReaderMode: false,
+  macOptionIsMeta: false,
+  macOptionClickForcesSelection: false,
+  disableStdin: false,
+  allowTransparency: false,
+  tabStopWidth: 8,
+  theme: {},
+  rightClickSelectsWord: isMac,
+  rendererType: 'canvas',
+  windowsMode: false,
+
+  convertEol: false,
+  termName: 'xterm',
+  screenKeys: false,
+  cancelEvents: false,
+  useFlowControl: false,
+  wordSeparator: ' ()[]{}\',:;"'
+});
+
+/**
+ * The set of options that only have an effect when set in the Terminal constructor.
+ */
+const CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows'];
+
+export class OptionsService implements IOptionsService {
+  serviceBrand: any;
+
+  public options: ITerminalOptions;
+
+  private _onOptionChange = new EventEmitter<string>();
+  public get onOptionChange(): IEvent<string> { return this._onOptionChange.event; }
+
+  constructor(options: IPartialTerminalOptions) {
+    this.options = clone(DEFAULT_OPTIONS);
+    Object.keys(options).forEach(k => {
+      if (k in this.options) {
+        const newValue = options[k as keyof IPartialTerminalOptions] as any;
+        this.options[k] = newValue;
+      }
+    });
+  }
+
+  public setOption(key: string, value: any): void {
+    if (!(key in DEFAULT_OPTIONS)) {
+      throw new Error('No option with key "' + key + '"');
+    }
+    if (CONSTRUCTOR_ONLY_OPTIONS.indexOf(key) !== -1) {
+      throw new Error(`Option "${key}" can only be set in the constructor`);
+    }
+    if (this.options[key] === value) {
+      return;
+    }
+
+    value = this._sanitizeAndValidateOption(key, value);
+
+    // Don't fire an option change event if they didn't change
+    if (this.options[key] === value) {
+      return;
+    }
+
+    this.options[key] = value;
+    this._onOptionChange.fire(key);
+  }
+
+  private _sanitizeAndValidateOption(key: string, value: any): any {
+    switch (key) {
+      case 'bellStyle':
+      case 'cursorStyle':
+      case 'fontWeight':
+      case 'fontWeightBold':
+      case 'rendererType':
+      case 'wordSeparator':
+        if (!value) {
+          value = DEFAULT_OPTIONS[key];
+        }
+        break;
+      case 'lineHeight':
+      case 'tabStopWidth':
+        if (value < 1) {
+          throw new Error(`${key} cannot be less than 1, value: ${value}`);
+        }
+        break;
+      case 'scrollback':
+        value = Math.min(value, 4294967295);
+        if (value < 0) {
+          throw new Error(`${key} cannot be less than 0, value: ${value}`);
+        }
+        break;
+      case 'fastScrollSensitivity':
+      case 'scrollSensitivity':
+        if (value <= 0) {
+          throw new Error(`${key} cannot be less than or equal to 0, value: ${value}`);
+        }
+        break;
+    }
+    return value;
+  }
+
+  public getOption(key: string): any {
+    if (!(key in DEFAULT_OPTIONS)) {
+      throw new Error(`No option with key "${key}"`);
+    }
+    return this.options[key];
+  }
+}
diff --git a/node_modules/xterm/src/common/services/ServiceRegistry.ts b/node_modules/xterm/src/common/services/ServiceRegistry.ts
new file mode 100644 (file)
index 0000000..450af49
--- /dev/null
@@ -0,0 +1,49 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ *
+ * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).
+ */
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *  Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+
+import { IServiceIdentifier } from 'common/services/Services';
+
+const DI_TARGET = 'di$target';
+const DI_DEPENDENCIES = 'di$dependencies';
+
+export const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map();
+
+export function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] {
+  return ctor[DI_DEPENDENCIES] || [];
+}
+
+export function createDecorator<T>(id: string): IServiceIdentifier<T> {
+  if (serviceRegistry.has(id)) {
+    return serviceRegistry.get(id)!;
+  }
+
+  const decorator = <any>function (target: Function, key: string, index: number): any {
+    if (arguments.length !== 3) {
+      throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
+    }
+
+    storeServiceDependency(decorator, target, index);
+  };
+
+  decorator.toString = () => id;
+
+  serviceRegistry.set(id, decorator);
+  return decorator;
+}
+
+function storeServiceDependency(id: Function, target: Function, index: number): void {
+  if ((target as any)[DI_TARGET] === target) {
+    (target as any)[DI_DEPENDENCIES].push({ id, index });
+  } else {
+    (target as any)[DI_DEPENDENCIES] = [{ id, index }];
+    (target as any)[DI_TARGET] = target;
+  }
+}
diff --git a/node_modules/xterm/src/common/services/Services.ts b/node_modules/xterm/src/common/services/Services.ts
new file mode 100644 (file)
index 0000000..0872d3d
--- /dev/null
@@ -0,0 +1,267 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IEvent } from 'common/EventEmitter';
+import { IBuffer, IBufferSet } from 'common/buffer/Types';
+import { IDecPrivateModes, ICoreMouseEvent, CoreMouseEncoding, ICoreMouseProtocol, CoreMouseEventType } from 'common/Types';
+import { createDecorator } from 'common/services/ServiceRegistry';
+
+export const IBufferService = createDecorator<IBufferService>('BufferService');
+export interface IBufferService {
+  serviceBrand: any;
+
+  readonly cols: number;
+  readonly rows: number;
+  readonly buffer: IBuffer;
+  readonly buffers: IBufferSet;
+
+  // TODO: Move resize event here
+
+  resize(cols: number, rows: number): void;
+  reset(): void;
+}
+
+export const ICoreMouseService = createDecorator<ICoreMouseService>('CoreMouseService');
+export interface ICoreMouseService {
+  activeProtocol: string;
+  activeEncoding: string;
+  addProtocol(name: string, protocol: ICoreMouseProtocol): void;
+  addEncoding(name: string, encoding: CoreMouseEncoding): void;
+  reset(): void;
+
+  /**
+   * Triggers a mouse event to be sent.
+   *
+   * Returns true if the event passed all protocol restrictions and a report
+   * was sent, otherwise false. The return value may be used to decide whether
+   * the default event action in the bowser component should be omitted.
+   *
+   * Note: The method will change values of the given event object
+   * to fullfill protocol and encoding restrictions.
+   */
+  triggerMouseEvent(event: ICoreMouseEvent): boolean;
+
+  /**
+   * Event to announce changes in mouse tracking.
+   */
+  onProtocolChange: IEvent<CoreMouseEventType>;
+
+  /**
+   * Human readable version of mouse events.
+   */
+  explainEvents(events: CoreMouseEventType): {[event: string]: boolean};
+}
+
+export const ICoreService = createDecorator<ICoreService>('CoreService');
+export interface ICoreService {
+  serviceBrand: any;
+
+  readonly decPrivateModes: IDecPrivateModes;
+
+  readonly onData: IEvent<string>;
+  readonly onUserInput: IEvent<void>;
+
+  reset(): void;
+
+  /**
+   * Triggers the onData event in the public API.
+   * @param data The data that is being emitted.
+   * @param wasFromUser Whether the data originated from the user (as opposed to
+   * resulting from parsing incoming data). When true this will also:
+   * - Scroll to the bottom of the buffer.s
+   * - Fire the `onUserInput` event (so selection can be cleared).
+    */
+  triggerDataEvent(data: string, wasUserInput?: boolean): void;
+}
+
+export const IDirtyRowService = createDecorator<IDirtyRowService>('DirtyRowService');
+export interface IDirtyRowService {
+  serviceBrand: any;
+
+  readonly start: number;
+  readonly end: number;
+
+  clearRange(): void;
+  markDirty(y: number): void;
+  markRangeDirty(y1: number, y2: number): void;
+  markAllDirty(): void;
+}
+
+export interface IServiceIdentifier<T> {
+  (...args: any[]): void;
+  type: T;
+}
+
+export interface IConstructorSignature0<T> {
+  new(...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature1<A1, T> {
+  new(first: A1, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature2<A1, A2, T> {
+  new(first: A1, second: A2, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature3<A1, A2, A3, T> {
+  new(first: A1, second: A2, third: A3, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature4<A1, A2, A3, A4, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { serviceBrand: any; }[]): T;
+}
+
+export interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {
+  new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { serviceBrand: any; }[]): T;
+}
+
+export const IInstantiationService = createDecorator<IInstantiationService>('InstantiationService');
+export interface IInstantiationService {
+  setService<T>(id: IServiceIdentifier<T>, instance: T): void;
+
+  createInstance<T>(ctor: IConstructorSignature0<T>): T;
+  createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T;
+  createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T;
+  createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T;
+  createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T;
+  createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;
+  createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;
+  createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;
+  createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;
+}
+
+export const ILogService = createDecorator<ILogService>('LogService');
+export interface ILogService {
+  serviceBrand: any;
+
+  debug(message: any, ...optionalParams: any[]): void;
+  info(message: any, ...optionalParams: any[]): void;
+  warn(message: any, ...optionalParams: any[]): void;
+  error(message: any, ...optionalParams: any[]): void;
+}
+
+export const IOptionsService = createDecorator<IOptionsService>('OptionsService');
+export interface IOptionsService {
+  serviceBrand: any;
+
+  readonly options: ITerminalOptions;
+
+  readonly onOptionChange: IEvent<string>;
+
+  setOption<T>(key: string, value: T): void;
+  getOption<T>(key: string): T | undefined;
+}
+
+export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
+export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';
+export type RendererType = 'dom' | 'canvas';
+
+export interface IPartialTerminalOptions {
+  allowTransparency?: boolean;
+  bellSound?: string;
+  bellStyle?: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;
+  cols?: number;
+  cursorBlink?: boolean;
+  cursorStyle?: 'block' | 'underline' | 'bar';
+  disableStdin?: boolean;
+  drawBoldTextInBrightColors?: boolean;
+  fastScrollModifier?: 'alt' | 'ctrl' | 'shift';
+  fastScrollSensitivity?: number;
+  fontSize?: number;
+  fontFamily?: string;
+  fontWeight?: FontWeight;
+  fontWeightBold?: FontWeight;
+  letterSpacing?: number;
+  lineHeight?: number;
+  logLevel?: LogLevel;
+  macOptionIsMeta?: boolean;
+  macOptionClickForcesSelection?: boolean;
+  rendererType?: RendererType;
+  rightClickSelectsWord?: boolean;
+  rows?: number;
+  screenReaderMode?: boolean;
+  scrollback?: number;
+  scrollSensitivity?: number;
+  tabStopWidth?: number;
+  theme?: ITheme;
+  windowsMode?: boolean;
+  wordSeparator?: string;
+}
+
+export interface ITerminalOptions {
+  allowTransparency: boolean;
+  bellSound: string;
+  bellStyle: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;
+  cols: number;
+  cursorBlink: boolean;
+  cursorStyle: 'block' | 'underline' | 'bar';
+  disableStdin: boolean;
+  drawBoldTextInBrightColors: boolean;
+  fastScrollModifier: 'alt' | 'ctrl' | 'shift' | undefined;
+  fastScrollSensitivity: number;
+  fontSize: number;
+  fontFamily: string;
+  fontWeight: FontWeight;
+  fontWeightBold: FontWeight;
+  letterSpacing: number;
+  lineHeight: number;
+  logLevel: LogLevel;
+  macOptionIsMeta: boolean;
+  macOptionClickForcesSelection: boolean;
+  rendererType: RendererType;
+  rightClickSelectsWord: boolean;
+  rows: number;
+  screenReaderMode: boolean;
+  scrollback: number;
+  scrollSensitivity: number;
+  tabStopWidth: number;
+  theme: ITheme;
+  windowsMode: boolean;
+  wordSeparator: string;
+
+  [key: string]: any;
+  cancelEvents: boolean;
+  convertEol: boolean;
+  screenKeys: boolean;
+  termName: string;
+  useFlowControl: boolean;
+}
+
+export interface ITheme {
+  foreground?: string;
+  background?: string;
+  cursor?: string;
+  cursorAccent?: string;
+  selection?: string;
+  black?: string;
+  red?: string;
+  green?: string;
+  yellow?: string;
+  blue?: string;
+  magenta?: string;
+  cyan?: string;
+  white?: string;
+  brightBlack?: string;
+  brightRed?: string;
+  brightGreen?: string;
+  brightYellow?: string;
+  brightBlue?: string;
+  brightMagenta?: string;
+  brightCyan?: string;
+  brightWhite?: string;
+}
diff --git a/node_modules/xterm/src/common/tsconfig.json b/node_modules/xterm/src/common/tsconfig.json
new file mode 100644 (file)
index 0000000..59050a0
--- /dev/null
@@ -0,0 +1,14 @@
+{
+  "extends": "../tsconfig-library-base",
+  "compilerOptions": {
+    "lib": [
+      "es2015"
+    ],
+    "outDir": "../../out",
+    "types": [
+      "../../node_modules/@types/mocha"
+    ],
+    "baseUrl": ".."
+  },
+  "include": [ "./**/*" ]
+}
diff --git a/node_modules/xterm/src/public/AddonManager.ts b/node_modules/xterm/src/public/AddonManager.ts
new file mode 100644 (file)
index 0000000..0261fd6
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2019 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { ITerminalAddon, IDisposable, Terminal } from 'xterm';
+
+export interface ILoadedAddon {
+  instance: ITerminalAddon;
+  dispose: () => void;
+  isDisposed: boolean;
+}
+
+export class AddonManager implements IDisposable {
+  protected _addons: ILoadedAddon[] = [];
+
+  constructor() {
+  }
+
+  public dispose(): void {
+    for (let i = this._addons.length - 1; i >= 0; i--) {
+      this._addons[i].instance.dispose();
+    }
+  }
+
+  public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {
+    const loadedAddon: ILoadedAddon = {
+      instance,
+      dispose: instance.dispose,
+      isDisposed: false
+    };
+    this._addons.push(loadedAddon);
+    instance.dispose = () => this._wrappedAddonDispose(loadedAddon);
+    instance.activate(<any>terminal);
+  }
+
+  private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {
+    if (loadedAddon.isDisposed) {
+      // Do nothing if already disposed
+      return;
+    }
+    let index = -1;
+    for (let i = 0; i < this._addons.length; i++) {
+      if (this._addons[i] === loadedAddon) {
+        index = i;
+        break;
+      }
+    }
+    if (index === -1) {
+      throw new Error('Could not dispose an addon that has not been loaded');
+    }
+    loadedAddon.isDisposed = true;
+    loadedAddon.dispose.apply(loadedAddon.instance);
+    this._addons.splice(index, 1);
+  }
+}
diff --git a/node_modules/xterm/src/public/Terminal.ts b/node_modules/xterm/src/public/Terminal.ts
new file mode 100644 (file)
index 0000000..c167bed
--- /dev/null
@@ -0,0 +1,241 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { Terminal as ITerminalApi, ITerminalOptions, IMarker, IDisposable, ILinkMatcherOptions, ITheme, ILocalizableStrings, ITerminalAddon, ISelectionPosition, IBuffer as IBufferApi, IBufferLine as IBufferLineApi, IBufferCell as IBufferCellApi, IParser, IFunctionIdentifier } from 'xterm';
+import { ITerminal } from '../Types';
+import { IBufferLine } from 'common/Types';
+import { IBuffer } from 'common/buffer/Types';
+import { Terminal as TerminalCore } from '../Terminal';
+import * as Strings from '../browser/LocalizableStrings';
+import { IEvent } from 'common/EventEmitter';
+import { AddonManager } from './AddonManager';
+import { IParams } from 'common/parser/Types';
+
+export class Terminal implements ITerminalApi {
+  private _core: ITerminal;
+  private _addonManager: AddonManager;
+  private _parser: IParser;
+
+  constructor(options?: ITerminalOptions) {
+    this._core = new TerminalCore(options);
+    this._addonManager = new AddonManager();
+  }
+
+  public get onCursorMove(): IEvent<void> { return this._core.onCursorMove; }
+  public get onLineFeed(): IEvent<void> { return this._core.onLineFeed; }
+  public get onSelectionChange(): IEvent<void> { return this._core.onSelectionChange; }
+  public get onData(): IEvent<string> { return this._core.onData; }
+  public get onTitleChange(): IEvent<string> { return this._core.onTitleChange; }
+  public get onScroll(): IEvent<number> { return this._core.onScroll; }
+  public get onKey(): IEvent<{ key: string, domEvent: KeyboardEvent }> { return this._core.onKey; }
+  public get onRender(): IEvent<{ start: number, end: number }> { return this._core.onRender; }
+  public get onResize(): IEvent<{ cols: number, rows: number }> { return this._core.onResize; }
+
+  public get element(): HTMLElement | undefined { return this._core.element; }
+  public get parser(): IParser {
+    if (!this._parser) {
+      this._parser = new ParserApi(this._core);
+    }
+    return this._parser;
+  }
+  public get textarea(): HTMLTextAreaElement | undefined { return this._core.textarea; }
+  public get rows(): number { return this._core.rows; }
+  public get cols(): number { return this._core.cols; }
+  public get buffer(): IBufferApi { return new BufferApiView(this._core.buffer); }
+  public get markers(): ReadonlyArray<IMarker> { return this._core.markers; }
+  public blur(): void {
+    this._core.blur();
+  }
+  public focus(): void {
+    this._core.focus();
+  }
+  public resize(columns: number, rows: number): void {
+    this._verifyIntegers(columns, rows);
+    this._core.resize(columns, rows);
+  }
+  public open(parent: HTMLElement): void {
+    this._core.open(parent);
+  }
+  public attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void {
+    this._core.attachCustomKeyEventHandler(customKeyEventHandler);
+  }
+  public registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number {
+    return this._core.registerLinkMatcher(regex, handler, options);
+  }
+  public deregisterLinkMatcher(matcherId: number): void {
+    this._core.deregisterLinkMatcher(matcherId);
+  }
+  public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
+    return this._core.registerCharacterJoiner(handler);
+  }
+  public deregisterCharacterJoiner(joinerId: number): void {
+    this._core.deregisterCharacterJoiner(joinerId);
+  }
+  public addMarker(cursorYOffset: number): IMarker {
+    this._verifyIntegers(cursorYOffset);
+    return this._core.addMarker(cursorYOffset);
+  }
+  public hasSelection(): boolean {
+    return this._core.hasSelection();
+  }
+  public select(column: number, row: number, length: number): void {
+    this._verifyIntegers(column, row, length);
+    this._core.select(column, row, length);
+  }
+  public getSelection(): string {
+    return this._core.getSelection();
+  }
+  public getSelectionPosition(): ISelectionPosition | undefined {
+    return this._core.getSelectionPosition();
+  }
+  public clearSelection(): void {
+    this._core.clearSelection();
+  }
+  public selectAll(): void {
+    this._core.selectAll();
+  }
+  public selectLines(start: number, end: number): void {
+    this._verifyIntegers(start, end);
+    this._core.selectLines(start, end);
+  }
+  public dispose(): void {
+    this._addonManager.dispose();
+    this._core.dispose();
+  }
+  public scrollLines(amount: number): void {
+    this._verifyIntegers(amount);
+    this._core.scrollLines(amount);
+  }
+  public scrollPages(pageCount: number): void {
+    this._verifyIntegers(pageCount);
+    this._core.scrollPages(pageCount);
+  }
+  public scrollToTop(): void {
+    this._core.scrollToTop();
+  }
+  public scrollToBottom(): void {
+    this._core.scrollToBottom();
+  }
+  public scrollToLine(line: number): void {
+    this._verifyIntegers(line);
+    this._core.scrollToLine(line);
+  }
+  public clear(): void {
+    this._core.clear();
+  }
+  public write(data: string | Uint8Array, callback?: () => void): void {
+    this._core.write(data, callback);
+  }
+  public writeUtf8(data: Uint8Array, callback?: () => void): void {
+    this._core.write(data, callback);
+  }
+  public writeln(data: string | Uint8Array, callback?: () => void): void {
+    this._core.write(data);
+    this._core.write('\r\n', callback);
+  }
+  public paste(data: string): void {
+    this._core.paste(data);
+  }
+  public getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;
+  public getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell'): boolean;
+  public getOption(key: 'colors'): string[];
+  public getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;
+  public getOption(key: 'handler'): (data: string) => void;
+  public getOption(key: string): any;
+  public getOption(key: any): any {
+    return this._core.optionsService.getOption(key);
+  }
+  public setOption(key: 'bellSound' | 'fontFamily' | 'termName' | 'wordSeparator', value: string): void;
+  public setOption(key: 'fontWeight' | 'fontWeightBold', value: 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'): void;
+  public setOption(key: 'logLevel', value: 'debug' | 'info' | 'warn' | 'error' | 'off'): void;
+  public setOption(key: 'bellStyle', value: 'none' | 'visual' | 'sound' | 'both'): void;
+  public setOption(key: 'cursorStyle', value: 'block' | 'underline' | 'bar'): void;
+  public setOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell', value: boolean): void;
+  public setOption(key: 'colors', value: string[]): void;
+  public setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;
+  public setOption(key: 'handler', value: (data: string) => void): void;
+  public setOption(key: 'theme', value: ITheme): void;
+  public setOption(key: 'cols' | 'rows', value: number): void;
+  public setOption(key: string, value: any): void;
+  public setOption(key: any, value: any): void {
+    this._core.optionsService.setOption(key, value);
+  }
+  public refresh(start: number, end: number): void {
+    this._verifyIntegers(start, end);
+    this._core.refresh(start, end);
+  }
+  public reset(): void {
+    this._core.reset();
+  }
+  public loadAddon(addon: ITerminalAddon): void {
+    return this._addonManager.loadAddon(this, addon);
+  }
+  public static get strings(): ILocalizableStrings {
+    return Strings;
+  }
+
+  private _verifyIntegers(...values: number[]): void {
+    values.forEach(value => {
+      if (value === Infinity || isNaN(value) || value % 1 !== 0) {
+        throw new Error('This API only accepts integers');
+      }
+    });
+  }
+}
+
+class BufferApiView implements IBufferApi {
+  constructor(private _buffer: IBuffer) {}
+
+  public get cursorY(): number { return this._buffer.y; }
+  public get cursorX(): number { return this._buffer.x; }
+  public get viewportY(): number { return this._buffer.ydisp; }
+  public get baseY(): number { return this._buffer.ybase; }
+  public get length(): number { return this._buffer.lines.length; }
+  public getLine(y: number): IBufferLineApi | undefined {
+    const line = this._buffer.lines.get(y);
+    if (!line) {
+      return undefined;
+    }
+    return new BufferLineApiView(line);
+  }
+}
+
+class BufferLineApiView implements IBufferLineApi {
+  constructor(private _line: IBufferLine) {}
+
+  public get isWrapped(): boolean { return this._line.isWrapped; }
+  public getCell(x: number): IBufferCellApi | undefined {
+    if (x < 0 || x >= this._line.length) {
+      return undefined;
+    }
+    return new BufferCellApiView(this._line, x);
+  }
+  public translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string {
+    return this._line.translateToString(trimRight, startColumn, endColumn);
+  }
+}
+
+class BufferCellApiView implements IBufferCellApi {
+  constructor(private _line: IBufferLine, private _x: number) {}
+  public get char(): string { return this._line.getString(this._x); }
+  public get width(): number { return this._line.getWidth(this._x); }
+}
+
+class ParserApi implements IParser {
+  constructor(private _core: ITerminal) {}
+
+  public addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable {
+    return this._core.addCsiHandler(id, (params: IParams) => callback(params.toArray()));
+  }
+  public addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable {
+    return this._core.addDcsHandler(id, (data: string, params: IParams) => callback(data, params.toArray()));
+  }
+  public addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable {
+    return this._core.addEscHandler(id, handler);
+  }
+  public addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable {
+    return this._core.addOscHandler(ident, callback);
+  }
+}
diff --git a/node_modules/xterm/src/renderer/CursorRenderLayer.ts b/node_modules/xterm/src/renderer/CursorRenderLayer.ts
new file mode 100644 (file)
index 0000000..1f2791f
--- /dev/null
@@ -0,0 +1,368 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderDimensions } from 'browser/renderer/Types';
+import { BaseRenderLayer } from '../browser/renderer/BaseRenderLayer';
+import { ITerminal } from '../Types';
+import { ICellData } from 'common/Types';
+import { CellData } from 'common/buffer/CellData';
+import { IColorSet } from 'browser/Types';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+
+interface ICursorState {
+  x: number;
+  y: number;
+  isFocused: boolean;
+  style: string;
+  width: number;
+}
+
+/**
+ * The time between cursor blinks.
+ */
+const BLINK_INTERVAL = 600;
+
+export class CursorRenderLayer extends BaseRenderLayer {
+  private _state: ICursorState;
+  private _cursorRenderers: {[key: string]: (x: number, y: number, cell: ICellData) => void};
+  private _cursorBlinkStateManager: CursorBlinkStateManager;
+  private _cell: ICellData = new CellData();
+
+  constructor(
+    container: HTMLElement,
+    zIndex: number,
+    colors: IColorSet,
+    private _terminal: ITerminal,
+    rendererId: number,
+    readonly bufferService: IBufferService,
+    readonly optionsService: IOptionsService
+  ) {
+    super(container, 'cursor', zIndex, true, colors, rendererId, bufferService, optionsService);
+    this._state = {
+      x: null,
+      y: null,
+      isFocused: null,
+      style: null,
+      width: null
+    };
+    this._cursorRenderers = {
+      'bar': this._renderBarCursor.bind(this),
+      'block': this._renderBlockCursor.bind(this),
+      'underline': this._renderUnderlineCursor.bind(this)
+    };
+    // TODO: Consider initial options? Maybe onOptionsChanged should be called at the end of open?
+  }
+
+  public resize(dim: IRenderDimensions): void {
+    super.resize(dim);
+    // Resizing the canvas discards the contents of the canvas so clear state
+    this._state = {
+      x: null,
+      y: null,
+      isFocused: null,
+      style: null,
+      width: null
+    };
+  }
+
+  public reset(): void {
+    this._clearCursor();
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.dispose();
+      this._cursorBlinkStateManager = null;
+      this.onOptionsChanged();
+    }
+  }
+
+  public onBlur(): void {
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.pause();
+    }
+    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);
+  }
+
+  public onFocus(): void {
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.resume();
+    } else {
+      this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);
+    }
+  }
+
+  public onOptionsChanged(): void {
+    if (this._optionsService.options.cursorBlink) {
+      if (!this._cursorBlinkStateManager) {
+        this._cursorBlinkStateManager = new CursorBlinkStateManager(this._terminal.isFocused, () => {
+          this._render(true);
+        });
+      }
+    } else {
+      if (this._cursorBlinkStateManager) {
+        this._cursorBlinkStateManager.dispose();
+        this._cursorBlinkStateManager = null;
+      }
+    }
+    // Request a refresh from the terminal as management of rendering is being
+    // moved back to the terminal
+    this._terminal.refresh(this._bufferService.buffer.y, this._bufferService.buffer.y);
+  }
+
+  public onCursorMove(): void {
+    if (this._cursorBlinkStateManager) {
+      this._cursorBlinkStateManager.restartBlinkAnimation();
+    }
+  }
+
+  public onGridChanged(startRow: number, endRow: number): void {
+    if (!this._cursorBlinkStateManager || this._cursorBlinkStateManager.isPaused) {
+      this._render(false);
+    } else {
+      this._cursorBlinkStateManager.restartBlinkAnimation();
+    }
+  }
+
+  private _render(triggeredByAnimationFrame: boolean): void {
+    // Don't draw the cursor if it's hidden
+    if (!this._terminal.cursorState || this._terminal.cursorHidden) {
+      this._clearCursor();
+      return;
+    }
+
+    const cursorY = this._bufferService.buffer.ybase + this._bufferService.buffer.y;
+    const viewportRelativeCursorY = cursorY - this._bufferService.buffer.ydisp;
+
+    // Don't draw the cursor if it's off-screen
+    if (viewportRelativeCursorY < 0 || viewportRelativeCursorY >= this._bufferService.rows) {
+      this._clearCursor();
+      return;
+    }
+
+    this._bufferService.buffer.lines.get(cursorY).loadCell(this._bufferService.buffer.x, this._cell);
+    if (this._cell.content === undefined) {
+      return;
+    }
+
+    if (!this._terminal.isFocused) {
+      this._clearCursor();
+      this._ctx.save();
+      this._ctx.fillStyle = this._colors.cursor.css;
+      const cursorStyle = this._optionsService.options.cursorStyle;
+      if (cursorStyle && cursorStyle !== 'block') {
+        this._cursorRenderers[cursorStyle](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);
+      } else {
+        this._renderBlurCursor(this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);
+      }
+      this._ctx.restore();
+      this._state.x = this._bufferService.buffer.x;
+      this._state.y = viewportRelativeCursorY;
+      this._state.isFocused = false;
+      this._state.style = cursorStyle;
+      this._state.width = this._cell.getWidth();
+      return;
+    }
+
+    // Don't draw the cursor if it's blinking
+    if (this._cursorBlinkStateManager && !this._cursorBlinkStateManager.isCursorVisible) {
+      this._clearCursor();
+      return;
+    }
+
+    if (this._state) {
+      // The cursor is already in the correct spot, don't redraw
+      if (this._state.x === this._bufferService.buffer.x &&
+          this._state.y === viewportRelativeCursorY &&
+          this._state.isFocused === this._terminal.isFocused &&
+          this._state.style === this._optionsService.options.cursorStyle &&
+          this._state.width === this._cell.getWidth()) {
+        return;
+      }
+      this._clearCursor();
+    }
+
+    this._ctx.save();
+    this._cursorRenderers[this._optionsService.options.cursorStyle || 'block'](this._bufferService.buffer.x, viewportRelativeCursorY, this._cell);
+    this._ctx.restore();
+
+    this._state.x = this._bufferService.buffer.x;
+    this._state.y = viewportRelativeCursorY;
+    this._state.isFocused = false;
+    this._state.style = this._optionsService.options.cursorStyle;
+    this._state.width = this._cell.getWidth();
+  }
+
+  private _clearCursor(): void {
+    if (this._state) {
+      this._clearCells(this._state.x, this._state.y, this._state.width, 1);
+      this._state = {
+        x: null,
+        y: null,
+        isFocused: null,
+        style: null,
+        width: null
+      };
+    }
+  }
+
+  private _renderBarCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.fillStyle = this._colors.cursor.css;
+    this._fillLeftLineAtCell(x, y);
+    this._ctx.restore();
+  }
+
+  private _renderBlockCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.fillStyle = this._colors.cursor.css;
+    this._fillCells(x, y, cell.getWidth(), 1);
+    this._ctx.fillStyle = this._colors.cursorAccent.css;
+    this._fillCharTrueColor(cell, x, y);
+    this._ctx.restore();
+  }
+
+  private _renderUnderlineCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.fillStyle = this._colors.cursor.css;
+    this._fillBottomLineAtCells(x, y);
+    this._ctx.restore();
+  }
+
+  private _renderBlurCursor(x: number, y: number, cell: ICellData): void {
+    this._ctx.save();
+    this._ctx.strokeStyle = this._colors.cursor.css;
+    this._strokeRectAtCell(x, y, cell.getWidth(), 1);
+    this._ctx.restore();
+  }
+}
+
+class CursorBlinkStateManager {
+  public isCursorVisible: boolean;
+
+  private _animationFrame: number;
+  private _blinkStartTimeout: number;
+  private _blinkInterval: number;
+
+  /**
+   * The time at which the animation frame was restarted, this is used on the
+   * next render to restart the timers so they don't need to restart the timers
+   * multiple times over a short period.
+   */
+  private _animationTimeRestarted: number;
+
+  constructor(
+    isFocused: boolean,
+    private _renderCallback: () => void
+  ) {
+    this.isCursorVisible = true;
+    if (isFocused) {
+      this._restartInterval();
+    }
+  }
+
+  public get isPaused(): boolean { return !(this._blinkStartTimeout || this._blinkInterval); }
+
+  public dispose(): void {
+    if (this._blinkInterval) {
+      window.clearInterval(this._blinkInterval);
+      this._blinkInterval = null;
+    }
+    if (this._blinkStartTimeout) {
+      window.clearTimeout(this._blinkStartTimeout);
+      this._blinkStartTimeout = null;
+    }
+    if (this._animationFrame) {
+      window.cancelAnimationFrame(this._animationFrame);
+      this._animationFrame = null;
+    }
+  }
+
+  public restartBlinkAnimation(): void {
+    if (this.isPaused) {
+      return;
+    }
+    // Save a timestamp so that the restart can be done on the next interval
+    this._animationTimeRestarted = Date.now();
+    // Force a cursor render to ensure it's visible and in the correct position
+    this.isCursorVisible = true;
+    if (!this._animationFrame) {
+      this._animationFrame = window.requestAnimationFrame(() => {
+        this._renderCallback();
+        this._animationFrame = null;
+      });
+    }
+  }
+
+  private _restartInterval(timeToStart: number = BLINK_INTERVAL): void {
+    // Clear any existing interval
+    if (this._blinkInterval) {
+      window.clearInterval(this._blinkInterval);
+    }
+
+    // Setup the initial timeout which will hide the cursor, this is done before
+    // the regular interval is setup in order to support restarting the blink
+    // animation in a lightweight way (without thrashing clearInterval and
+    // setInterval).
+    this._blinkStartTimeout = <number><any>setTimeout(() => {
+      // Check if another animation restart was requested while this was being
+      // started
+      if (this._animationTimeRestarted) {
+        const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
+        this._animationTimeRestarted = null;
+        if (time > 0) {
+          this._restartInterval(time);
+          return;
+        }
+      }
+
+      // Hide the cursor
+      this.isCursorVisible = false;
+      this._animationFrame = window.requestAnimationFrame(() => {
+        this._renderCallback();
+        this._animationFrame = null;
+      });
+
+      // Setup the blink interval
+      this._blinkInterval = <number><any>setInterval(() => {
+        // Adjust the animation time if it was restarted
+        if (this._animationTimeRestarted) {
+          // calc time diff
+          // Make restart interval do a setTimeout initially?
+          const time = BLINK_INTERVAL - (Date.now() - this._animationTimeRestarted);
+          this._animationTimeRestarted = null;
+          this._restartInterval(time);
+          return;
+        }
+
+        // Invert visibility and render
+        this.isCursorVisible = !this.isCursorVisible;
+        this._animationFrame = window.requestAnimationFrame(() => {
+          this._renderCallback();
+          this._animationFrame = null;
+        });
+      }, BLINK_INTERVAL);
+    }, timeToStart);
+  }
+
+  public pause(): void {
+    this.isCursorVisible = true;
+    if (this._blinkInterval) {
+      window.clearInterval(this._blinkInterval);
+      this._blinkInterval = null;
+    }
+    if (this._blinkStartTimeout) {
+      window.clearTimeout(this._blinkStartTimeout);
+      this._blinkStartTimeout = null;
+    }
+    if (this._animationFrame) {
+      window.cancelAnimationFrame(this._animationFrame);
+      this._animationFrame = null;
+    }
+  }
+
+  public resume(): void {
+    this._animationTimeRestarted = null;
+    this._restartInterval();
+    this.restartBlinkAnimation();
+  }
+}
diff --git a/node_modules/xterm/src/renderer/Renderer.ts b/node_modules/xterm/src/renderer/Renderer.ts
new file mode 100644 (file)
index 0000000..d3977af
--- /dev/null
@@ -0,0 +1,208 @@
+/**
+ * Copyright (c) 2017 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { TextRenderLayer } from '../browser/renderer/TextRenderLayer';
+import { SelectionRenderLayer } from '../browser/renderer/SelectionRenderLayer';
+import { CursorRenderLayer } from './CursorRenderLayer';
+import { IRenderLayer, IRenderer, IRenderDimensions, CharacterJoinerHandler, ICharacterJoinerRegistry } from 'browser/renderer/Types';
+import { ITerminal } from '../Types';
+import { LinkRenderLayer } from '../browser/renderer/LinkRenderLayer';
+import { CharacterJoinerRegistry } from 'browser/renderer/CharacterJoinerRegistry';
+import { Disposable } from 'common/Lifecycle';
+import { IColorSet } from 'browser/Types';
+import { ICharSizeService } from 'browser/services/Services';
+import { IBufferService, IOptionsService } from 'common/services/Services';
+import { removeTerminalFromCache } from 'browser/renderer/atlas/CharAtlasCache';
+
+let nextRendererId = 1;
+
+export class Renderer extends Disposable implements IRenderer {
+  private _id = nextRendererId++;
+
+  private _renderLayers: IRenderLayer[];
+  private _devicePixelRatio: number;
+  private _characterJoinerRegistry: ICharacterJoinerRegistry;
+
+  public dimensions: IRenderDimensions;
+
+  constructor(
+    private _colors: IColorSet,
+    private readonly _terminal: ITerminal,
+    readonly bufferService: IBufferService,
+    private readonly _charSizeService: ICharSizeService,
+    readonly optionsService: IOptionsService
+  ) {
+    super();
+    const allowTransparency = this._terminal.options.allowTransparency;
+    this._characterJoinerRegistry = new CharacterJoinerRegistry(bufferService);
+
+    this._renderLayers = [
+      new TextRenderLayer(this._terminal.screenElement, 0, this._colors, this._characterJoinerRegistry, allowTransparency, this._id, bufferService, optionsService),
+      new SelectionRenderLayer(this._terminal.screenElement, 1, this._colors, this._id, bufferService, optionsService),
+      new LinkRenderLayer(this._terminal.screenElement, 2, this._colors, this._id, this._terminal.linkifier, bufferService, optionsService),
+      new CursorRenderLayer(this._terminal.screenElement, 3, this._colors, this._terminal, this._id, bufferService, optionsService)
+    ];
+    this.dimensions = {
+      scaledCharWidth: null,
+      scaledCharHeight: null,
+      scaledCellWidth: null,
+      scaledCellHeight: null,
+      scaledCharLeft: null,
+      scaledCharTop: null,
+      scaledCanvasWidth: null,
+      scaledCanvasHeight: null,
+      canvasWidth: null,
+      canvasHeight: null,
+      actualCellWidth: null,
+      actualCellHeight: null
+    };
+    this._devicePixelRatio = window.devicePixelRatio;
+    this._updateDimensions();
+    this.onOptionsChanged();
+  }
+
+  public dispose(): void {
+    super.dispose();
+    this._renderLayers.forEach(l => l.dispose());
+    removeTerminalFromCache(this._id);
+  }
+
+  public onDevicePixelRatioChange(): void {
+    // If the device pixel ratio changed, the char atlas needs to be regenerated
+    // and the terminal needs to refreshed
+    if (this._devicePixelRatio !== window.devicePixelRatio) {
+      this._devicePixelRatio = window.devicePixelRatio;
+      this.onResize(this._terminal.cols, this._terminal.rows);
+    }
+  }
+
+  public setColors(colors: IColorSet): void {
+    this._colors = colors;
+
+    // Clear layers and force a full render
+    this._renderLayers.forEach(l => {
+      l.setColors(this._colors);
+      l.reset();
+    });
+  }
+
+  public onResize(cols: number, rows: number): void {
+    // Update character and canvas dimensions
+    this._updateDimensions();
+
+    // Resize all render layers
+    this._renderLayers.forEach(l => l.resize(this.dimensions));
+
+    // Resize the screen
+    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;
+    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;
+  }
+
+  public onCharSizeChanged(): void {
+    this.onResize(this._terminal.cols, this._terminal.rows);
+  }
+
+  public onBlur(): void {
+    this._runOperation(l => l.onBlur());
+  }
+
+  public onFocus(): void {
+    this._runOperation(l => l.onFocus());
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean = false): void {
+    this._runOperation(l => l.onSelectionChanged(start, end, columnSelectMode));
+  }
+
+  public onCursorMove(): void {
+    this._runOperation(l => l.onCursorMove());
+  }
+
+  public onOptionsChanged(): void {
+    this._runOperation(l => l.onOptionsChanged());
+  }
+
+  public clear(): void {
+    this._runOperation(l => l.reset());
+  }
+
+  private _runOperation(operation: (layer: IRenderLayer) => void): void {
+    this._renderLayers.forEach(l => operation(l));
+  }
+
+  /**
+   * Performs the refresh loop callback, calling refresh only if a refresh is
+   * necessary before queueing up the next one.
+   */
+  public renderRows(start: number, end: number): void {
+    this._renderLayers.forEach(l => l.onGridChanged(start, end));
+  }
+
+  /**
+   * Recalculates the character and canvas dimensions.
+   */
+  private _updateDimensions(): void {
+    if (!this._charSizeService.hasValidSize) {
+      return;
+    }
+
+    // Calculate the scaled character width. Width is floored as it must be
+    // drawn to an integer grid in order for the CharAtlas "stamps" to not be
+    // blurry. When text is drawn to the grid not using the CharAtlas, it is
+    // clipped to ensure there is no overlap with the next cell.
+    this.dimensions.scaledCharWidth = Math.floor(this._charSizeService.width * window.devicePixelRatio);
+
+    // Calculate the scaled character height. Height is ceiled in case
+    // devicePixelRatio is a floating point number in order to ensure there is
+    // enough space to draw the character to the cell.
+    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);
+
+    // Calculate the scaled cell height, if lineHeight is not 1 then the value
+    // will be floored because since lineHeight can never be lower then 1, there
+    // is a guarentee that the scaled line height will always be larger than
+    // scaled char height.
+    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);
+
+    // Calculate the y coordinate within a cell that text should draw from in
+    // order to draw in the center of a cell.
+    this.dimensions.scaledCharTop = this._terminal.options.lineHeight === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2);
+
+    // Calculate the scaled cell width, taking the letterSpacing into account.
+    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);
+
+    // Calculate the x coordinate with a cell that text should draw from in
+    // order to draw in the center of a cell.
+    this.dimensions.scaledCharLeft = Math.floor(this._terminal.options.letterSpacing / 2);
+
+    // Recalculate the canvas dimensions; scaled* define the actual number of
+    // pixel in the canvas
+    this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight;
+    this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth;
+
+    // The the size of the canvas on the page. It's very important that this
+    // rounds to nearest integer and not ceils as browsers often set
+    // window.devicePixelRatio as something like 1.100000023841858, when it's
+    // actually 1.1. Ceiling causes blurriness as the backing canvas image is 1
+    // pixel too large for the canvas element size.
+    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);
+    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);
+
+    // Get the _actual_ dimensions of an individual cell. This needs to be
+    // derived from the canvasWidth/Height calculated above which takes into
+    // account window.devicePixelRatio. ICharSizeService.width/height by itself
+    // is insufficient when the page is not at 100% zoom level as it's measured
+    // in CSS pixels, but the actual char size on the canvas can differ.
+    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;
+    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
+    return this._characterJoinerRegistry.registerCharacterJoiner(handler);
+  }
+
+  public deregisterCharacterJoiner(joinerId: number): boolean {
+    return this._characterJoinerRegistry.deregisterCharacterJoiner(joinerId);
+  }
+}
diff --git a/node_modules/xterm/src/renderer/dom/DomRenderer.ts b/node_modules/xterm/src/renderer/dom/DomRenderer.ts
new file mode 100644 (file)
index 0000000..ef927f2
--- /dev/null
@@ -0,0 +1,392 @@
+/**
+ * Copyright (c) 2018 The xterm.js authors. All rights reserved.
+ * @license MIT
+ */
+
+import { IRenderer, IRenderDimensions, CharacterJoinerHandler } from 'browser/renderer/Types';
+import { ITerminal } from '../../Types';
+import { BOLD_CLASS, ITALIC_CLASS, CURSOR_CLASS, CURSOR_STYLE_BLOCK_CLASS, CURSOR_BLINK_CLASS, CURSOR_STYLE_BAR_CLASS, CURSOR_STYLE_UNDERLINE_CLASS, DomRendererRowFactory } from 'browser/renderer/dom/DomRendererRowFactory';
+import { INVERTED_DEFAULT_COLOR } from 'browser/renderer/atlas/Constants';
+import { Disposable } from 'common/Lifecycle';
+import { IColorSet, ILinkifierEvent } from 'browser/Types';
+import { ICharSizeService } from 'browser/services/Services';
+import { IOptionsService } from 'common/services/Services';
+
+const TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-';
+const ROW_CONTAINER_CLASS = 'xterm-rows';
+const FG_CLASS_PREFIX = 'xterm-fg-';
+const BG_CLASS_PREFIX = 'xterm-bg-';
+const FOCUS_CLASS = 'xterm-focus';
+const SELECTION_CLASS = 'xterm-selection';
+
+let nextTerminalId = 1;
+
+/**
+ * A fallback renderer for when canvas is slow. This is not meant to be
+ * particularly fast or feature complete, more just stable and usable for when
+ * canvas is not an option.
+ */
+export class DomRenderer extends Disposable implements IRenderer {
+  private _rowFactory: DomRendererRowFactory;
+  private _terminalClass: number = nextTerminalId++;
+
+  private _themeStyleElement: HTMLStyleElement;
+  private _dimensionsStyleElement: HTMLStyleElement;
+  private _rowContainer: HTMLElement;
+  private _rowElements: HTMLElement[] = [];
+  private _selectionContainer: HTMLElement;
+
+  public dimensions: IRenderDimensions;
+
+  constructor(
+    private _terminal: ITerminal,
+    private _colors: IColorSet,
+    private _charSizeService: ICharSizeService,
+    private _optionsService: IOptionsService
+  ) {
+    super();
+
+    this._rowContainer = document.createElement('div');
+    this._rowContainer.classList.add(ROW_CONTAINER_CLASS);
+    this._rowContainer.style.lineHeight = 'normal';
+    this._rowContainer.setAttribute('aria-hidden', 'true');
+    this._refreshRowElements(this._terminal.cols, this._terminal.rows);
+    this._selectionContainer = document.createElement('div');
+    this._selectionContainer.classList.add(SELECTION_CLASS);
+    this._selectionContainer.setAttribute('aria-hidden', 'true');
+
+    this.dimensions = {
+      scaledCharWidth: null,
+      scaledCharHeight: null,
+      scaledCellWidth: null,
+      scaledCellHeight: null,
+      scaledCharLeft: null,
+      scaledCharTop: null,
+      scaledCanvasWidth: null,
+      scaledCanvasHeight: null,
+      canvasWidth: null,
+      canvasHeight: null,
+      actualCellWidth: null,
+      actualCellHeight: null
+    };
+    this._updateDimensions();
+    this._injectCss();
+
+    this._rowFactory = new DomRendererRowFactory(document, this._optionsService);
+
+    this._terminal.element.classList.add(TERMINAL_CLASS_PREFIX + this._terminalClass);
+    this._terminal.screenElement.appendChild(this._rowContainer);
+    this._terminal.screenElement.appendChild(this._selectionContainer);
+
+    this._terminal.linkifier.onLinkHover(e => this._onLinkHover(e));
+    this._terminal.linkifier.onLinkLeave(e => this._onLinkLeave(e));
+  }
+
+  public dispose(): void {
+    this._terminal.element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass);
+    this._terminal.screenElement.removeChild(this._rowContainer);
+    this._terminal.screenElement.removeChild(this._selectionContainer);
+    this._terminal.screenElement.removeChild(this._themeStyleElement);
+    this._terminal.screenElement.removeChild(this._dimensionsStyleElement);
+    super.dispose();
+  }
+
+  private _updateDimensions(): void {
+    this.dimensions.scaledCharWidth = this._charSizeService.width * window.devicePixelRatio;
+    this.dimensions.scaledCharHeight = Math.ceil(this._charSizeService.height * window.devicePixelRatio);
+    this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing);
+    this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight);
+    this.dimensions.scaledCharLeft = 0;
+    this.dimensions.scaledCharTop = 0;
+    this.dimensions.scaledCanvasWidth = this.dimensions.scaledCellWidth * this._terminal.cols;
+    this.dimensions.scaledCanvasHeight = this.dimensions.scaledCellHeight * this._terminal.rows;
+    this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio);
+    this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio);
+    this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols;
+    this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows;
+
+    this._rowElements.forEach(element => {
+      element.style.width = `${this.dimensions.canvasWidth}px`;
+      element.style.height = `${this.dimensions.actualCellHeight}px`;
+      element.style.lineHeight = `${this.dimensions.actualCellHeight}px`;
+      // Make sure rows don't overflow onto following row
+      element.style.overflow = 'hidden';
+    });
+
+    if (!this._dimensionsStyleElement) {
+      this._dimensionsStyleElement = document.createElement('style');
+      this._terminal.screenElement.appendChild(this._dimensionsStyleElement);
+    }
+
+    const styles =
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} span {` +
+        ` display: inline-block;` +
+        ` height: 100%;` +
+        ` vertical-align: top;` +
+        ` width: ${this.dimensions.actualCellWidth}px` +
+        `}`;
+
+    this._dimensionsStyleElement.innerHTML = styles;
+
+    this._selectionContainer.style.height = (<any>this._terminal)._viewportElement.style.height;
+    this._terminal.screenElement.style.width = `${this.dimensions.canvasWidth}px`;
+    this._terminal.screenElement.style.height = `${this.dimensions.canvasHeight}px`;
+  }
+
+  public setColors(colors: IColorSet): void {
+    this._colors = colors;
+    this._injectCss();
+  }
+
+  private _injectCss(): void {
+    if (!this._themeStyleElement) {
+      this._themeStyleElement = document.createElement('style');
+      this._terminal.screenElement.appendChild(this._themeStyleElement);
+    }
+
+    // Base CSS
+    let styles =
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} {` +
+        ` color: ${this._colors.foreground.css};` +
+        ` background-color: ${this._colors.background.css};` +
+        ` font-family: ${this._terminal.options.fontFamily};` +
+        ` font-size: ${this._terminal.options.fontSize}px;` +
+        `}`;
+    // Text styles
+    styles +=
+        `${this._terminalSelector} span:not(.${BOLD_CLASS}) {` +
+        ` font-weight: ${this._terminal.options.fontWeight};` +
+        `}` +
+        `${this._terminalSelector} span.${BOLD_CLASS} {` +
+        ` font-weight: ${this._terminal.options.fontWeightBold};` +
+        `}` +
+        `${this._terminalSelector} span.${ITALIC_CLASS} {` +
+        ` font-style: italic;` +
+        `}`;
+    // Blink animation
+    styles +=
+        `@keyframes blink_box_shadow {` +
+        ` 50% {` +
+        `  box-shadow: none;` +
+        ` }` +
+        `}`;
+    styles +=
+        `@keyframes blink_block {` +
+        ` 0% {` +
+        `  background-color: ${this._colors.cursor.css};` +
+        `  color: ${this._colors.cursorAccent.css};` +
+        ` }` +
+        ` 50% {` +
+        `  background-color: ${this._colors.cursorAccent.css};` +
+        `  color: ${this._colors.cursor.css};` +
+        ` }` +
+        `}`;
+    // Cursor
+    styles +=
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}:not(.${FOCUS_CLASS}) .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +
+        ` outline: 1px solid ${this._colors.cursor.css};` +
+        ` outline-offset: -1px;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}:not(.${CURSOR_STYLE_BLOCK_CLASS}) {` +
+        ` animation: blink_box_shadow 1s step-end infinite;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_BLINK_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +
+        ` animation: blink_block 1s step-end infinite;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS}.${FOCUS_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BLOCK_CLASS} {` +
+        ` background-color: ${this._colors.cursor.css};` +
+        ` color: ${this._colors.cursorAccent.css};` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_BAR_CLASS} {` +
+        ` box-shadow: 1px 0 0 ${this._colors.cursor.css} inset;` +
+        `}` +
+        `${this._terminalSelector} .${ROW_CONTAINER_CLASS} .${CURSOR_CLASS}.${CURSOR_STYLE_UNDERLINE_CLASS} {` +
+        ` box-shadow: 0 -1px 0 ${this._colors.cursor.css} inset;` +
+        `}`;
+    // Selection
+    styles +=
+        `${this._terminalSelector} .${SELECTION_CLASS} {` +
+        ` position: absolute;` +
+        ` top: 0;` +
+        ` left: 0;` +
+        ` z-index: 1;` +
+        ` pointer-events: none;` +
+        `}` +
+        `${this._terminalSelector} .${SELECTION_CLASS} div {` +
+        ` position: absolute;` +
+        ` background-color: ${this._colors.selection.css};` +
+        `}`;
+    // Colors
+    this._colors.ansi.forEach((c, i) => {
+      styles +=
+          `${this._terminalSelector} .${FG_CLASS_PREFIX}${i} { color: ${c.css}; }` +
+          `${this._terminalSelector} .${BG_CLASS_PREFIX}${i} { background-color: ${c.css}; }`;
+    });
+    styles +=
+        `${this._terminalSelector} .${FG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { color: ${this._colors.background.css}; }` +
+        `${this._terminalSelector} .${BG_CLASS_PREFIX}${INVERTED_DEFAULT_COLOR} { background-color: ${this._colors.foreground.css}; }`;
+
+    this._themeStyleElement.innerHTML = styles;
+  }
+
+  public onDevicePixelRatioChange(): void {
+    this._updateDimensions();
+  }
+
+  private _refreshRowElements(cols: number, rows: number): void {
+    // Add missing elements
+    for (let i = this._rowElements.length; i <= rows; i++) {
+      const row = document.createElement('div');
+      this._rowContainer.appendChild(row);
+      this._rowElements.push(row);
+    }
+    // Remove excess elements
+    while (this._rowElements.length > rows) {
+      this._rowContainer.removeChild(this._rowElements.pop());
+    }
+  }
+
+  public onResize(cols: number, rows: number): void {
+    this._refreshRowElements(cols, rows);
+    this._updateDimensions();
+  }
+
+  public onCharSizeChanged(): void {
+    this._updateDimensions();
+  }
+
+  public onBlur(): void {
+    this._rowContainer.classList.remove(FOCUS_CLASS);
+  }
+
+  public onFocus(): void {
+    this._rowContainer.classList.add(FOCUS_CLASS);
+  }
+
+  public onSelectionChanged(start: [number, number], end: [number, number], columnSelectMode: boolean): void {
+    // Remove all selections
+    while (this._selectionContainer.children.length) {
+      this._selectionContainer.removeChild(this._selectionContainer.children[0]);
+    }
+
+    // Selection does not exist
+    if (!start || !end) {
+      return;
+    }
+
+    // Translate from buffer position to viewport position
+    const viewportStartRow = start[1] - this._terminal.buffer.ydisp;
+    const viewportEndRow = end[1] - this._terminal.buffer.ydisp;
+    const viewportCappedStartRow = Math.max(viewportStartRow, 0);
+    const viewportCappedEndRow = Math.min(viewportEndRow, this._terminal.rows - 1);
+
+    // No need to draw the selection
+    if (viewportCappedStartRow >= this._terminal.rows || viewportCappedEndRow < 0) {
+      return;
+    }
+
+    // Create the selections
+    const documentFragment = document.createDocumentFragment();
+
+    if (columnSelectMode) {
+      documentFragment.appendChild(
+        this._createSelectionElement(viewportCappedStartRow, start[0], end[0], viewportCappedEndRow - viewportCappedStartRow + 1)
+      );
+    } else {
+      // Draw first row
+      const startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0;
+      const endCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._terminal.cols;
+      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol));
+      // Draw middle rows
+      const middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1;
+      documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._terminal.cols, middleRowsCount));
+      // Draw final row
+      if (viewportCappedStartRow !== viewportCappedEndRow) {
+        // Only draw viewportEndRow if it's not the same as viewporttartRow
+        const endCol = viewportEndRow === viewportCappedEndRow ? end[0] : this._terminal.cols;
+        documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol));
+      }
+    }
+    this._selectionContainer.appendChild(documentFragment);
+  }
+
+  /**
+   * Creates a selection element at the specified position.
+   * @param row The row of the selection.
+   * @param colStart The start column.
+   * @param colEnd The end columns.
+   */
+  private _createSelectionElement(row: number, colStart: number, colEnd: number, rowCount: number = 1): HTMLElement {
+    const element = document.createElement('div');
+    element.style.height = `${rowCount * this.dimensions.actualCellHeight}px`;
+    element.style.top = `${row * this.dimensions.actualCellHeight}px`;
+    element.style.left = `${colStart * this.dimensions.actualCellWidth}px`;
+    element.style.width = `${this.dimensions.actualCellWidth * (colEnd - colStart)}px`;
+    return element;
+  }
+
+  public onCursorMove(): void {
+    // No-op, the cursor is drawn when rows are drawn
+  }
+
+  public onOptionsChanged(): void {
+    // Force a refresh
+    this._updateDimensions();
+    this._injectCss();
+    this._terminal.refresh(0, this._terminal.rows - 1);
+  }
+
+  public clear(): void {
+    this._rowElements.forEach(e => e.innerHTML = '');
+  }
+
+  public renderRows(start: number, end: number): void {
+    const terminal = this._terminal;
+
+    const cursorAbsoluteY = terminal.buffer.ybase + terminal.buffer.y;
+    const cursorX = this._terminal.buffer.x;
+    const cursorBlink = this._terminal.options.cursorBlink;
+
+    for (let y = start; y <= end; y++) {
+      const rowElement = this._rowElements[y];
+      rowElement.innerHTML = '';
+
+      const row = y + terminal.buffer.ydisp;
+      const lineData = terminal.buffer.lines.get(row);
+      const cursorStyle = terminal.options.cursorStyle;
+      rowElement.appendChild(this._rowFactory.createRow(lineData, row === cursorAbsoluteY, cursorStyle, cursorX, cursorBlink, this.dimensions.actualCellWidth, terminal.cols));
+    }
+  }
+
+  private get _terminalSelector(): string {
+    return `.${TERMINAL_CLASS_PREFIX}${this._terminalClass}`;
+  }
+
+  public registerCharacterJoiner(handler: CharacterJoinerHandler): number { return -1; }
+  public deregisterCharacterJoiner(joinerId: number): boolean { return false; }
+
+  private _onLinkHover(e: ILinkifierEvent): void {
+    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true);
+  }
+
+  private _onLinkLeave(e: ILinkifierEvent): void {
+    this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false);
+  }
+
+  private _setCellUnderline(x: number, x2: number, y: number, y2: number, cols: number, enabled: boolean): void {
+    while (x !== x2 || y !== y2) {
+      const row = this._rowElements[y];
+      if (!row) {
+        return;
+      }
+      const span = <HTMLElement>row.children[x];
+      if (span) {
+        span.style.textDecoration = enabled ? 'underline' : 'none';
+      }
+      if (++x >= cols) {
+        x = 0;
+        y++;
+      }
+    }
+  }
+}
diff --git a/node_modules/xterm/src/tsconfig-base.json b/node_modules/xterm/src/tsconfig-base.json
new file mode 100644 (file)
index 0000000..84d0c92
--- /dev/null
@@ -0,0 +1,13 @@
+{
+  "compilerOptions": {
+    "target": "es5",
+    "lib": [ "es5" ],
+    "rootDir": ".",
+
+    "sourceMap": true,
+    "removeComments": true,
+    "pretty": true,
+
+    "incremental": true
+  }
+}
diff --git a/node_modules/xterm/src/tsconfig-library-base.json b/node_modules/xterm/src/tsconfig-library-base.json
new file mode 100644 (file)
index 0000000..e08695d
--- /dev/null
@@ -0,0 +1,9 @@
+{
+  "extends": "./tsconfig-base.json",
+  "compilerOptions": {
+    "composite": true,
+    "strict": true,
+    "declarationMap": true,
+    "experimentalDecorators": true
+  }
+}
diff --git a/node_modules/xterm/src/tsconfig.json b/node_modules/xterm/src/tsconfig.json
new file mode 100644 (file)
index 0000000..9757666
--- /dev/null
@@ -0,0 +1,34 @@
+{
+  "extends": "./tsconfig-base",
+  "compilerOptions": {
+    "module": "commonjs",
+    "lib": [
+      "dom",
+      "es5",
+      "es6",
+      "scripthost",
+      "es2015.promise"
+    ],
+    "rootDir": ".",
+    "outDir": "../out",
+    "baseUrl": ".",
+    "paths": {
+      "common/*": [ "./common/*" ],
+      "browser/*": [ "./browser/*" ]
+    },
+
+    "noUnusedLocals": true,
+    "noImplicitAny": true
+  },
+  "include": [
+    "./**/*",
+    "../typings/xterm.d.ts"
+  ],
+  "exclude": [
+    "./addons/**/*"
+  ],
+  "references": [
+    { "path": "./common" },
+    { "path": "./browser" }
+  ]
+}
diff --git a/node_modules/xterm/tsconfig.all.json b/node_modules/xterm/tsconfig.all.json
new file mode 100644 (file)
index 0000000..7ddf33d
--- /dev/null
@@ -0,0 +1,14 @@
+{
+  "files": [],
+  "include": [],
+  "references": [
+    { "path": "./src" },
+    { "path": "./test/api" },
+    { "path": "./test/benchmark" },
+    { "path": "./addons/xterm-addon-attach/src" },
+    { "path": "./addons/xterm-addon-fit/src" },
+    { "path": "./addons/xterm-addon-search/src" },
+    { "path": "./addons/xterm-addon-web-links/src" },
+    { "path": "./addons/xterm-addon-webgl/src" }
+  ]
+}
diff --git a/node_modules/xterm/typings/xterm.d.ts b/node_modules/xterm/typings/xterm.d.ts
new file mode 100644 (file)
index 0000000..295a03b
--- /dev/null
@@ -0,0 +1,1105 @@
+/**
+ * @license MIT
+ *
+ * This contains the type declarations for the xterm.js library. Note that
+ * some interfaces differ between this file and the actual implementation in
+ * src/, that's because this file declares the *public* API which is intended
+ * to be stable and consumed by external programs.
+ */
+
+/// <reference lib="dom"/>
+
+declare module 'xterm' {
+  /**
+   * A string representing text font weight.
+   */
+  export type FontWeight = 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
+
+  /**
+   * A string representing log level.
+   */
+  export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';
+
+  /**
+   * A string representing a renderer type.
+   */
+  export type RendererType = 'dom' | 'canvas';
+
+  /**
+   * An object containing start up options for the terminal.
+   */
+  export interface ITerminalOptions {
+    /**
+     * Whether background should support non-opaque color. It must be set before
+     * executing the `Terminal.open()` method and can't be changed later without
+     * executing it again. Note that enabling this can negatively impact
+     * performance.
+     */
+    allowTransparency?: boolean;
+
+    /**
+     * A data uri of the sound to use for the bell when `bellStyle = 'sound'`.
+     */
+    bellSound?: string;
+
+    /**
+     * The type of the bell notification the terminal will use.
+     */
+    bellStyle?: 'none' /*| 'visual'*/ | 'sound' /*| 'both'*/;
+
+    /**
+     * When enabled the cursor will be set to the beginning of the next line
+     * with every new line. This equivalent to sending '\r\n' for each '\n'.
+     * Normally the termios settings of the underlying PTY deals with the
+     * translation of '\n' to '\r\n' and this setting should not be used. If you
+     * deal with data from a non-PTY related source, this settings might be
+     * useful.
+     */
+    convertEol?: boolean;
+
+    /**
+     * The number of columns in the terminal.
+     */
+    cols?: number;
+
+    /**
+     * Whether the cursor blinks.
+     */
+    cursorBlink?: boolean;
+
+    /**
+     * The style of the cursor.
+     */
+    cursorStyle?: 'block' | 'underline' | 'bar';
+
+    /**
+     * Whether input should be disabled.
+     */
+    disableStdin?: boolean;
+
+    /**
+     * Whether to draw bold text in bright colors. The default is true.
+     */
+    drawBoldTextInBrightColors?: boolean;
+
+    /**
+     * The modifier key hold to multiply scroll speed.
+     */
+    fastScrollModifier?: 'alt' | 'ctrl' | 'shift' | undefined;
+
+    /**
+     * The scroll speed multiplier used for fast scrolling.
+     */
+    fastScrollSensitivity?: number;
+
+    /**
+     * The font size used to render text.
+     */
+    fontSize?: number;
+
+    /**
+     * The font family used to render text.
+     */
+    fontFamily?: string;
+
+    /**
+     * The font weight used to render non-bold text.
+     */
+    fontWeight?: FontWeight;
+
+    /**
+     * The font weight used to render bold text.
+     */
+    fontWeightBold?: FontWeight;
+
+    /**
+     * The spacing in whole pixels between characters..
+     */
+    letterSpacing?: number;
+
+    /**
+     * The line height used to render text.
+     */
+    lineHeight?: number;
+
+    /**
+     * What log level to use, this will log for all levels below and including
+     * what is set:
+     *
+     * 1. debug
+     * 2. info (default)
+     * 3. warn
+     * 4. error
+     * 5. off
+     */
+    logLevel?: LogLevel;
+
+    /**
+     * Whether to treat option as the meta key.
+     */
+    macOptionIsMeta?: boolean;
+
+    /**
+     * Whether holding a modifier key will force normal selection behavior,
+     * regardless of whether the terminal is in mouse events mode. This will
+     * also prevent mouse events from being emitted by the terminal. For
+     * example, this allows you to use xterm.js' regular selection inside tmux
+     * with mouse mode enabled.
+     */
+    macOptionClickForcesSelection?: boolean;
+
+    /**
+     * The type of renderer to use, this allows using the fallback DOM renderer
+     * when canvas is too slow for the environment. The following features do
+     * not work when the DOM renderer is used:
+     *
+     * - Letter spacing
+     * - Cursor blink
+     */
+    rendererType?: RendererType;
+
+    /**
+     * Whether to select the word under the cursor on right click, this is
+     * standard behavior in a lot of macOS applications.
+     */
+    rightClickSelectsWord?: boolean;
+
+    /**
+     * The number of rows in the terminal.
+     */
+    rows?: number;
+
+    /**
+     * Whether screen reader support is enabled. When on this will expose
+     * supporting elements in the DOM to support NVDA on Windows and VoiceOver
+     * on macOS.
+     */
+    screenReaderMode?: boolean;
+
+    /**
+     * The amount of scrollback in the terminal. Scrollback is the amount of
+     * rows that are retained when lines are scrolled beyond the initial
+     * viewport.
+     */
+    scrollback?: number;
+
+    /**
+     * The scrolling speed multiplier used for adjusting normal scrolling speed.
+     */
+    scrollSensitivity?: number;
+
+    /**
+     * The size of tab stops in the terminal.
+     */
+    tabStopWidth?: number;
+
+    /**
+     * The color theme of the terminal.
+     */
+    theme?: ITheme;
+
+    /**
+     * Whether "Windows mode" is enabled. Because Windows backends winpty and
+     * conpty operate by doing line wrapping on their side, xterm.js does not
+     * have access to wrapped lines. When Windows mode is enabled the following
+     * changes will be in effect:
+     *
+     * - Reflow is disabled.
+     * - Lines are assumed to be wrapped if the last character of the line is
+     *   not whitespace.
+     */
+    windowsMode?: boolean;
+
+    /**
+     * A string containing all characters that are considered word separated by the
+     * double click to select work logic.
+    */
+    wordSeparator?: string;
+  }
+
+  /**
+   * Contains colors to theme the terminal with.
+   */
+  export interface ITheme {
+    /** The default foreground color */
+    foreground?: string;
+    /** The default background color */
+    background?: string;
+    /** The cursor color */
+    cursor?: string;
+    /** The accent color of the cursor (fg color for a block cursor) */
+    cursorAccent?: string;
+    /** The selection background color (can be transparent) */
+    selection?: string;
+    /** ANSI black (eg. `\x1b[30m`) */
+    black?: string;
+    /** ANSI red (eg. `\x1b[31m`) */
+    red?: string;
+    /** ANSI green (eg. `\x1b[32m`) */
+    green?: string;
+    /** ANSI yellow (eg. `\x1b[33m`) */
+    yellow?: string;
+    /** ANSI blue (eg. `\x1b[34m`) */
+    blue?: string;
+    /** ANSI magenta (eg. `\x1b[35m`) */
+    magenta?: string;
+    /** ANSI cyan (eg. `\x1b[36m`) */
+    cyan?: string;
+    /** ANSI white (eg. `\x1b[37m`) */
+    white?: string;
+    /** ANSI bright black (eg. `\x1b[1;30m`) */
+    brightBlack?: string;
+    /** ANSI bright red (eg. `\x1b[1;31m`) */
+    brightRed?: string;
+    /** ANSI bright green (eg. `\x1b[1;32m`) */
+    brightGreen?: string;
+    /** ANSI bright yellow (eg. `\x1b[1;33m`) */
+    brightYellow?: string;
+    /** ANSI bright blue (eg. `\x1b[1;34m`) */
+    brightBlue?: string;
+    /** ANSI bright magenta (eg. `\x1b[1;35m`) */
+    brightMagenta?: string;
+    /** ANSI bright cyan (eg. `\x1b[1;36m`) */
+    brightCyan?: string;
+    /** ANSI bright white (eg. `\x1b[1;37m`) */
+    brightWhite?: string;
+  }
+
+  /**
+   * An object containing options for a link matcher.
+   */
+  export interface ILinkMatcherOptions {
+    /**
+     * The index of the link from the regex.match(text) call. This defaults to 0
+     * (for regular expressions without capture groups).
+     */
+    matchIndex?: number;
+
+    /**
+     * A callback that validates whether to create an individual link, pass
+     * whether the link is valid to the callback.
+     */
+    validationCallback?: (uri: string, callback: (isValid: boolean) => void) => void;
+
+    /**
+     * A callback that fires when the mouse hovers over a link for a moment.
+     */
+    tooltipCallback?: (event: MouseEvent, uri: string, location: IViewportRange) => boolean | void;
+
+    /**
+     * A callback that fires when the mouse leaves a link. Note that this can
+     * happen even when tooltipCallback hasn't fired for the link yet.
+     */
+    leaveCallback?: () => void;
+
+    /**
+     * The priority of the link matcher, this defines the order in which the
+     * link matcher is evaluated relative to others, from highest to lowest. The
+     * default value is 0.
+     */
+    priority?: number;
+
+    /**
+     * A callback that fires when the mousedown and click events occur that
+     * determines whether a link will be activated upon click. This enables
+     * only activating a link when a certain modifier is held down, if not the
+     * mouse event will continue propagation (eg. double click to select word).
+     */
+    willLinkActivate?: (event: MouseEvent, uri: string) => boolean;
+  }
+
+  /**
+   * An object that can be disposed via a dispose function.
+   */
+  export interface IDisposable {
+    dispose(): void;
+  }
+
+  /**
+   * An event that can be listened to.
+   * @returns an `IDisposable` to stop listening.
+   */
+  export interface IEvent<T> {
+    (listener: (e: T) => any): IDisposable;
+  }
+
+  /**
+   * Represents a specific line in the terminal that is tracked when scrollback
+   * is trimmed and lines are added or removed. This is a single line that may
+   * be part of a larger wrapped line.
+   */
+  export interface IMarker extends IDisposable {
+    /**
+     * A unique identifier for this marker.
+     */
+    readonly id: number;
+
+    /**
+     * Whether this marker is disposed.
+     */
+    readonly isDisposed: boolean;
+
+    /**
+     * The actual line index in the buffer at this point in time. This is set to
+     * -1 if the marker has been disposed.
+     */
+    readonly line: number;
+  }
+
+  /**
+   * The set of localizable strings.
+   */
+  export interface ILocalizableStrings {
+    /**
+     * The aria label for the underlying input textarea for the terminal.
+     */
+    promptLabel: string;
+
+    /**
+     * Announcement for when line reading is suppressed due to too many lines
+     * being printed to the terminal when `screenReaderMode` is enabled.
+     */
+    tooMuchOutput: string;
+  }
+
+  /**
+   * The class that represents an xterm.js terminal.
+   */
+  export class Terminal implements IDisposable {
+    /**
+     * The element containing the terminal.
+     */
+    readonly element: HTMLElement | undefined;
+
+    /**
+     * The textarea that accepts input for the terminal.
+     */
+    readonly textarea: HTMLTextAreaElement | undefined;
+
+    /**
+     * The number of rows in the terminal's viewport. Use
+     * `ITerminalOptions.rows` to set this in the constructor and
+     * `Terminal.resize` for when the terminal exists.
+     */
+    readonly rows: number;
+
+    /**
+     * The number of columns in the terminal's viewport. Use
+     * `ITerminalOptions.cols` to set this in the constructor and
+     * `Terminal.resize` for when the terminal exists.
+     */
+    readonly cols: number;
+
+    /**
+     * (EXPERIMENTAL) The terminal's current buffer, this might be either the
+     * normal buffer or the alt buffer depending on what's running in the
+     * terminal.
+     */
+    readonly buffer: IBuffer;
+
+    /**
+     * (EXPERIMENTAL) Get all markers registered against the buffer. If the alt
+     * buffer is active this will always return [].
+     */
+    readonly markers: ReadonlyArray<IMarker>;
+
+    /**
+     * (EXPERIMENTAL) Get the parser interface to register
+     * custom escape sequence handlers.
+     */
+    readonly parser: IParser;
+
+    /**
+     * Natural language strings that can be localized.
+     */
+    static strings: ILocalizableStrings;
+
+    /**
+     * Creates a new `Terminal` object.
+     *
+     * @param options An object containing a set of options.
+     */
+    constructor(options?: ITerminalOptions);
+
+    /**
+     * Adds an event listener for the cursor moves.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onCursorMove: IEvent<void>;
+
+    /**
+     * Adds an event listener for when a data event fires. This happens for
+     * example when the user types or pastes into the terminal. The event value
+     * is whatever `string` results, in a typical setup, this should be passed
+     * on to the backing pty.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onData: IEvent<string>;
+
+    /**
+     * Adds an event listener for a key is pressed. The event value contains the
+     * string that will be sent in the data event as well as the DOM event that
+     * triggered it.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onKey: IEvent<{ key: string, domEvent: KeyboardEvent }>;
+
+    /**
+     * Adds an event listener for when a line feed is added.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onLineFeed: IEvent<void>;
+
+    /**
+     * Adds an event listener for when a scroll occurs. The event value is the
+     * new position of the viewport.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onScroll: IEvent<number>;
+
+    /**
+     * Adds an event listener for when a selection change occurs.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onSelectionChange: IEvent<void>;
+
+    /**
+     * Adds an event listener for when rows are rendered. The event value
+     * contains the start row and end rows of the rendered area (ranges from `0`
+     * to `Terminal.rows - 1`).
+     * @returns an `IDisposable` to stop listening.
+     */
+    onRender: IEvent<{ start: number, end: number }>;
+
+    /**
+     * Adds an event listener for when the terminal is resized. The event value
+     * contains the new size.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onResize: IEvent<{ cols: number, rows: number }>;
+
+    /**
+     * Adds an event listener for when an OSC 0 or OSC 2 title change occurs.
+     * The event value is the new title.
+     * @returns an `IDisposable` to stop listening.
+     */
+    onTitleChange: IEvent<string>;
+
+    /**
+     * Unfocus the terminal.
+     */
+    blur(): void;
+
+    /**
+     * Focus the terminal.
+     */
+    focus(): void;
+
+    /**
+     * Resizes the terminal. It's best practice to debounce calls to resize,
+     * this will help ensure that the pty can respond to the resize event
+     * before another one occurs.
+     * @param x The number of columns to resize to.
+     * @param y The number of rows to resize to.
+     */
+    resize(columns: number, rows: number): void;
+
+    /**
+     * Opens the terminal within an element.
+     * @param parent The element to create the terminal within. This element
+     * must be visible (have dimensions) when `open` is called as several DOM-
+     * based measurements need to be performed when this function is called.
+     */
+    open(parent: HTMLElement): void;
+
+    /**
+     * Attaches a custom key event handler which is run before keys are
+     * processed, giving consumers of xterm.js ultimate control as to what keys
+     * should be processed by the terminal and what keys should not.
+     * @param customKeyEventHandler The custom KeyboardEvent handler to attach.
+     * This is a function that takes a KeyboardEvent, allowing consumers to stop
+     * propagation and/or prevent the default action. The function returns
+     * whether the event should be processed by xterm.js.
+     */
+    attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void;
+
+    /**
+     * (EXPERIMENTAL) Registers a link matcher, allowing custom link patterns to
+     * be matched and handled.
+     * @param regex The regular expression to search for, specifically this
+     * searches the textContent of the rows. You will want to use \s to match a
+     * space ' ' character for example.
+     * @param handler The callback when the link is called.
+     * @param options Options for the link matcher.
+     * @return The ID of the new matcher, this can be used to deregister.
+     */
+    registerLinkMatcher(regex: RegExp, handler: (event: MouseEvent, uri: string) => void, options?: ILinkMatcherOptions): number;
+
+    /**
+     * (EXPERIMENTAL) Deregisters a link matcher if it has been registered.
+     * @param matcherId The link matcher's ID (returned after register)
+     */
+    deregisterLinkMatcher(matcherId: number): void;
+
+    /**
+     * (EXPERIMENTAL) Registers a character joiner, allowing custom sequences of
+     * characters to be rendered as a single unit. This is useful in particular
+     * for rendering ligatures and graphemes, among other things.
+     *
+     * Each registered character joiner is called with a string of text
+     * representing a portion of a line in the terminal that can be rendered as
+     * a single unit. The joiner must return a sorted array, where each entry is
+     * itself an array of length two, containing the start (inclusive) and end
+     * (exclusive) index of a substring of the input that should be rendered as
+     * a single unit. When multiple joiners are provided, the results of each
+     * are collected. If there are any overlapping substrings between them, they
+     * are combined into one larger unit that is drawn together.
+     *
+     * All character joiners that are registered get called every time a line is
+     * rendered in the terminal, so it is essential for the handler function to
+     * run as quickly as possible to avoid slowdowns when rendering. Similarly,
+     * joiners should strive to return the smallest possible substrings to
+     * render together, since they aren't drawn as optimally as individual
+     * characters.
+     *
+     * NOTE: character joiners are only used by the canvas renderer.
+     *
+     * @param handler The function that determines character joins. It is called
+     * with a string of text that is eligible for joining and returns an array
+     * where each entry is an array containing the start (inclusive) and end
+     * (exclusive) indexes of ranges that should be rendered as a single unit.
+     * @return The ID of the new joiner, this can be used to deregister
+     */
+    registerCharacterJoiner(handler: (text: string) => [number, number][]): number;
+
+    /**
+     * (EXPERIMENTAL) Deregisters the character joiner if one was registered.
+     * NOTE: character joiners are only used by the canvas renderer.
+     * @param joinerId The character joiner's ID (returned after register)
+     */
+    deregisterCharacterJoiner(joinerId: number): void;
+
+    /**
+     * (EXPERIMENTAL) Adds a marker to the normal buffer and returns it. If the
+     * alt buffer is active, undefined is returned.
+     * @param cursorYOffset The y position offset of the marker from the cursor.
+     */
+    addMarker(cursorYOffset: number): IMarker;
+
+    /**
+     * Gets whether the terminal has an active selection.
+     */
+    hasSelection(): boolean;
+
+    /**
+     * Gets the terminal's current selection, this is useful for implementing
+     * copy behavior outside of xterm.js.
+     */
+    getSelection(): string;
+
+    /**
+     * Gets the selection position or undefined if there is no selection.
+     */
+    getSelectionPosition(): ISelectionPosition | undefined;
+
+    /**
+     * Clears the current terminal selection.
+     */
+    clearSelection(): void;
+
+    /**
+     * Selects text within the terminal.
+     * @param column The column the selection starts at..
+     * @param row The row the selection starts at.
+     * @param length The length of the selection.
+     */
+    select(column: number, row: number, length: number): void;
+
+    /**
+     * Selects all text within the terminal.
+     */
+    selectAll(): void;
+
+    /**
+     * Selects text in the buffer between 2 lines.
+     * @param start The 0-based line index to select from (inclusive).
+     * @param end The 0-based line index to select to (inclusive).
+     */
+    selectLines(start: number, end: number): void;
+
+    /*
+     * Disposes of the terminal, detaching it from the DOM and removing any
+     * active listeners.
+     */
+    dispose(): void;
+
+    /**
+     * Scroll the display of the terminal
+     * @param amount The number of lines to scroll down (negative scroll up).
+     */
+    scrollLines(amount: number): void;
+
+    /**
+     * Scroll the display of the terminal by a number of pages.
+     * @param pageCount The number of pages to scroll (negative scrolls up).
+     */
+    scrollPages(pageCount: number): void;
+
+    /**
+     * Scrolls the display of the terminal to the top.
+     */
+    scrollToTop(): void;
+
+    /**
+     * Scrolls the display of the terminal to the bottom.
+     */
+    scrollToBottom(): void;
+
+    /**
+     * Scrolls to a line within the buffer.
+     * @param line The 0-based line index to scroll to.
+     */
+    scrollToLine(line: number): void;
+
+    /**
+     * Clear the entire buffer, making the prompt line the new first line.
+     */
+    clear(): void;
+
+    /**
+     * Write data to the terminal.
+     * @param data The data to write to the terminal. This can either be raw
+     * bytes given as Uint8Array from the pty or a string. Raw bytes will always
+     * be treated as UTF-8 encoded, string data as UTF-16.
+     * @param callback Optional callback that fires when the data was processed
+     * by the parser.
+     */
+    write(data: string | Uint8Array, callback?: () => void): void;
+
+    /**
+     * Writes data to the terminal, followed by a break line character (\n).
+     * @param data The data to write to the terminal. This can either be raw
+     * bytes given as Uint8Array from the pty or a string. Raw bytes will always
+     * be treated as UTF-8 encoded, string data as UTF-16.
+     * @param callback Optional callback that fires when the data was processed
+     * by the parser.
+     */
+    writeln(data: string | Uint8Array, callback?: () => void): void;
+
+    /**
+     * Write UTF8 data to the terminal.
+     * @param data The data to write to the terminal.
+     * @param callback Optional callback when data was processed.
+     * @deprecated use `write` instead
+     */
+    writeUtf8(data: Uint8Array, callback?: () => void): void;
+
+    /**
+     * Writes text to the terminal, performing the necessary transformations for pasted text.
+     * @param data The text to write to the terminal.
+     */
+    paste(data: string): void;
+
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'logLevel' | 'rendererType' | 'termName' | 'wordSeparator'): string;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell' | 'windowsMode'): boolean;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'colors'): string[];
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'cols' | 'fontSize' | 'letterSpacing' | 'lineHeight' | 'rows' | 'tabStopWidth' | 'scrollback'): number;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: 'handler'): (data: string) => void;
+    /**
+     * Retrieves an option's value from the terminal.
+     * @param key The option key.
+     */
+    getOption(key: string): any;
+
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'fontFamily' | 'termName' | 'bellSound' | 'wordSeparator', value: string): void;
+    /**
+    * Sets an option on the terminal.
+    * @param key The option key.
+    * @param value The option value.
+    */
+    setOption(key: 'fontWeight' | 'fontWeightBold', value: null | 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'): void;
+    /**
+    * Sets an option on the terminal.
+    * @param key The option key.
+    * @param value The option value.
+    */
+    setOption(key: 'logLevel', value: LogLevel): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'bellStyle', value: null | 'none' | 'visual' | 'sound' | 'both'): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'cursorStyle', value: null | 'block' | 'underline' | 'bar'): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'disableStdin' | 'macOptionIsMeta' | 'popOnBell' | 'rightClickSelectsWord' | 'screenKeys' | 'useFlowControl' | 'visualBell' | 'windowsMode', value: boolean): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'colors', value: string[]): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'fontSize' | 'letterSpacing' | 'lineHeight' | 'tabStopWidth' | 'scrollback', value: number): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'handler', value: (data: string) => void): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'theme', value: ITheme): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: 'cols' | 'rows', value: number): void;
+    /**
+     * Sets an option on the terminal.
+     * @param key The option key.
+     * @param value The option value.
+     */
+    setOption(key: string, value: any): void;
+
+    /**
+     * Tells the renderer to refresh terminal content between two rows
+     * (inclusive) at the next opportunity.
+     * @param start The row to start from (between 0 and this.rows - 1).
+     * @param end The row to end at (between start and this.rows - 1).
+     */
+    refresh(start: number, end: number): void;
+
+    /**
+     * Perform a full reset (RIS, aka '\x1bc').
+     */
+    reset(): void;
+
+    /**
+     * Loads an addon into this instance of xterm.js.
+     * @param addon The addon to load.
+     */
+    loadAddon(addon: ITerminalAddon): void;
+  }
+
+  /**
+   * An addon that can provide additional functionality to the terminal.
+   */
+  export interface ITerminalAddon extends IDisposable {
+    /**
+     * This is called when the addon is activated.
+     */
+    activate(terminal: Terminal): void;
+  }
+
+  /**
+   * An object representing a selection within the terminal.
+   */
+  interface ISelectionPosition {
+    /**
+     * The start column of the selection.
+     */
+    startColumn: number;
+
+    /**
+     * The start row of the selection.
+     */
+    startRow: number;
+
+    /**
+     * The end column of the selection.
+     */
+    endColumn: number;
+
+    /**
+     * The end row of the selection.
+     */
+    endRow: number;
+  }
+
+  /**
+   * An object representing a range within the viewport of the terminal.
+   */
+  export interface IViewportRange {
+    /**
+     * The start of the range.
+     */
+    start: IViewportRangePosition;
+
+    /**
+     * The end of the range.
+     */
+    end: IViewportRangePosition;
+  }
+
+  /**
+   * An object representing a cell position within the viewport of the terminal.
+   */
+  interface IViewportRangePosition {
+    /**
+     * The x position of the cell. This is a 0-based index that refers to the
+     * space in between columns, not the column itself. Index 0 refers to the
+     * left side of the viewport, index `Terminal.cols` refers to the right side
+     * of the viewport. This can be thought of as how a cursor is positioned in
+     * a text editor.
+     */
+    x: number;
+
+    /**
+     * The y position of the cell. This is a 0-based index that refers to a
+     * specific row.
+     */
+    y: number;
+  }
+
+  /**
+   * Represents a terminal buffer.
+   */
+  interface IBuffer {
+    /**
+     * The y position of the cursor. This ranges between `0` (when the
+     * cursor is at baseY) and `Terminal.rows - 1` (when the cursor is on the
+     * last row).
+     */
+    readonly cursorY: number;
+
+    /**
+     * The x position of the cursor. This ranges between `0` (left side) and
+     * `Terminal.cols - 1` (right side).
+     */
+    readonly cursorX: number;
+
+    /**
+     * The line within the buffer where the top of the viewport is.
+     */
+    readonly viewportY: number;
+
+    /**
+     * The line within the buffer where the top of the bottom page is (when
+     * fully scrolled down);
+     */
+    readonly baseY: number;
+
+    /**
+     * The amount of lines in the buffer.
+     */
+    readonly length: number;
+
+    /**
+     * Gets a line from the buffer, or undefined if the line index does not
+     * exist.
+     *
+     * Note that the result of this function should be used immediately after
+     * calling as when the terminal updates it could lead to unexpected
+     * behavior.
+     *
+     * @param y The line index to get.
+     */
+    getLine(y: number): IBufferLine | undefined;
+  }
+
+  /**
+   * Represents a line in the terminal's buffer.
+   */
+  interface IBufferLine {
+    /**
+     * Whether the line is wrapped from the previous line.
+     */
+    readonly isWrapped: boolean;
+
+    /**
+     * Gets a cell from the line, or undefined if the line index does not exist.
+     *
+     * Note that the result of this function should be used immediately after
+     * calling as when the terminal updates it could lead to unexpected
+     * behavior.
+     *
+     * @param x The character index to get.
+     */
+    getCell(x: number): IBufferCell | undefined;
+
+    /**
+     * Gets the line as a string. Note that this is gets only the string for the
+     * line, not taking isWrapped into account.
+     *
+     * @param trimRight Whether to trim any whitespace at the right of the line.
+     * @param startColumn The column to start from (inclusive).
+     * @param endColumn The column to end at (exclusive).
+     */
+    translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string;
+  }
+
+  /**
+   * Represents a single cell in the terminal's buffer.
+   */
+  interface IBufferCell {
+    /**
+     * The character within the cell.
+     */
+    readonly char: string;
+
+    /**
+     * The width of the character. Some examples:
+     *
+     * - This is `1` for most cells.
+     * - This is `2` for wide character like CJK glyphs.
+     * - This is `0` for cells immediately following cells with a width of `2`.
+     */
+    readonly width: number;
+  }
+
+  /**
+   * (EXPERIMENTAL) Data type to register a CSI, DCS or ESC callback in the parser
+   * in the form:
+   *    ESC I..I F
+   *    CSI Prefix P..P I..I F
+   *    DCS Prefix P..P I..I F data_bytes ST
+   *
+   * with these rules/restrictions:
+   * - prefix can only be used with CSI and DCS
+   * - only one leading prefix byte is recognized by the parser
+   *   before any other parameter bytes (P..P)
+   * - intermediate bytes are recognized up to 2
+   *
+   * For custom sequences make sure to read ECMA-48 and the resources at
+   * vt100.net to not clash with existing sequences or reserved address space.
+   * General recommendations:
+   * - use private address space (see ECMA-48)
+   * - use max one intermediate byte (technically not limited by the spec,
+   *   in practice there are no sequences with more than one intermediate byte,
+   *   thus parsers might get confused with more intermediates)
+   * - test against other common emulators to check whether they escape/ignore
+   *   the sequence correctly
+   *
+   * Notes: OSC command registration is handled differently (see addOscHandler)
+   *        APC, PM or SOS is currently not supported.
+   */
+  export interface IFunctionIdentifier {
+    /**
+     * Optional prefix byte, must be in range \x3c .. \x3f.
+     * Usable in CSI and DCS.
+     */
+    prefix?: string;
+    /**
+     * Optional intermediate bytes, must be in range \x20 .. \x2f.
+     * Usable in CSI, DCS and ESC.
+     */
+    intermediates?: string;
+    /**
+     * Final byte, must be in range \x40 .. \x7e for CSI and DCS,
+     * \x30 .. \x7e for ESC.
+     */
+    final: string;
+  }
+
+  /**
+   * (EXPERIMENTAL) Parser interface.
+   */
+  export interface IParser {
+    /**
+     * Adds a handler for CSI escape sequences.
+     * @param id Specifies the function identifier under which the callback
+     * gets registered, e.g. {final: 'm'} for SGR.
+     * @param callback The function to handle the sequence. The callback is
+     * called with the numerical params. If the sequence has subparams the
+     * array will contain subarrays with their numercial values.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addCsiHandler or setCsiHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addCsiHandler(id: IFunctionIdentifier, callback: (params: (number | number[])[]) => boolean): IDisposable;
+
+    /**
+     * Adds a handler for DCS escape sequences.
+     * @param id Specifies the function identifier under which the callback
+     * gets registered, e.g. {intermediates: '$' final: 'q'} for DECRQSS.
+     * @param callback The function to handle the sequence. Note that the
+     * function will only be called once if the sequence finished sucessfully.
+     * There is currently no way to intercept smaller data chunks, data chunks
+     * will be stored up until the sequence is finished. Since DCS sequences
+     * are not limited by the amount of data this might impose a problem for
+     * big payloads. Currently xterm.js limits DCS payload to 10 MB
+     * which should give enough room for most use cases.
+     * The function gets the payload and numerical parameters as arguments.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addDcsHandler or setDcsHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: (number | number[])[]) => boolean): IDisposable;
+
+    /**
+     * Adds a handler for ESC escape sequences.
+     * @param id Specifies the function identifier under which the callback
+     * gets registered, e.g. {intermediates: '%' final: 'G'} for
+     * default charset selection.
+     * @param callback The function to handle the sequence.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addEscHandler or setEscHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addEscHandler(id: IFunctionIdentifier, handler: () => boolean): IDisposable;
+
+    /**
+     * Adds a handler for OSC escape sequences.
+     * @param ident The number (first parameter) of the sequence.
+     * @param callback The function to handle the sequence. Note that the
+     * function will only be called once if the sequence finished sucessfully.
+     * There is currently no way to intercept smaller data chunks, data chunks
+     * will be stored up until the sequence is finished. Since OSC sequences
+     * are not limited by the amount of data this might impose a problem for
+     * big payloads. Currently xterm.js limits OSC payload to 10 MB
+     * which should give enough room for most use cases.
+     * The callback is called with OSC data string.
+     * Return true if the sequence was handled; false if we should try
+     * a previous handler (set by addOscHandler or setOscHandler).
+     * The most recently-added handler is tried first.
+     * @return An IDisposable you can call to remove this handler.
+     */
+    addOscHandler(ident: number, callback: (data: string) => boolean): IDisposable;
+  }
+}
index 072e61e8ec8a4231a9918fdb2761358d82d40328..e231888305ea033abbb49f688d344db78c84f9f5 100644 (file)
@@ -18,6 +18,7 @@ app.use(express.json());
 app.use('/styles', express.static('styles'));
 app.use('/js', express.static('js'));
 app.use('/img', express.static('img'));
+app.use('/node_modules', express.static('node_modules'));
 //rutas
 app.use(require('./routes/index'));
 // Configurar cabeceras y cors
diff --git a/src/views/starter.ejs b/src/views/starter.ejs
deleted file mode 100644 (file)
index 1098809..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-<!DOCTYPE html>
-<html>
-
-<head>
-  <title></title>
-  <!-- <link rel="stylesheet" type="text/css" href="/styles/main.css" /> -->
-  <%include ../../partials/head%>
-  <link rel="stylesheet" type="text/css" href="/styles/starter.css" />
-
-</head>
-<header>
-  <%include ../../partials/header%>
-</header>
-
-<body>
-
-  <main>
-    <div class="side">
-
-      <div class="panel">
-        <textarea class="text" rows="20" cols="7" id="comandos" placeholder="Definicion de la red como: H1:S1"></textarea>
-        <div class="buttons">
-          <button type="button" name="button" onclick="startvsorc()">Iniciar VSoRC</button>
-          <button type="button" name="button" onclick="stopvsorc()">Detener VSoRC</button>
-          <button type="button" name="button" onclick="startcontroller()">Iniciar controlador</button>
-          <button type="button" name="button" onclick="stopcontroller()">Detener controlador</button>
-        </div>
-      </div>
-
-      <div class="panel">
-        <textarea class="text" disabled rows="20" cols="7" id="vsorcout" placeholder="Salida del sistema de consola"></textarea>
-        <div class="buttons">
-          <button type="button" name="button" onclick="startvsorc()">Ping all</button>
-          <button type="button" name="button" onclick="stopvsorc()">Placement</button>
-          <button type="button" name="button" onclick="startcontroller()">Iperf3</button>
-        </div>
-      </div>
-
-    </div>
-
-    <div class="side">
-
-      <div class="panel">
-        <textarea class="text" disabled rows="20" cols="7" id="vsorcout" placeholder="Salida del controlador"></textarea>
-      </div>
-
-      <div class="panel">
-
-      </div>
-
-    </div>
-
-    <script type="text/javascript">
-      let topo = document.getElementById('comandos') //Donde van escrito el DSL
-
-
-
-      function stopcontroller() {
-        let xhr = new XMLHttpRequest();
-        xhr.open('GET', '/stopcontroller', true);
-        xhr.onload = function() {
-          if (xhr.status == 200) { //can use this.status instead
-            //console.log(xhr.responseText);// para ver en la consola
-            console.log("controller stoped");
-          }
-        }
-        xhr.send();
-
-      }
-
-      function startcontroller() {
-        let xhr = new XMLHttpRequest();
-        xhr.open('GET', '/startcontroller', true);
-        //console.log(xhr); //para ver en la consola
-        xhr.onload = function() {
-          if (xhr.status == 200) { //can use this.status instead
-
-            console.log("controller started");
-          }
-        }
-        xhr.send();
-      }
-
-      function startvsorc() {
-        let xhr = new XMLHttpRequest();
-        topology = JSON.stringify(topo.value)
-        xhr.open('GET', '/startvsorc?topology=' + topology, true);
-        xhr.onload = function() {
-          if (xhr.status == 200) { //can use this.status instead
-            //console.log(xhr.responseText);// para ver en la consola
-            console.log("vsorc started");
-          }
-        }
-
-        xhr.send();
-
-      }
-
-      function stopvsorc() {
-        let xhr = new XMLHttpRequest();
-        xhr.open('GET', '/stopvsorc', true);
-        xhr.onload = function() {
-          if (xhr.status == 200) { //can use this.status instead
-            //console.log(xhr.responseText);// para ver en la consola
-            console.log("vsorc stopped");
-          }
-        }
-        xhr.send();
-      }
-    </script>
-  </main>
-</body>
-<footer>
-  <%include ../../partials/footer%>
-</footer>
-
-
-</html>
\ No newline at end of file